├── .gitignore ├── MANIFEST.in ├── doc └── .bugzillarc.sample ├── bzlib ├── __init__.py ├── test_bug.py ├── config.py ├── editor.py ├── test_ui.py ├── test_bugzilla.py ├── bugzilla.py ├── ui.py ├── bug.py └── command.py ├── setup.py ├── bin └── bugzilla ├── plugin-bzr ├── __init__.py └── hooks.py ├── README.rst ├── CHANGES └── gpl-3.0.txt /.gitignore: -------------------------------------------------------------------------------- 1 | MANIFEST 2 | *.pyc 3 | /build/ 4 | /dist/ 5 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include MANIFEST.in 2 | include README.rst 3 | include gpl-3.0.txt 4 | include CHANGES 5 | -------------------------------------------------------------------------------- /doc/.bugzillarc.sample: -------------------------------------------------------------------------------- 1 | [core] 2 | server = example 3 | 4 | [server.example] 5 | url = http://bugzilla.example.com 6 | user = user@example.com 7 | password = sekrit 8 | 9 | [alias] 10 | fix = status --status RESOLVED --resolution FIXED 11 | wfm = status --status RESOLVED --resolution WORKSFORME 12 | confirm = status --status CONFIRMED 13 | -------------------------------------------------------------------------------- /bzlib/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of bugzillatools 2 | # Copyright (C) 2011, 2012, 2013, 2014, 2015 Fraser Tweedale 3 | # Copyright (C) 2011, 2012 Benon Technologies Pty Ltd 4 | # 5 | # bugzillatools is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | version_info = (0, 5, 5, 'final', 0) 19 | 20 | version_fmt = '{0}.{1}' 21 | if version_info[2]: 22 | version_fmt += '.{2}' 23 | if version_info[3] != 'final': 24 | version_fmt += '{3}{4}' 25 | elif version_info[4]: 26 | version_fmt += '.{4}' 27 | version = version_fmt.format(*version_info) 28 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import distutils.core 2 | import sys 3 | 4 | import bzlib # import version info 5 | 6 | with open('README.rst') as fh: 7 | readme = fh.read() 8 | with open('CHANGES') as fh: 9 | changes = fh.read() 10 | long_description = '\n\n'.join((readme, changes)) 11 | 12 | distutils.core.setup( 13 | name='bugzillatools', 14 | version=bzlib.version, 15 | description='Bugzilla CLI client, XML-RPC binding and VCS plugins', 16 | author='Fraser Tweedale', 17 | author_email='frase@frase.id.au', 18 | url='https://github.com/frasertweedale/bugzillatools', 19 | packages=['bzlib', 'bzrlib.plugins.bugzillatools'], 20 | package_dir={ 21 | 'bzlib': 'bzlib', 22 | 'bzrlib.plugins.bugzillatools': 'plugin-bzr', 23 | }, 24 | scripts=['bin/bugzilla'], 25 | data_files=[ 26 | ('doc/bugzillatools', ['doc/.bugzillarc.sample']), 27 | ], 28 | classifiers=[ 29 | 'Development Status :: 4 - Beta', 30 | 'Environment :: Console', 31 | 'Intended Audience :: Developers', 32 | 'Intended Audience :: Information Technology', 33 | 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 34 | 'Operating System :: OS Independent', 35 | 'Programming Language :: Python :: 2.7', 36 | 'Topic :: Software Development :: Bug Tracking', 37 | 'Topic :: Software Development :: Version Control', 38 | ], 39 | long_description=long_description, 40 | ) 41 | -------------------------------------------------------------------------------- /bzlib/test_bug.py: -------------------------------------------------------------------------------- 1 | # This file is part of bugzillatools 2 | # Copyright (C) 2013 Fraser Tweedale 3 | # Copyright (C) 2011 Benon Technologies Pty Ltd 4 | # 5 | # bugzillatools is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | import socket 19 | import unittest 20 | 21 | from . import bugzilla 22 | from . import bug 23 | 24 | 25 | class BugTestCase(unittest.TestCase): 26 | def setUp(self): 27 | self.bz = bugzilla.Bugzilla('http://bugzilla.example.com/', 'u', 'p') 28 | 29 | def test_search(self): 30 | with self.assertRaisesRegexp(TypeError, r'\bfoobar\b'): 31 | bug.Bug.search(self.bz, foobar='baz') 32 | with self.assertRaisesRegexp(TypeError, r'\bfoobar\b'): 33 | bug.Bug.search(self.bz, not_foobar='baz') 34 | fields = frozenset([ 35 | 'alias', 'assigned_to', 'component', 'creation_time', 'creator', 36 | 'id', 'last_change_time', 'op_sys', 'rep_platform', 'priority', 37 | 'product', 'resolution', 'severity', 'status', 'summary', 38 | 'target_milestone', 'qa_contact', 'url', 'version', 'whiteboard', 39 | 'limit', 'offset', 40 | ]) 41 | with self.assertRaises(socket.gaierror): 42 | bug.Bug.search(self.bz, **{field: 'foo' for field in fields}) 43 | with self.assertRaises(socket.gaierror): 44 | bug.Bug.search( 45 | self.bz, 46 | **{field: 'not_' + 'foo' for field in fields} 47 | ) 48 | -------------------------------------------------------------------------------- /bzlib/config.py: -------------------------------------------------------------------------------- 1 | # This file is part of bugzillatools 2 | # Copyright (C) 2011 Benon Technologies Pty Ltd, Fraser Tweedale 3 | # 4 | # bugzillatools is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | try: 18 | import ConfigParser 19 | except ImportError: 20 | import configparser as ConfigParser 21 | import os.path 22 | import re 23 | 24 | 25 | show_fields = [ 26 | 'alias', 'assigned_to', 'blocks', 'cc', 'creator', 'depends_on', 27 | 'keywords', 'priority', 'component', 'resolution', 'status', 28 | 'summary', 29 | ] 30 | 31 | 32 | class ConfigError(Exception): 33 | pass 34 | 35 | 36 | def check_section(section): 37 | if section in ['core', 'alias'] \ 38 | or re.match(r'server\.\w+', section): 39 | return section 40 | raise ConfigError('invalid section: {}'.format(section)) 41 | 42 | 43 | class Config(ConfigParser.SafeConfigParser): 44 | _instances = {} 45 | 46 | @classmethod 47 | def get_config(cls, path): 48 | path = os.path.expanduser(path) 49 | if path not in cls._instances: 50 | cls._instances[path] = cls(path) 51 | return cls._instances[path] 52 | 53 | def __init__(self, path): 54 | path = os.path.expanduser(path) 55 | ConfigParser.SafeConfigParser.__init__(self) 56 | self._path = path 57 | self.read(self._path) 58 | 59 | def write(self): 60 | with open(self._path, 'w') as fp: 61 | ConfigParser.SafeConfigParser.write(self, fp) 62 | 63 | def add_section(self, section): 64 | ConfigParser.SafeConfigParser.add_section(self, check_section(section)) 65 | 66 | 67 | NoSectionError = ConfigParser.NoSectionError 68 | -------------------------------------------------------------------------------- /bzlib/editor.py: -------------------------------------------------------------------------------- 1 | # This file is part of bugzillatools 2 | # Copyright (C) 2011, 2013 Fraser Tweedale 3 | # Copyright (C) 2011 Benon Technologies Pty Ltd 4 | # 5 | # bugzillatools is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | import os 19 | import subprocess 20 | import tempfile 21 | import textwrap 22 | 23 | 24 | class EmptyInputError(Exception): 25 | pass 26 | 27 | 28 | def input(message, remove_comments=True): 29 | """Invoke ``$EDITOR`` for message input. 30 | 31 | Invoke ``$EDITOR`` or vi(1) on a temporary file for user input. 32 | 33 | ``message`` 34 | A message describing what the user is inputting. Should be 35 | terminated with a full stop. 36 | ``remove_comments`` 37 | Remove lines starting with '#' from the data. 38 | 39 | """ 40 | try: 41 | editor = [os.environ['EDITOR']] 42 | except KeyError: 43 | editor = ['/usr/bin/env', 'vi'] 44 | 45 | # build initial text 46 | text = [message.encode('utf-8')] 47 | if remove_comments: 48 | text.append("Lines starting with '#' will be ignored.") 49 | text.append('An empty message aborts the operation.') 50 | 51 | lines = ['\n'] # start with a single empty line 52 | lines += map('# {}\n'.format, textwrap.wrap(' '.join(text))) 53 | 54 | with tempfile.NamedTemporaryFile() as fh: 55 | fh.writelines(lines) 56 | fh.flush() 57 | returncode = subprocess.call(editor + [fh.name]) 58 | if returncode: 59 | raise IOError('Editor did not exit cleanly') 60 | fh.seek(0) 61 | lines = fh.readlines() 62 | if remove_comments: 63 | lines = filter(lambda x: not x or x[0] != '#', lines) 64 | if not lines or not lines[0] and len(lines) == 1: 65 | # no lines, or a single empty line 66 | raise EmptyInputError() 67 | return ''.join(lines) 68 | -------------------------------------------------------------------------------- /bin/bugzilla: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # bugzilla - a command line interface to Bugzilla 4 | # Copyright (C) 2011, 2012 Benon Technologies Pty Ltd 5 | # Copyright (C) 2011, 2012 Fraser Tweedale 6 | # 7 | # bugzillatools is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # This program is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with this program. If not, see . 19 | 20 | 21 | import argparse 22 | 23 | import bzlib.command 24 | import bzlib.config 25 | import bzlib.ui 26 | 27 | # retrieve user-defined aliases 28 | conf = bzlib.config.Config.get_config('~/.bugzillarc') 29 | if conf.has_section('alias'): 30 | aliases = dict(conf.items('alias')) 31 | else: 32 | aliases = {} 33 | 34 | # format the epilogue 35 | epilog = None 36 | lines = map( 37 | lambda (alias, target): " {:20}{}".format(alias, target), 38 | aliases.viewitems() 39 | ) 40 | epilog = 'user-defined aliases:\n' + '\n'.join(lines) if lines else None 41 | 42 | # create an argument parser 43 | _parser = argparse.ArgumentParser(add_help=False) 44 | 45 | # add global arguments 46 | _parser.add_argument('-V', action='version', 47 | version='%(prog)s {}'.format(bzlib.version)) 48 | 49 | # parse known args 50 | args, argv = _parser.parse_known_args() 51 | 52 | # add subcommands 53 | parser = argparse.ArgumentParser( 54 | parents=[_parser], 55 | description='Interact with Bugzilla servers.', 56 | epilog=epilog, 57 | formatter_class=argparse.RawDescriptionHelpFormatter 58 | ) 59 | subparsers = parser.add_subparsers(title='subcommands') 60 | commands = {x.__name__.lower(): x for x in bzlib.command.commands} 61 | for name, command in sorted(commands.viewitems(), key=lambda x: x[0]): 62 | command_parser = subparsers.add_parser(name, 63 | formatter_class=argparse.RawDescriptionHelpFormatter, 64 | help=command.help(), epilog=command.epilog()) 65 | map(lambda x: x(command_parser), command.args) 66 | command_parser.set_defaults(command=command) 67 | 68 | # process user-defined aliases 69 | for i, arg in enumerate(argv): 70 | if arg in aliases: 71 | # an alias; replace and stop processing 72 | argv[i:i+1] = aliases[arg].split() 73 | break 74 | if arg in commands: 75 | # a valid command; stop processing 76 | break 77 | 78 | # parse remaining args 79 | args = parser.parse_args(args=argv, namespace=args) 80 | 81 | # execute command 82 | ui = bzlib.ui.UI() 83 | args.command(args, parser, commands, aliases, ui)() 84 | -------------------------------------------------------------------------------- /bzlib/test_ui.py: -------------------------------------------------------------------------------- 1 | # This file is part of bugzillatools 2 | # Copyright (C) 2012 Fraser Tweedale 3 | # 4 | # bugzillatools is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | import unittest 18 | 19 | from . import ui 20 | 21 | 22 | class FilterTestCase(unittest.TestCase): 23 | """Test filter functions.""" 24 | 25 | def test_filter_int(self): 26 | # 'start' arg 27 | with self.assertRaisesRegexp(ui.InvalidInputError, 'value too small'): 28 | ui.filter_int('0', start=1) 29 | self.assertEqual(ui.filter_int('0', start=0), 0) 30 | 31 | # 'stop' arg 32 | with self.assertRaisesRegexp(ui.InvalidInputError, 'value too large'): 33 | ui.filter_int('2', stop=2) 34 | self.assertEqual(ui.filter_int('1', stop=2), 1) 35 | 36 | # bogus input 37 | with self.assertRaisesRegexp(ui.InvalidInputError, 'not an int'): 38 | ui.filter_int('a') 39 | 40 | # default 41 | with self.assertRaisesRegexp(ui.InvalidInputError, 'not an int'): 42 | ui.filter_int('') 43 | self.assertEqual(ui.filter_int('', default=100), 100) 44 | 45 | def test_filter_list(self): 46 | # no filter 47 | with self.assertRaisesRegexp(TypeError, r'\bfilter\b'): 48 | ui.filter_list('1 2 3') 49 | 50 | # duplicates 51 | with self.assertRaisesRegexp( 52 | ui.InvalidInputError, 53 | 'duplicate values are not allowed' 54 | ): 55 | ui.filter_list( 56 | '1 1 1', 57 | filter=ui.filter_int, 58 | allow_duplicates=False 59 | ) 60 | self.assertEqual( 61 | ui.filter_list( 62 | '1 1 1', 63 | filter=ui.filter_int, 64 | allow_duplicates=True, 65 | filter_duplicates=False 66 | ), 67 | [1, 1, 1] 68 | ) 69 | self.assertEqual( 70 | ui.filter_list( 71 | '1 1 1', 72 | filter=ui.filter_int, 73 | allow_duplicates=True, 74 | filter_duplicates=True 75 | ), 76 | [1] 77 | ) 78 | 79 | # min, max allowed 80 | with self.assertRaisesRegexp(ui.InvalidInputError, 'too few'): 81 | ui.filter_list('1 2 3', filter=ui.filter_int, min_allowed=4) 82 | ui.filter_list('1 2 3', filter=ui.filter_int, min_allowed=3) 83 | with self.assertRaisesRegexp(ui.InvalidInputError, 'too many'): 84 | ui.filter_list('1 2 3', filter=ui.filter_int, max_allowed=2) 85 | ui.filter_list('1 2 3', filter=ui.filter_int, max_allowed=3) 86 | 87 | # bogus values 88 | with self.assertRaises(ui.InvalidInputError): 89 | ui.filter_list('a b c', filter=ui.filter_int) 90 | 91 | # delimiter checks 92 | self.assertEqual( 93 | ui.filter_list(' 1,,2::3;;4 5\t\t6:;,7 ', filter=ui.filter_int), 94 | [1, 2, 3, 4, 5, 6, 7] 95 | ) 96 | self.assertEqual(ui.filter_list(' ', filter=ui.filter_int), []) 97 | 98 | # empty (no default) 99 | self.assertEqual(ui.filter_list('', filter=ui.filter_int), []) 100 | 101 | # empty (with default) 102 | self.assertEqual( 103 | ui.filter_list('', filter=ui.filter_int, default=[3, 2, 1]), 104 | [3, 2, 1] 105 | ) 106 | -------------------------------------------------------------------------------- /plugin-bzr/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of bugzillatools 2 | # Copyright (C) 2010-2011 Benon Technologies Pty Ltd 3 | # 4 | # bugzillatools is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | """Mark bugzilla bugs fixed using --fixes argument. 18 | 19 | Description 20 | ----------- 21 | 22 | This plugin, when enabled for Bugzilla bugtrackers, marks bugs fixed on 23 | those trackers when ``bzr commit`` is invoked with the ``--fixes`` argument. 24 | It also adds a comment to the bug that includes the branch location, the 25 | commit message, the list of changed files and other details about the commit. 26 | 27 | Configuration 28 | ------------- 29 | 30 | Define the bugtracker in your ``bazaar.conf`` in the normal fashion, and 31 | enable *bugzillatools* for that tracker. 32 | 33 | bugzilla__url = 34 | bugzilla__bugzillatools_enable = True 35 | 36 | The type of ``bugzilla__bugzillatools_enable`` is actually string, 37 | not boolean, so to explicitly disable the plugin leave the line blank after 38 | the ``=``. 39 | 40 | If the handle matches a server in your ``.bugzillarc``, no further 41 | configuration is needed; the parameters from this file will be used. The 42 | URLs should not differ between the two configuration files, but if they do, 43 | ``.bugzillarc`` takes precendence. 44 | 45 | If the handle does not match a server in your ``.bugzillarc``, the Bugzilla 46 | URL, user and password are determined thusly: 47 | 48 | - For the url, the value of ``bugzilla__url``. 49 | - For the username, ``bugzilla__user`` or if this is not defined, the 50 | email address of the committer. 51 | - For the password, ``bugzilla__password``, which must be defined. 52 | 53 | The status and resolution of "fixed" bugs must also be specified for each 54 | tracker, since these are configurable and may differ between installations 55 | of Bugzilla. For example, in your ``bazaar.conf``:: 56 | 57 | bugzilla__status = RESOLVED 58 | bugzilla__resolution = FIXED 59 | 60 | Example 61 | ------- 62 | 63 | A Bugzilla server at ``http://bugzilla.example.com``, with user 64 | ``bob@example.com`` and password ``bob123``. 65 | 66 | ``.bugzillarc``:: 67 | 68 | ... 69 | "servers": { 70 | "example": ["http://bugzilla.example.com", "bob@example.com", "bob123"] 71 | } 72 | ... 73 | 74 | ``bazaar.conf``:: 75 | 76 | bugzilla_example_url = http://bugzilla.example.com/ 77 | bugzilla_example_bugzillatools_enable = True 78 | bugzilla_example_status = RESOLVED 79 | bugzilla_example_resolution = FIXED 80 | 81 | If not defining ``example`` in ``.bugzillarc``, also include:: 82 | 83 | bugzilla_example_password = bob123 84 | 85 | and, if Bob is not committing as ``bob@example.com``, also include:: 86 | 87 | bugzilla_example_user = bob@example.com 88 | 89 | To mark a bug fixed (in addition to the standard behaviour of recording 90 | a bug URL and status in the revision metadata), invoke Bazaar thusly:: 91 | 92 | bzr commit -m 'fix bug 123' --fixes example:123 93 | """ 94 | 95 | import bzrlib.api 96 | import bzrlib.commands 97 | import bzrlib.trace 98 | 99 | import bzlib 100 | 101 | from . import hooks 102 | 103 | # plugin setup 104 | version_info = bzlib.version_info 105 | 106 | COMPATIBLE_BZR_VERSIONS = [ 107 | (2, 0, 0), 108 | (2, 1, 0), 109 | (2, 2, 0), 110 | (2, 3, 0), 111 | ] 112 | 113 | bzrlib.api.require_any_api(bzrlib, COMPATIBLE_BZR_VERSIONS) 114 | 115 | if __name__ != 'bzrlib.plugins.bugzillatools': 116 | bzrlib.trace.warning( 117 | 'Not running as bzrlib.plugins.bugzillatools; things may break.') 118 | 119 | # install the get_command hook 120 | bzrlib.commands.Command.hooks.install_named_hook( 121 | 'get_command', 122 | hooks.get_command_hook, 123 | 'bugzilla plugin - extend cmd_commit' 124 | ) 125 | -------------------------------------------------------------------------------- /bzlib/test_bugzilla.py: -------------------------------------------------------------------------------- 1 | # This file is part of bugzillatools 2 | # Copyright (C) 2011 Fraser Tweedale, Benon Technologies Pty Ltd 3 | # 4 | # bugzillatools is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | import itertools 18 | import os 19 | import tempfile 20 | import unittest 21 | 22 | from . import bugzilla 23 | from . import config 24 | 25 | 26 | class URLTestCase(unittest.TestCase): 27 | """Test Bugzilla URL handling.""" 28 | 29 | def testScheme(self): 30 | # http 31 | self.assertIsInstance( 32 | bugzilla.Bugzilla('http://bugzilla.example.com/', 'u', 'p'), 33 | bugzilla.Bugzilla 34 | ) 35 | # https 36 | self.assertIsInstance( 37 | bugzilla.Bugzilla('https://bugzilla.example.com/', 'u', 'p'), 38 | bugzilla.Bugzilla 39 | ) 40 | # bogus scheme 41 | with self.assertRaises(bugzilla.URLError) as cm: 42 | bugzilla.Bugzilla('bogus://bugzilla.example.com/', 'u', 'p') 43 | self.assertEqual( 44 | str(cm.exception), 45 | "URL scheme 'bogus' not supported." 46 | ) 47 | 48 | def testNetloc(self): 49 | urls = [ 50 | '', 51 | 'http:example.com' 52 | ] 53 | for url in urls: 54 | with self.assertRaises(bugzilla.URLError) as cm: 55 | bugzilla.Bugzilla(url, 'u', 'p') 56 | self.assertEqual( 57 | str(cm.exception), 58 | 'URL {!r} is not valid.'.format(url) 59 | ) 60 | 61 | def testParamQueryFragment(self): 62 | # param 63 | with self.assertRaises(bugzilla.URLError) as cm: 64 | bugzilla.Bugzilla('http://bugzilla.example.com/;p', 'u', 'p') 65 | self.assertEqual( 66 | str(cm.exception), 67 | 'URL params, queries and fragments not supported.' 68 | ) 69 | # query 70 | with self.assertRaises(bugzilla.URLError) as cm: 71 | bugzilla.Bugzilla('http://bugzilla.example.com/?q', 'u', 'p') 72 | self.assertEqual( 73 | str(cm.exception), 74 | 'URL params, queries and fragments not supported.' 75 | ) 76 | # fragment 77 | with self.assertRaises(bugzilla.URLError) as cm: 78 | bugzilla.Bugzilla('http://bugzilla.example.com/#f', 'u', 'p') 79 | self.assertEqual( 80 | str(cm.exception), 81 | 'URL params, queries and fragments not supported.' 82 | ) 83 | 84 | def testXMLRPC(self): 85 | host = 'bugzilla.example.com' 86 | 87 | # no trailing '/' 88 | bz = bugzilla.Bugzilla('http://' + host, 'u', 'p') 89 | self.assertEquals(bz.server._ServerProxy__host, host) 90 | self.assertEquals(bz.server._ServerProxy__handler, '/xmlrpc.cgi') 91 | 92 | # trailing '/' 93 | bz = bugzilla.Bugzilla('http://' + host + '/', 'u', 'p') 94 | self.assertEquals(bz.server._ServerProxy__host, host) 95 | self.assertEquals(bz.server._ServerProxy__handler, '/xmlrpc.cgi') 96 | 97 | 98 | class FromConfigTestCase(unittest.TestCase): 99 | def setUp(self): 100 | fd, self._path = tempfile.mkstemp() 101 | os.close(fd) 102 | with open(self._path, 'w') as f: 103 | f.write( 104 | '[core]\n' 105 | 'server = test\n' 106 | '[server.test]\n' 107 | 'url = http://bugzilla.example.com/\n' 108 | 'user = jbloggs\n' 109 | 'password = letmein\n' 110 | 'foo = bar\n' 111 | ) 112 | self._conf = config.Config.get_config(self._path) 113 | 114 | def tearDown(self): 115 | del self._conf 116 | os.remove(self._path) 117 | del self._path 118 | 119 | def test_from_config_type(self): 120 | """Test that all mandatory args are checked.""" 121 | mandatory_args = set(['server', 'url', 'user', 'password']) 122 | for args in itertools.combinations(mandatory_args, 2): 123 | with self.assertRaisesRegexp(TypeError, '[Mm]andatory'): 124 | bugzilla.Bugzilla.from_config( 125 | self._conf, 126 | **{k: None for k in args} 127 | ) 128 | kwargs = {k: None for k in mandatory_args} 129 | kwargs['server'] = 'test' 130 | 131 | def test_from_config(self): 132 | """Test that from_config produces correctly initialised instance.""" 133 | mandatory_args = set(['server', 'url', 'user', 'password']) 134 | kwargs = {k: None for k in mandatory_args} 135 | kwargs['server'] = 'test' 136 | bz = bugzilla.Bugzilla.from_config(self._conf, **kwargs) 137 | self.assertEqual(bz.url, 'http://bugzilla.example.com/') 138 | self.assertEqual(bz.user, 'jbloggs') 139 | self.assertEqual(bz.password, 'letmein') 140 | self.assertEqual(bz.config, {'foo': 'bar'}) 141 | 142 | def test_from_config_with_default_server(self): 143 | """Test that the default server gets used.""" 144 | mandatory_args = set(['server', 'url', 'user', 'password']) 145 | kwargs = {k: None for k in mandatory_args} 146 | bz = bugzilla.Bugzilla.from_config(self._conf, **kwargs) 147 | self.assertEqual(bz.url, 'http://bugzilla.example.com/') 148 | -------------------------------------------------------------------------------- /plugin-bzr/hooks.py: -------------------------------------------------------------------------------- 1 | # This file is part of bugzillatools 2 | # Copyright (C) 2010-2011 Benon Technologies Pty Ltd 3 | # 4 | # bugzillatools is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | import functools 18 | import StringIO 19 | 20 | import bzlib.bugzilla 21 | import bzlib.config 22 | 23 | import bzrlib.builtins 24 | import bzrlib.branch 25 | import bzrlib.bugtracker 26 | import bzrlib.config 27 | import bzrlib.log 28 | import bzrlib.trace 29 | 30 | conf = bzlib.config.Config.get_config('~/.bugzillarc') 31 | 32 | 33 | def post_commit_hook( 34 | local, master, old_revno, old_revid, new_revno, new_revid, # bzrlib args 35 | fixes=None # this one get curried using functools.partial 36 | ): 37 | """This hook marks fixed bugzilla bugs specified by --fixes arguments.""" 38 | branch = local or master 39 | config = branch.get_config() 40 | revision = branch.repository.get_revision(new_revid) 41 | status_by_url = dict(revision.iter_bugs()) 42 | 43 | # store bugzilla tasks 44 | bugs = [] 45 | 46 | # since we made it to post-commit, all the bugtracker handles are valid 47 | for tag, bug in map(lambda x: x.split(':'), fixes or []): 48 | enabled = config.get_user_option( 49 | 'bugzilla_%s_bugzillatools_enable' % tag 50 | ) 51 | if not enabled: 52 | continue # bugzillatools not enabled for this tracker 53 | 54 | tracker = bzrlib.bugtracker.tracker_registry.get_tracker(tag, branch) 55 | UPIBT = bzrlib.bugtracker.URLParametrizedIntegerBugTracker 56 | if not isinstance(tracker, UPIBT) or tracker.type_name != 'bugzilla': 57 | continue # tracker is not a bugzilla tracker 58 | 59 | if status_by_url[tracker.get_bug_url(bug)] != bzrlib.bugtracker.FIXED: 60 | # bzrlib only groks fixed for now, but if other statuses come 61 | # along this will filter them out 62 | continue 63 | 64 | # see if bzlib knows about this server 65 | url, user, password = None, None, None 66 | try: 67 | server = dict(conf.items('server.' + tag)) 68 | url, user, password = \ 69 | [server.get(k) for k in 'url', 'user', 'password'] 70 | except bzlib.config.NoSectionError: 71 | pass # server not defined 72 | 73 | # url falls back to bzr config (tracker url) 74 | # 75 | # ugly hack: API doesn't expose the tracker URL, but _base_url property 76 | # is defined for URLParametrizedBugTracker, which bugzilla trackers are 77 | url = url or tracker._base_url 78 | 79 | # user falls back to bzr config, then committer 80 | user = user \ 81 | or config.get_user_option('bugzilla_%s_user' % tag) \ 82 | or bzrlib.config.extract_email_address(revision.committer) 83 | 84 | # password falls back to bzr config 85 | password = password \ 86 | or config.get_user_option('bugzilla_%s_password' % tag) 87 | if not password: 88 | bzrlib.trace.warning( 89 | "Password not defined for bugtracker '{}'.".format(tag) 90 | ) 91 | continue 92 | 93 | # get status and resolution 94 | status = config.get_user_option('bugzilla_%s_status' % tag) 95 | resolution = config.get_user_option('bugzilla_%s_resolution' % tag) 96 | if not (status and resolution): 97 | bzrlib.trace.warning( 98 | "Status or resolution not defined for bugtracker '{}'.".format( 99 | tag 100 | ) 101 | ) 102 | continue 103 | 104 | bugs.append([bug, url, user, password, status, resolution]) 105 | 106 | if not bugs: 107 | return # nothing to do 108 | 109 | # assemble the comment 110 | outf = StringIO.StringIO() 111 | # show master branch (i.e. bound location if a bound branch) 112 | outf.write('Fixed in commit at:\n %s\n\n' % master.base) 113 | lf = bzrlib.log.log_formatter('long', show_ids=True, to_file=outf) 114 | bzrlib.log.show_log( 115 | branch, 116 | lf, 117 | start_revision=new_revno, 118 | end_revision=new_revno, 119 | verbose=True 120 | ) 121 | msg = outf.getvalue() 122 | print 'message:\n', msg 123 | 124 | for bug, url, user, password, status, resolution in bugs: 125 | print 'Setting status of bug {} on {} to {} {}'.format( 126 | bug, url, status, resolution 127 | ) 128 | bz = bzlib.bugzilla.Bugzilla(url, user, password) 129 | try: 130 | bz.bug(bug).set_status(status, resolution, msg) 131 | except Exception as e: 132 | bzrlib.trace.show_error('Bugtracker error: ' + str(e)) 133 | 134 | 135 | def get_command_hook(cmd_or_None, command_name): 136 | """Enhance the ``commit`` command.""" 137 | if isinstance(cmd_or_None, bzrlib.builtins.cmd_commit): 138 | class cmd_commit(type(cmd_or_None)): 139 | """Commit command that saves bug state. 140 | 141 | This is a tiny shim around the builtin commit command that 142 | simply saves information about fixed bugs (if any are given 143 | on the command line) for later use in the post_commit hook 144 | provided by this plugin. 145 | """ 146 | def __init__(self, *args, **kwargs): 147 | self.__doc__ = super(cmd_commit, self).__doc__ 148 | super(cmd_commit, self).__init__(*args, **kwargs) 149 | 150 | def run(self, *args, **kwargs): 151 | if kwargs['fixes']: 152 | # curry the post-commit hook with fixes and install it 153 | bzrlib.branch.Branch.hooks.install_named_hook( 154 | 'post_commit', 155 | functools.partial( 156 | post_commit_hook, 157 | fixes=kwargs['fixes'] 158 | ), 159 | 'Check fixed bugs' 160 | ) 161 | super(cmd_commit, self).run(*args, **kwargs) 162 | 163 | return cmd_commit() 164 | 165 | return cmd_or_None 166 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | bugzillatools consists of the ``bugzilla`` CLI program and a Python 2 | library for interacting with the Bugzilla_ bug tracking system, and 3 | plugins for version control systems that enable interaction with 4 | Bugzilla installations. 5 | 6 | The only dependency is Python_ 2.7 and bugzillatools works with 7 | Bugzilla_ 4.0 or later where the XML-RPC feature is enabled. 8 | 9 | .. _Bugzilla: http://www.bugzilla.org/ 10 | .. _Python: http://python.org/ 11 | 12 | 13 | Installation 14 | ============ 15 | 16 | :: 17 | 18 | # via pip 19 | pip install bugzillatools # as superuser 20 | -or- 21 | pip install bugzillatools --user # user site-packages installation 22 | 23 | # from source 24 | python setup.py install # as superuser 25 | -or- 26 | python setup.py install --user # user site-packages installation 27 | 28 | The ``bin/`` directory in your user base directory will need to appear 29 | on the ``PATH`` if installing to user site-packages. This directory is 30 | system dependent; see :pep:`370`. 31 | 32 | If installing to user site-packages, some manual moving or symlinking 33 | of files will be required for the Bazaar plugin to be detected by 34 | Bazaar. :pep:`402` speaks to this shortcoming. 35 | 36 | 37 | Components 38 | ========== 39 | 40 | ``bugzilla`` program 41 | -------------------- 42 | 43 | Command-line application for interacting with Bugzilla servers. 44 | The following subcommands are available: 45 | 46 | :assign: Assign bugs to the given user. 47 | :block: Show or update block list of given bugs. 48 | :cc: Show or update CC List. 49 | :comment: List comments or file a comment on the given bugs. 50 | :config: Show or update configuration. 51 | :depend: Show or update dependencies of given bugs. 52 | :desc: Show the description of the given bug(s). 53 | :dump: Print internal representation of bug data. 54 | :edit: Edit the given bugs. 55 | :fields: List valid values for bug fields. 56 | :help: Show help. 57 | :history: Show the history of the given bugs. 58 | :info: Show detailed information about the given bugs. 59 | :list: Show a one-line summary of the given bugs. 60 | :new: File a new bug. 61 | :priority: Set the priority on the given bugs. 62 | :products: List the products of a Bugzilla instance. 63 | :search: Search for bugs matching given criteria. 64 | :status: Set the status of the given bugs. 65 | :time: Show or adjust times and estimates for the given bugs. 66 | 67 | 68 | ``bzlib`` 69 | --------- 70 | 71 | Library providing access to Bugzilla instances through the XML-RPC 72 | interface. Supports bug creation, bug information and comment 73 | retrieval, updating bug fields and appending comments to bugs. 74 | 75 | 76 | Bazaar_ plugin 77 | -------------- 78 | 79 | This plugin, when enabled for Bugzilla bugtrackers, marks bugs fixed on 80 | those trackers when ``bzr commit`` is invoked with the ``--fixes`` argument. 81 | It also adds a comment to the bug that includes the branch location, the 82 | commit message, the list of changed files and other details about the commit. 83 | 84 | The Bazaar_ plugin requires Bazaar 2.0 or later. 85 | 86 | .. _Bazaar: http://bazaar.canonical.com/ 87 | 88 | 89 | Configuration 90 | ============= 91 | 92 | ``.bugzillarc`` 93 | --------------- 94 | 95 | The ``bugzilla`` program looks for its configuration in 96 | ``~/.bugzillarc``, which uses ini-style configuration. 97 | 98 | ``core`` 99 | ^^^^^^^^ 100 | 101 | ``server`` 102 | Name of the default server 103 | 104 | ``alias`` 105 | ^^^^^^^^^ 106 | 107 | Option names are aliases; their values are the replacement. 108 | 109 | ``server.`` 110 | ^^^^^^^^^^^^^^^^^ 111 | 112 | Define a server. bugzillatools supports multiple servers; the 113 | ``--server=`` argument can be used to select a server. 114 | 115 | ``url`` 116 | Base URL of the Bugzilla server (mandatory) 117 | ``user`` 118 | Bugzilla username (optional) 119 | ``password`` 120 | Bugzilla password (optional) 121 | ``assign_status`` 122 | When the ``assign`` command is used, if the current status of a bug 123 | is in the first list, the status will be updated to the second item. 124 | The format is: ``[,]* ``. An 125 | appropriate value for the default Bugzilla workflow might be: 126 | ``"UNCONFIRMED,CONFIRMED IN_PROGRESS"``. 127 | ``default_product`` 128 | If provided and if the provided string corresponds to the name of a 129 | product on this server, use that product as the default. The user 130 | will still be prompted to confirm. 131 | 132 | 133 | Example ``.bugzillarc`` 134 | ^^^^^^^^^^^^^^^^^^^^^^^ 135 | 136 | :: 137 | 138 | [core] 139 | server = example 140 | 141 | [server.example] 142 | url = http://bugzilla.example.com 143 | user = user@example.com 144 | password = sekrit 145 | 146 | [alias] 147 | fix = status --status RESOLVED --resolution FIXED 148 | wfm = status --status RESOLVED --resolution WORKSFORME 149 | confirm = status --status CONFIRMED 150 | 151 | 152 | Bazaar plugin 153 | ------------- 154 | 155 | To enable the Bazaar bugzillatools plugin, include following 156 | configuration directives in either ``~/.bazaar/bazaar.conf`` (global 157 | configuration) or ``.bzr/branch/branch.conf`` (within a branch):: 158 | 159 | bugzilla__bugzillatools_enable = True 160 | bugzilla__url = 161 | bugzilla__status = RESOLVED 162 | bugzilla__resolution = FIXED 163 | 164 | Such a configuration assumes that a section ``[server.]`` 165 | has been defined in your ``.bugzillarc``. 166 | 167 | You can now set the status of bugs (using the status and resolution 168 | defined in the Bazaar config) directly:: 169 | 170 | bzr commit -m 'fix bug 123' --fixes :123 171 | 172 | 173 | License 174 | ======= 175 | 176 | bugzillatools is free software: you can redistribute it and/or modify 177 | it under the terms of the GNU General Public License as published by 178 | the Free Software Foundation, either version 3 of the License, or 179 | (at your option) any later version. 180 | 181 | 182 | Contributing 183 | ============ 184 | 185 | The bugzillatools source code is available from 186 | https://github.com/frasertweedale/bugzillatools. 187 | 188 | Bug reports, patches, feature requests, code review and 189 | documentation are welcomed. 190 | 191 | To submit a patch, please use ``git send-email`` or generate a pull 192 | request. Write a `well formed commit message`_. If your patch is 193 | nontrivial, update the copyright notice at the top of each changed 194 | file. 195 | 196 | .. _well formed commit message: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html 197 | -------------------------------------------------------------------------------- /CHANGES: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | v0.5.5 :: Sat Apr 25 2015 5 | ------------------------- 6 | 7 | New features: 8 | 9 | - ``comment`` command learned the ``--private`` option 10 | (contributed by Johannes Segitz) 11 | 12 | Bug fixes: 13 | 14 | - fix comment enumeration order 15 | - fix string encoding error when invoking editor which could lead to invalid 16 | XML being sent to server 17 | 18 | 19 | v0.5.4 :: Sun Nov 23 2014 20 | ------------------------- 21 | 22 | Bug fixes: 23 | 24 | - better error messages on missing server/account configuration (#3) 25 | - remove fields without name data from bug records (#5) 26 | - make user and password configuration optional (#12) 27 | 28 | 29 | v0.5.3.1 :: Sun Nov 24 2013 30 | --------------------------- 31 | 32 | Bug fixes: 33 | 34 | - fix installation error 35 | 36 | 37 | v0.5.3 :: Sat Nov 23 2013 38 | ------------------------- 39 | 40 | Bug fixes: 41 | 42 | - editor: fix incorrect path to vi(1) when EDITOR is not defined 43 | (issues/1; reported by @taa1) 44 | - ``create`` command: treat "defaulted" fields as mandatory in case 45 | no default is set (issues/2; reported by @taa1) 46 | - ui: fix some unicode encoding errors 47 | - ``fields`` command: handle minor changes in result format in 4.4 48 | - correct the name of the platform field (platform -> rep_platform) 49 | 50 | Other changes: 51 | 52 | - expand bzr plugin documentation 53 | 54 | 55 | v0.5.2 :: Tue Feb 7 2012 56 | ------------------------ 57 | 58 | New features: 59 | 60 | - ``priority`` command: set the priority of the given bugs. 61 | - ``comment`` command learned the ``--which`` argument, for limiting 62 | output to only the given comment(s). 63 | - ``search`` learned the ``--version`` argument. 64 | - ``edit`` command: edit the product version of a bug. 65 | 66 | Bug fixes: 67 | 68 | - ``search`` command: fix crash when zero bugs returned 69 | 70 | Other changes: 71 | 72 | - ``-V`` replaces ``--version`` for displaying program version 73 | information. 74 | 75 | 76 | v0.5.1 :: Tue Jan 10 2012 77 | ------------------------- 78 | 79 | Bug fixes: 80 | 81 | - ``new`` command: fix assigned_to user matching. 82 | 83 | 84 | v0.5 :: Tue Jan 3 2012 85 | ---------------------- 86 | 87 | New features: 88 | 89 | - ``search`` command: search for bugs matching given criteria. 90 | - ``history`` command: display bug history. 91 | - ``new`` command: new config ``server..default_product``, if set 92 | and if corresponding to a product on the server, specifies the default 93 | product. 94 | - ``new`` command: perform user matching when specifying the assignee or 95 | cc list during bug creation. 96 | 97 | Bug fixes: 98 | 99 | - ``time`` command: calculate the hours worked on a bug. 100 | 101 | 102 | v0.4 :: Wed Nov 30 2011 103 | ----------------------- 104 | 105 | New features: 106 | 107 | - ``time`` command: show or adjust times and estimates for given bug. 108 | At time of writing, limitations in Bugzilla's RPC API prevent the 109 | display of cumulative time for a bug. 110 | - ``desc`` command: show the description of the given bugs. 111 | - ``dump`` command: print internal representation of bug(s). 112 | - ``comment`` learned the ``--omit-empty`` and ``--include-empty`` 113 | arguments; exclude or include empty comments (e.g. additional time 114 | worked, but no specific comment) from the output. The default is to 115 | omit empty comments. 116 | - The ``assign`` command can now be configured (on a per-server basis) 117 | to change the status of a bug, using the ``assign_status`` option. 118 | See README for details. 119 | 120 | Bug fixes: 121 | 122 | - Bugzilla URLs are now more rigourously sanity checked. 123 | 124 | Other changes: 125 | 126 | - Configuration file syntax changed to ini-like (i.e., parsable by 127 | ``ConfigParser``). JSON configuration is no longer supported. 128 | 129 | 130 | v0.3 :: Sun Aug 7 2011 131 | ---------------------- 132 | 133 | New features: 134 | 135 | - Added the Bazaar plugin. 136 | - ``new`` command: file a new bug, prompting user for bug data. 137 | - ``status`` learned the ``--dupe-of`` argument; this is all that's needed 138 | to mark a bug as a duplicate of another (Bugzilla with automatically set 139 | the status and resolution fields to appropriate values). 140 | 141 | Bug fixes: 142 | 143 | - ``status`` only prompts for resolution if new status is closed and 144 | current status is open (``--resolution`` may still be specified, 145 | however.) 146 | - The unused ``--choose-status`` and ``--choose-resolution`` arguments 147 | were removed from ``status``. 148 | - Fix the index-field width when displaying choose-from lists (was too 149 | wide when the number of items displayed was a power of 10) 150 | - Convert ``EOFError`` (``^D``) into ``bzlib.ui.RejectWarning`` when 151 | prompting user for input. 152 | - Don't bother prompting the user to choose an item from a list that 153 | contains only one item. 154 | 155 | 156 | v0.2.1 :: Tue Jul 12 2011 157 | ------------------------- 158 | 159 | Bug fixes: 160 | 161 | - Support Unicode data in all commands. 162 | - Do not show 'aliases' heading in ``--help`` output if none defined. 163 | - Add global arguments to subcommand ``--help`` output. 164 | 165 | 166 | v0.2 :: Sat Jul 2 2011 167 | ---------------------- 168 | 169 | New features: 170 | 171 | - ``comment`` now lists bug comments when no comment is given. 172 | ``--forward``, ``--reverse`` and ``--limit=N`` can be used to control 173 | output. 174 | - ``depend`` and ``block`` commands: show or update bug dependency 175 | relationships. 176 | - ``cc`` command: Show or update CC List. 177 | - ``fields`` command: List valid values for bug fields. 178 | - ``help`` command: Show help for a command, or the top-level help if 179 | no argument is given. 180 | - ``--version`` prints bugzillatools version. 181 | - Invoke EDITOR for comment input when comment required but not 182 | explicitly provided 183 | - User matching: For commands that require usernames, instead of 184 | providing full username, if a provided fragment matches a single user 185 | that user will be used. 186 | - Command aliases: users can define their own aliases for commands and 187 | command arguments. 188 | - Replace ``close``, ``fix``, ``reopen`` and ``resolve`` commands with the 189 | single ``status`` command; commands to suit a particular workflow can be 190 | defined as aliases of ``status``, with appropriate arguments. 191 | 192 | Bug fixes: 193 | 194 | - Improved server misconfiguration or missing configuration handling. 195 | - List commands in alphabetical order. 196 | 197 | Other changes: 198 | 199 | - The default user configuration file changed to ``~/.bugzillarc`` 200 | (formerly ~/.bugrc). 201 | 202 | 203 | v0.1.2 :: Fri Jun 17 2011 204 | ------------------------- 205 | 206 | Bug fixes: 207 | 208 | - Fix Bugzilla construction args 209 | 210 | 211 | v0.1.1 :: Tue Jun 14 2011 212 | ------------------------- 213 | 214 | New features: 215 | 216 | - ``products`` command: list products of a Bugzilla. 217 | - Describe subcommands in ``--help`` output. 218 | 219 | Bug fixes: 220 | 221 | - Handle server lookup failure when no servers are defined. 222 | 223 | 224 | v0.1 :: Sun Jun 12 2011 225 | ----------------------- 226 | 227 | New features: 228 | 229 | - First release of bugzillatools 230 | -------------------------------------------------------------------------------- /bzlib/bugzilla.py: -------------------------------------------------------------------------------- 1 | # This file is part of bugzillatools 2 | # Copyright (C) 2011 Benon Technologies Pty Ltd, Fraser Tweedale 3 | # Copyright (C) 2014 Fraser Tweedale 4 | # 5 | # bugzillatools is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | try: 19 | import urllib.parse as urlparse 20 | except ImportError: 21 | import urlparse 22 | try: 23 | import xmlrpclib 24 | except ImportError: 25 | import xmlrpc.client as xmlrpclib 26 | 27 | from . import bug 28 | from . import config 29 | 30 | 31 | # field type constants 32 | FIELD_UNKNOWN = 0 33 | FIELD_TEXT = 1 34 | FIELD_SELECT = 2 35 | FIELD_SELECT_MULTIPLE = 3 36 | FIELD_TEXTAREA = 4 37 | FIELD_DATETIME = 5 38 | FIELD_BUG_ID = 6 39 | FIELD_BUG_URL = 7 40 | 41 | 42 | class UserError(Exception): 43 | pass 44 | 45 | 46 | class URLError(Exception): 47 | pass 48 | 49 | 50 | class Bugzilla(object): 51 | """A Bugzilla server.""" 52 | 53 | __slots__ = [ 54 | '_products', '_fields', '_user_cache', 55 | 'url', 'user', 'password', 'config', 56 | 'server', 57 | ] 58 | 59 | @classmethod 60 | def from_config(cls, conf, **kwargs): 61 | """Instantiate a Bugzilla according to given Config and args. 62 | 63 | The 'server', 'url', 'user' and 'password' keyword arguments are 64 | required, but may be ``None``. 65 | """ 66 | mandatory_args = set(['server', 'url', 'user', 'password']) 67 | mandatory_args -= set(kwargs.keys()) 68 | if mandatory_args: 69 | raise TypeError('Mandatory args ({}) not supplied'.format( 70 | ', '.join("'{}'".format(arg) for arg in mandatory_args))) 71 | 72 | if kwargs['server'] is None and conf.has_option('core', 'server'): 73 | kwargs['server'] = conf.get('core', 'server') 74 | 75 | _server = {} 76 | if kwargs['server']: 77 | try: 78 | _server = dict(conf.items('server.' + kwargs['server'])) 79 | except config.NoSectionError: 80 | raise UserWarning( 81 | "No configuration for server '{}'." 82 | .format(kwargs['server']) 83 | ) 84 | 85 | for k in {'url', 'user', 'password'}: 86 | if k in kwargs and kwargs[k]: 87 | _server[k] = kwargs[k] 88 | 89 | mandatory_kwargs = {'url'} 90 | if mandatory_kwargs - set(_server.keys()): 91 | missing_args = ', '.join(mandatory_kwargs - _server.items()) 92 | raise UserWarning("missing args: {}".format(missing_args)) 93 | 94 | return cls(**_server) 95 | 96 | def __init__(self, url=None, user=None, password=None, **config): 97 | """Create a Bugzilla XML-RPC client. 98 | 99 | url : points to a bugzilla instance (base URL; must end in '/') 100 | user : bugzilla username 101 | password : bugzilla password 102 | """ 103 | 104 | self._products = None 105 | self._fields = None 106 | self._user_cache = {} 107 | 108 | self.url = url 109 | self.user = user 110 | self.password = password 111 | self.config = config 112 | 113 | parsed_url = urlparse.urlparse(url) 114 | if not parsed_url.netloc: 115 | raise URLError('URL {!r} is not valid.'.format(url)) 116 | if parsed_url.scheme not in ('http', 'https'): 117 | raise URLError( 118 | 'URL scheme {!r} not supported.'.format(parsed_url.scheme) 119 | ) 120 | if parsed_url.params or parsed_url.query or parsed_url.fragment: 121 | raise URLError( 122 | 'URL params, queries and fragments not supported.' 123 | ) 124 | url = url + 'xmlrpc.cgi' if url[-1] == '/' else url + '/xmlrpc.cgi' 125 | # httplib explodes if url is unicode 126 | self.server = xmlrpclib.ServerProxy( 127 | str(url), 128 | use_datetime=True, 129 | allow_none=True 130 | ) 131 | 132 | def rpc(self, *args, **kwargs): 133 | """Do an RPC on the Bugzilla server. 134 | 135 | args: RPC method, in fragments 136 | kwargs: RPC parameters 137 | """ 138 | kwargs['Bugzilla_login'] = self.user 139 | kwargs['Bugzilla_password'] = self.password 140 | 141 | method = self.server 142 | for fragment in args: 143 | method = getattr(method, fragment) 144 | return method(kwargs) 145 | 146 | def bug(self, bugno): 147 | """Extrude a Bug object.""" 148 | return bug.Bug(self, bugno) 149 | 150 | def get_products(self, use_cache=True): 151 | """Get accessible products of this Bugzilla.""" 152 | if use_cache and self._products: 153 | return self._products 154 | ids = self.rpc('Product', 'get_accessible_products')['ids'] 155 | self._products = self.rpc('Product', 'get', ids=ids)['products'] 156 | return self._products 157 | 158 | def get_fields(self, use_cache=True): 159 | """Get information about bug fields.""" 160 | if use_cache and self._fields: 161 | return self._fields 162 | self._fields = self.rpc('Bug', 'fields')['fields'] 163 | return self._fields 164 | 165 | def get_field_values(self, 166 | name, 167 | sort=True, 168 | omit_empty=True, 169 | visible_for=None 170 | ): 171 | """Return the legal values for a field; a list of dicts. 172 | 173 | visible_for: 174 | A dict of bug data. If the field has a value_field and its value 175 | is a key in the dict, the value of that bug field will be used to 176 | filter the values of field being queried accord to the contents of 177 | visibility_values. If the field does not have a value_field, no 178 | effect. If not supplied, no effect. 179 | """ 180 | field = filter(lambda x: x['name'] == name, self.get_fields())[0] 181 | values = [value for value in field['values'] if 'name' in value] 182 | if omit_empty: 183 | values = filter(lambda x: x['name'], values) 184 | value_field = field.get('value_field') 185 | if visible_for and value_field and value_field in visible_for: 186 | visibility_value = visible_for[value_field] 187 | values = filter( 188 | lambda x: visibility_value in x['visibility_values'], 189 | values 190 | ) 191 | if sort: 192 | values = sorted(values, key=lambda x: int(x['sortkey'])) 193 | return values 194 | 195 | def match_users(self, fragment, use_cache=True): 196 | """Return a list of users matching the given string.""" 197 | if use_cache and fragment in self._user_cache: 198 | return self._user_cache[fragment] 199 | users = self.rpc('User', 'get', match=[fragment])['users'] 200 | if use_cache: 201 | self._user_cache[fragment] = users 202 | return users 203 | 204 | def match_one_user(self, fragment, use_cache=True): 205 | """Return the user matching the given string. 206 | 207 | Raise UserError if the result does not contain exactly one user. 208 | """ 209 | users = self.match_users(fragment) 210 | if not users: 211 | raise UserError("No users matching '{}'".format(fragment)) 212 | if len(users) > 1: 213 | raise UserError("Multiple users matching '{}': {}".format( 214 | fragment, 215 | ', '.join(map(lambda x: x['name'], users)) 216 | )) 217 | return users[0] 218 | -------------------------------------------------------------------------------- /bzlib/ui.py: -------------------------------------------------------------------------------- 1 | # This file is part of bugzillatools 2 | # Copyright (C) 2011, 2012, 2013 Fraser Tweedale 3 | # Copyright (C) 2011, 2012 Benon Technologies Pty Ltd 4 | # 5 | # bugzillatools is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | from __future__ import unicode_literals 19 | 20 | import functools 21 | import math 22 | import re 23 | import sys 24 | 25 | from . import bugzilla as _bugzilla 26 | 27 | curry = functools.partial 28 | 29 | 30 | class InvalidInputError(Exception): 31 | pass 32 | 33 | 34 | class RejectWarning(Warning): 35 | pass 36 | 37 | 38 | def number(items): 39 | """Maps numbering onto given values""" 40 | n = len(items) 41 | width = math.log10(n - 1) // 1 + 1 if n > 1 else 1 42 | return map( 43 | lambda x: '[{0[0]:{1}}] {0[1]}'.format(x, int(width)), 44 | enumerate(items) 45 | ) 46 | 47 | 48 | def filter_yn(string, default=None): 49 | """Return True if yes, False if no, or the default.""" 50 | if string.startswith(('Y', 'y')): 51 | return True 52 | elif string.startswith(('N', 'n')): 53 | return False 54 | elif not string and default is not None: 55 | return True if default else False 56 | raise InvalidInputError 57 | 58 | 59 | def filter_int(string, default=None, start=None, stop=None): 60 | """Return the input integer, or the default.""" 61 | try: 62 | i = int(string) 63 | if start is not None and i < start: 64 | raise InvalidInputError( 65 | 'value too small; minimum is {}'.format(start)) 66 | if stop is not None and i >= stop: 67 | raise InvalidInputError( 68 | 'value too large; maximum is {}'.format(stop - 1)) 69 | return i 70 | except ValueError: 71 | if not string and default is not None: 72 | # empty string, default was given 73 | return default 74 | else: 75 | raise InvalidInputError('not an int: {!r}'.format(string)) 76 | 77 | 78 | def filter_list( 79 | string, 80 | default=None, 81 | filter=None, 82 | min_allowed=None, 83 | max_allowed=None, 84 | allow_duplicates=True, 85 | filter_duplicates=True 86 | ): 87 | """Return a list of values, or the default list. 88 | 89 | string 90 | A string of values delimited by commas, colons, semicolons and 91 | whitespace. 92 | default 93 | A list of values (possibly empty), or None. 94 | min_allowed 95 | The minimum number of responses allowed (inclusive), or None. 96 | max_allowed 97 | The maximum number of responses allowed (exclusive), or None. 98 | allow_duplicates 99 | Whether duplicates are allowed in the input. Defaults to True. 100 | filter_duplicates 101 | Whether duplicates are filtered out of the list before returning. 102 | Defaults to True. 103 | 104 | The min_allowed and max_allowed constraints are applied after 105 | duplicates are filtered out, if the duplicate filtering behaviour 106 | is used. 107 | """ 108 | if filter is None: 109 | raise TypeError("argument 'filter' not given") 110 | if not string and default is not None: 111 | return default 112 | strs = re.split(r'[\s:;,]+', string) 113 | strs = strs[1:] if strs and not strs[0] else strs 114 | strs = strs[:-1] if strs and not strs[-1] else strs 115 | values = [filter(s) for s in strs] 116 | valueset = set(values) 117 | if len(valueset) != len(values): 118 | if not allow_duplicates: 119 | raise InvalidInputError('duplicate values are not allowed') 120 | if filter_duplicates: 121 | values = list(valueset) 122 | if min_allowed is not None and len(values) < min_allowed: 123 | raise InvalidInputError('too few values supplied') 124 | if max_allowed is not None and len(values) > max_allowed: 125 | raise InvalidInputError('too many values supplied') 126 | return values 127 | 128 | 129 | def filter_decimal(string, default=None, lower=None, upper=None): 130 | """Return the input decimal number, or the default.""" 131 | try: 132 | d = decimal.Decimal(string) 133 | if lower is not None and d < lower: 134 | raise InvalidInputError("value too small") 135 | if upper is not None and d >= upper: 136 | raise InvalidInputError("value too large") 137 | return d 138 | except decimal.InvalidOperation: 139 | if not string and default is not None: 140 | # empty string, default was given 141 | return default 142 | else: 143 | raise InvalidInputError("invalid decimal number") 144 | 145 | 146 | def filter_text(string, default=None): 147 | if string: 148 | return string 149 | elif default is not None: 150 | return default 151 | else: 152 | raise InvalidInputError 153 | 154 | 155 | def filter_user(string, bugzilla=None, default=None): 156 | """Match to a single user and return the user name. 157 | 158 | ``bugzilla`` 159 | A ``bzlib.bugzilla.Bugzilla``. 160 | """ 161 | if not string and default: 162 | return None 163 | try: 164 | return bugzilla.match_one_user(string)['name'] 165 | except _bugzilla.UserError as e: 166 | raise InvalidInputError(e.message) 167 | 168 | 169 | class UI(object): 170 | def show(self, msg): 171 | print(msg) 172 | 173 | def bail(self, msg=None): 174 | """Exit uncleanly with an optional message""" 175 | if msg: 176 | self.show('BAIL OUT: ' + msg) 177 | sys.exit(1) 178 | 179 | def input(self, filter_fn, prompt): 180 | """Prompt user until valid input is received. 181 | 182 | RejectWarning is raised if a KeyboardInterrupt is caught. 183 | """ 184 | while True: 185 | try: 186 | return filter_fn(raw_input(prompt)) 187 | except InvalidInputError as e: 188 | if e.message: 189 | self.show('ERROR: ' + e.message) 190 | except EOFError: 191 | raise RejectWarning 192 | except KeyboardInterrupt: 193 | raise RejectWarning 194 | 195 | def text(self, prompt, default=None): 196 | """Prompts the user for some text, with optional default""" 197 | prompt = prompt if prompt is not None else 'Enter some text' 198 | prompt += " [{0}]: ".format(default) if default is not None else ': ' 199 | return self.input(curry(filter_text, default=default), prompt) 200 | 201 | def user(self, prompt, bugzilla=None, default=None): 202 | """Prompt the user for a username on the given ``Bugzilla``.""" 203 | prompt = prompt if prompt is not None else 'Enter a user name' 204 | prompt += " [{}]: ".format(default) if default is not None else ': ' 205 | return self.input( 206 | curry(filter_user, bugzilla=bugzilla, default=default), prompt) 207 | 208 | def user_list(self, prompt, bugzilla=None, default=None): 209 | """Prompt the user for a list of usernames on the ``Bugzilla``.""" 210 | prompt = prompt if prompt is not None else 'Enter a user name' 211 | prompt += " [{}]: ".format(default) if default is not None else ': ' 212 | return self.input( 213 | curry( 214 | filter_list, 215 | default=default, 216 | filter=curry(filter_user, bugzilla=bugzilla) 217 | ), 218 | prompt 219 | ) 220 | 221 | def bugno(self, prompt, default=None): 222 | prompt = prompt if prompt is None else 'Enter an bug number' 223 | prompt += " [{0}]: ".format(default) if default is not None else ': ' 224 | return self.input(curry(filter_int, start=1, default=default), prompt) 225 | 226 | def decimal(self, prompt, default=None, lower=None, upper=None): 227 | """Prompts user to input decimal, with optional default and bounds.""" 228 | prompt = prompt if prompt is not None else "Enter a decimal number" 229 | prompt += " [{0}]: ".format(default) if default is not None else ': ' 230 | return self.input( 231 | curry(filter_decimal, default=default, lower=lower, upper=upper), 232 | prompt 233 | ) 234 | 235 | def yn(self, prompt, default=None): 236 | """Prompts the user for yes/no confirmation, with optional default""" 237 | if default is True: 238 | opts = " [Y/n]: " 239 | elif default is False: 240 | opts = " [y/N]: " 241 | else: 242 | opts = " [y/n]: " 243 | prompt += opts 244 | return self.input(curry(filter_yn, default=default), prompt) 245 | 246 | def choose(self, prompt, items, default=None): 247 | """Prompts the user to choose one item from a list. 248 | 249 | The default, if provided, is an index; the item of that index will 250 | be returned. 251 | 252 | If the list has a single item, that item is returned without 253 | prompting the user at all. 254 | """ 255 | if len(items) == 1: 256 | return items[0] # only one item; return it without prompting 257 | if default is not None and (default >= len(items) or default < 0): 258 | raise IndexError 259 | prompt = prompt if prompt is not None else "Choose from following:" 260 | self.show(prompt + '\n') 261 | self.show("\n".join(number(items))) # show the items 262 | prompt = "Enter number of chosen item" 263 | prompt += " [{0}]: ".format(default) if default is not None else ': ' 264 | return items[self.input( 265 | curry(filter_int, default=default, start=0, stop=len(items)), 266 | prompt 267 | )] 268 | 269 | def chooseN(self, 270 | prompt, 271 | items, 272 | default=None, 273 | min_allowed=None, 274 | max_allowed=None 275 | ): 276 | """Prompt the user to choose multiple items from a list. 277 | 278 | prompt: 279 | Message with which to prompt user. If None given, a default 280 | prompt is generated. 281 | items: 282 | A list of items from which to choose. 283 | default: 284 | A list of indices. If the default is used, the list of values 285 | corresponding to these indices will be returned. If any value 286 | is out of range, IndexError is raised. 287 | min_allowed: 288 | The minimum number of items that must be chosen from the list 289 | (inclusive). Defaults to None (no minimum). 290 | max_allowed: 291 | The maximum number of items that must be chosen from the list 292 | (exclusive). Defaults to None (no maximum). 293 | """ 294 | if default and filter(lambda x: x >= len(items) or x < 0, default): 295 | raise IndexError('Default value ({}) out of range({})'.format( 296 | default, len(default) 297 | )) 298 | 299 | prompt = prompt if prompt is not None else \ 300 | "Choose from the following (multiple values may be chosen):" 301 | self.show(prompt + '\n') 302 | self.show('\n'.join(number(items))) # show the items 303 | prompt = "Enter the numbers of chosen items " \ 304 | "(comma or space separated list)" 305 | prompt += ' [{}]: '.format(' '.join(default)) if default is not None \ 306 | else ': ' 307 | indices = self.input( 308 | curry( 309 | filter_list, 310 | default=default, 311 | filter=curry(filter_int, start=0, stop=len(items)), 312 | min_allowed=min_allowed, 313 | max_allowed=max_allowed 314 | ), 315 | prompt 316 | ) 317 | return map(lambda x: items[x], indices) 318 | -------------------------------------------------------------------------------- /bzlib/bug.py: -------------------------------------------------------------------------------- 1 | # This file is part of bugzillatools 2 | # Copyright (C) 2011, 2012, 2013 Fraser Tweedale 3 | # Copyright (C) 2011, 2012 Benon Technologies Pty Ltd 4 | # 5 | # bugzillatools is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | import datetime 19 | import functools 20 | import itertools 21 | 22 | 23 | class Bug(object): 24 | 25 | @property 26 | def data(self): 27 | if self._data is None: 28 | if not self.bugno: 29 | raise Exception("bugno not provided.") 30 | self._data = self.rpc('get', ids=[self.bugno])['bugs'][0] 31 | return self._data 32 | 33 | @data.setter 34 | def data(self, value): 35 | self._data = value 36 | 37 | @property 38 | def history(self): 39 | if self._history is None: 40 | if not self.bugno: 41 | raise Exception("bugno not provided.") 42 | self._history = \ 43 | self.rpc('history', ids=[self.bugno])['bugs'][0]['history'] 44 | return self._history 45 | 46 | @history.setter 47 | def history(self, value): 48 | self._history = value 49 | 50 | @property 51 | def comments(self): 52 | if self._comments is None: 53 | if not self.bugno: 54 | raise Exception("bugno not provided.") 55 | result = self.rpc('comments', ids=[self.bugno]) 56 | self._comments = result['bugs'][str(self.bugno)]['comments'] 57 | return self._comments 58 | 59 | @comments.setter 60 | def comments(self, value): 61 | self._comments = value 62 | 63 | @classmethod 64 | def search(cls, bz, **kwargs): 65 | """Return bugs matching the search criteria. 66 | 67 | Values for fields are specified as keyword args. For fields 68 | with sets of valid values, appending ``"not_"`` to the field 69 | negates the criterion. If both forms are provided ("in" and 70 | "not in"), the "in" criterion take precedence. 71 | 72 | Return an Iterable of bugs (caller must not assume that the 73 | value returned is a Sequence). 74 | """ 75 | fields = frozenset([ 76 | 'alias', 'assigned_to', 'component', 'creation_time', 'creator', 77 | 'id', 'last_change_time', 'op_sys', 'rep_platform', 'priority', 78 | 'product', 'resolution', 'severity', 'status', 'summary', 79 | 'target_milestone', 'qa_contact', 'url', 'version', 'whiteboard', 80 | 'limit', 'offset', 81 | ]) 82 | 83 | # search kwargs for "not in" args and converts to an "in", 84 | # unless an "in" already exists 85 | for _not_in in (k for k in kwargs if k.startswith('not_')): 86 | _in = _not_in[4:] 87 | if _in not in fields: 88 | raise TypeError('Invalid keyword argument: {}.'.format(_in)) 89 | if _in not in kwargs: 90 | # set _in version (_in takes precedence if it's already set) 91 | if _in == 'product': 92 | all_values = set(x['name'] for x in bz.get_products()) 93 | else: 94 | all_values = set( 95 | value['name'] for value in 96 | [ 97 | field['values'] for field in bz.get_fields() 98 | if field['name'] == _in 99 | ][0] 100 | ) 101 | kwargs[_in] = list(all_values - frozenset(kwargs[_not_in])) 102 | del kwargs[_not_in] # delete the _not_in 103 | 104 | unknowns = set(kwargs.keys()) - fields 105 | if unknowns: 106 | # unknown arguments 107 | raise TypeError( 108 | 'Invalid keyword arguments: {}.'.format(', '.join(unknowns))) 109 | _cls = functools.partial(cls, bz) # curry constructor with bz 110 | return map(_cls, bz.rpc('Bug', 'search', **kwargs)['bugs']) 111 | 112 | def __init__(self, bz, bugno_or_data=None): 113 | """Create a bug object. 114 | 115 | bz: a bzlib.Bugzilla object 116 | bugno_or_data: if an int, refers to bugno, otherwise implies a 117 | new bug with the given data, otherwise implies 118 | a new bug with no data (yet). 119 | If data is None (the default) and if bugno is set, the data will be 120 | retrieved lazily. 121 | """ 122 | self.bz = bz 123 | 124 | self.bugno = None 125 | self.data = None 126 | self.comments = None 127 | self.history = None 128 | try: 129 | self.bugno = int(bugno_or_data) 130 | except TypeError: 131 | self.data = bugno_or_data or {} 132 | if 'id' in self.data: 133 | self.bugno = int(self.data['id']) 134 | 135 | @property 136 | def id(self): 137 | return self.bugno 138 | 139 | def rpc(self, *args, **kwargs): 140 | """Does an RPC on the Bugzilla server. 141 | 142 | Prepends 'Bug' to the method name. 143 | """ 144 | return self.bz.rpc(*(('Bug',) + args), **kwargs) 145 | 146 | def create(self): 147 | """Create a new bug. 148 | 149 | Required fields are: 150 | - product 151 | - component 152 | - summary 153 | - version 154 | 155 | Optional fields that may be useful include: 156 | - assigned_to 157 | - status 158 | - priority 159 | - cc 160 | 161 | Return the new bug ID. 162 | """ 163 | if self.bugno or 'id' in self.data: 164 | raise Exception("bugno is known; not creating bug.") 165 | result = self.rpc('create', **self.data) 166 | self.bugno = result['id'] 167 | return self.bugno 168 | 169 | def add_comment(self, comment, is_private=False): 170 | self.rpc('add_comment', id=self.bugno, comment=comment, is_private=is_private) 171 | self.comments = None # comments are stale 172 | self.history = None # history is stale 173 | 174 | def is_open(self): 175 | """Return True if the bug is open, otherwise False.""" 176 | return self.data['is_open'] 177 | 178 | def set_dupe_of(self, bug, comment=None): 179 | """Set this bug a duplicate of the given bug.""" 180 | kwargs = {'dupe_of': bug} 181 | if comment: 182 | kwargs['comment'] = {'body': comment} 183 | self.rpc('update', ids=[self.bugno], **kwargs) 184 | self.data = None # data is stale 185 | self.history = None # history is stale 186 | if comment: 187 | self.comments = None # comments are stale 188 | 189 | def set_status(self, status, resolution='', comment=None): 190 | """Set the status of this bug. 191 | 192 | A resolution string should be included for those statuses where it 193 | makes sense. 194 | 195 | A comment may optionally accompany the status change. 196 | """ 197 | kwargs = {'status': status} 198 | if resolution: 199 | kwargs['resolution'] = resolution 200 | if comment: 201 | kwargs['comment'] = {'body': comment} 202 | self.rpc('update', ids=[self.bugno], **kwargs) 203 | self.data = None # data is stale 204 | self.history = None # history is stale 205 | if comment: 206 | self.comments = None # comments are stale 207 | 208 | def set_assigned_to( 209 | self, 210 | user, 211 | comment=None, 212 | match=True 213 | ): 214 | """Reassign this bug. 215 | 216 | user: the new assignee 217 | comment: optional comment 218 | match: search for a user matching the given string 219 | 220 | If the ``assign_status`` config is set for the ``Bugzilla`` and 221 | the current status matches the first value, the status will be 222 | updated to the second value. 223 | """ 224 | if match: 225 | user = self.bz.match_one_user(user)['name'] 226 | kwargs = {'assigned_to': user} 227 | if comment: 228 | kwargs['comment'] = {'body': comment} 229 | if 'assign_status' in self.bz.config: 230 | try: 231 | froms, to = self.bz.config['assign_status'].split() 232 | if self.data['status'] in froms.split(','): 233 | kwargs['status'] = to 234 | except: 235 | pass # ignore errors (incorrect config) 236 | self.rpc('update', ids=[self.bugno], **kwargs) 237 | self.data = None # data is stale 238 | self.history = None # history is stale 239 | if comment: 240 | self.comments = None # comments are stale 241 | 242 | def update(self, **kwargs): 243 | """Update the bug. 244 | 245 | A wrapper for the RPC ``bug.update`` method that performs some sanity 246 | checks and flushes cached data as necessary. 247 | """ 248 | fields = frozenset([ 249 | 'remaining_time', 'work_time', 'estimated_time', 'deadline', 250 | 'blocks', 'depends_on', 251 | 'cc', 252 | 'comment', 253 | 'version', 'priority', 254 | ]) 255 | unknowns = kwargs.keys() - fields 256 | if unknowns: 257 | # unknown arguments 258 | raise TypeError('Invalid keyword arguments: {}.'.format(unknowns)) 259 | 260 | # filter out ``None``s 261 | kwargs = {k: v for k, v in kwargs.keys() if v is not None} 262 | # format deadline (YYYY-MM-DD) 263 | if 'deadline' in kwargs: 264 | date = kwargs['deadline'] 265 | if isinstance(date, datetime.datetime): 266 | date = date.date() # get date component of a datetime 267 | kwargs['deadline'] = str(date) # datetime.date formats in ISO 268 | 269 | result = self.rpc('update', ids=[self.bugno], **kwargs) 270 | self.data = None # data is stale 271 | self.history = None # history is stale 272 | if 'comment' in kwargs: 273 | self.comments = None # comments are stale 274 | return result 275 | # TODO refactor other methods to use this 276 | 277 | def update_block(self, add=None, remove=None, set=None, comment=None): 278 | """Update the bugs that this bug blocks. 279 | 280 | Accepts arrays of integer bug numbers. 281 | """ 282 | blocks = {} 283 | if set: 284 | blocks['set'] = set 285 | else: 286 | if add: 287 | blocks['add'] = add 288 | if remove: 289 | blocks['remove'] = remove 290 | kwargs = {'blocks': blocks} 291 | if comment: 292 | kwargs['comment'] = {'body': comment} 293 | self.rpc('update', ids=[self.bugno], **kwargs) 294 | self.data = None # data is stale 295 | self.history = None # history is stale 296 | if comment: 297 | self.comments = None # comments are stale 298 | 299 | def update_depend(self, add=None, remove=None, set=None, comment=None): 300 | """Update the bugs on which this bug depends. 301 | 302 | Accepts arrays of integer bug numbers. 303 | """ 304 | depends = {} 305 | if set: 306 | depends['set'] = set 307 | else: 308 | if add: 309 | depends['add'] = add 310 | if remove: 311 | depends['remove'] = remove 312 | kwargs = {'depends_on': depends} 313 | if comment: 314 | kwargs['comment'] = {'body': comment} 315 | self.rpc('update', ids=[self.bugno], **kwargs) 316 | self.data = None # data is stale 317 | self.history = None # history is stale 318 | if comment: 319 | self.comments = None # comments are stale 320 | 321 | def update_cc(self, add=None, remove=None, comment=None): 322 | """Update the CC list of the given bugs. 323 | 324 | Accepts arrays of valid user names. 325 | """ 326 | cc = {} 327 | if add: 328 | cc['add'] = add 329 | if remove: 330 | cc['remove'] = remove 331 | if not cc: 332 | return # nothing to do 333 | kwargs = {'cc': cc} 334 | if comment: 335 | kwargs['comment'] = {'body': comment} 336 | self.rpc('update', ids=[self.bugno], **kwargs) 337 | self.data = None # data is stale 338 | self.history = None # history is stale 339 | if comment: 340 | self.comments = None # comments are stale 341 | 342 | def actual_time(self): 343 | """Calculate the actual hours worked on a bug. 344 | 345 | Hopefully this will one day be available via rpc('get', ...), but 346 | for the time being, we have to use the history to calculate it. 347 | """ 348 | changesets = (changeset['changes'] for changeset in self.history) 349 | hours = ( 350 | float(change['added']) 351 | for change in itertools.chain.from_iterable(changesets) 352 | if change['field_name'] == 'work_time' 353 | ) 354 | return sum(hours) 355 | -------------------------------------------------------------------------------- /bzlib/command.py: -------------------------------------------------------------------------------- 1 | # This file is part of bugzillatools 2 | # Copyright (C) 2011, 2012, 2013 Fraser Tweedale 3 | # Copyright (C) 2011, 2012 Benon Technologies Pty Ltd 4 | # 5 | # bugzillatools is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | from __future__ import unicode_literals 19 | 20 | import argparse 21 | import datetime 22 | import functools 23 | import itertools 24 | import re 25 | import textwrap 26 | 27 | from . import bug 28 | from . import bugzilla 29 | from . import config 30 | from . import editor 31 | 32 | curry = functools.partial 33 | 34 | conf = config.Config.get_config('~/.bugzillarc') 35 | 36 | 37 | class _ReadFileAction(argparse.Action): 38 | def __call__(self, parser, namespace, values, option_string): 39 | setattr(namespace, self.dest, values.read()) 40 | 41 | 42 | def date(s): 43 | match = re.match(r'(\d{4})-(\d\d)-(\d\d)$', s) 44 | if not match: 45 | raise argparse.ArgumentTypeError('Date must be in format: YYYY-MM-DD') 46 | try: 47 | return datetime.date(*map(int, match.group(1, 2, 3))) 48 | except ValueError as e: 49 | raise argparse.ArgumentTypeError(e.message) 50 | 51 | 52 | def with_add_remove(src, dst, metavar=None, type=None): 53 | def decorator(cls): 54 | cls.args = cls.args + [ 55 | lambda x: x.add_argument('--add', metavar=metavar, type=type, 56 | nargs='+', 57 | help="Add {} to {}.".format(src, dst)), 58 | lambda x: x.add_argument('--remove', metavar=metavar, type=type, 59 | nargs='+', 60 | help="Remove {} from {}.".format(src, dst)), 61 | ] 62 | return cls 63 | return decorator 64 | 65 | 66 | def with_set(src, dst, metavar=None, type=None): 67 | def decorator(cls): 68 | cls.args = cls.args + [ 69 | lambda x: x.add_argument('--set', metavar=metavar, type=type, 70 | nargs='+', 71 | help="Set {} to {}. Ignore --add, --remove.".format(dst, src)), 72 | ] 73 | return cls 74 | return decorator 75 | 76 | 77 | def with_bugs(cls): 78 | cls.args = cls.args + [ 79 | lambda x: x.add_argument('bugs', metavar='BUG', type=int, nargs='+', 80 | help='Bug number'), 81 | ] 82 | return cls 83 | 84 | 85 | def with_time(cls): 86 | cls.args = cls.args + [ 87 | lambda x: x.add_argument('--estimated-time', type=float, 88 | help='Estimate of the total time required to fix the bug, ' 89 | 'in hours.'), 90 | lambda x: x.add_argument('--work-time', type=float, 91 | help='Additional hours worked.'), 92 | lambda x: x.add_argument('--remaining-time', type=float, 93 | help='Estimated time remaining. If not supplied, any hours ' 94 | 'worked will be deducted from the current remaining time.'), 95 | lambda x: x.add_argument('--deadline', type=date, 96 | help='Date when the bug must be fixed, in format YYYY-MM-DD'), 97 | ] 98 | return cls 99 | 100 | 101 | def with_optional_message(cls): 102 | def msgargs(parser): 103 | group = parser.add_mutually_exclusive_group() 104 | group.add_argument('-F', '--file', metavar='MSGFILE', dest='message', 105 | type=argparse.FileType('r'), action=_ReadFileAction, 106 | help='Take comment from this file') 107 | group.add_argument('-m', '--message', nargs='?', const=True, 108 | help='Comment on the change. With no argument, invokes an editor.') 109 | cls.args = cls.args + [msgargs] 110 | return cls 111 | 112 | 113 | def with_limit(things='items', default=None): 114 | def decorator(cls): 115 | cls.args = cls.args + [ 116 | lambda x: x.add_argument('--limit', '-l', type=int, 117 | default=default, metavar='N', 118 | help='Limit output to N {}.'.format(things)) 119 | ] 120 | return cls 121 | return decorator 122 | 123 | 124 | def with_server(cls): 125 | def add_server_args(parser): 126 | group = parser.add_argument_group('server arguments') 127 | group.add_argument('--server', help='name of Bugzilla server to use') 128 | group.add_argument('--url', help='base URL of Bugzilla server') 129 | group.add_argument('--user', help='Bugzilla username') 130 | group.add_argument('--password', help='Bugzilla password') 131 | cls.args = cls.args + [add_server_args] 132 | return cls 133 | 134 | 135 | class Command(object): 136 | """A command object. 137 | 138 | Provides arguments. Does what it does using __call__. 139 | """ 140 | 141 | """ 142 | An array of (args, kwargs) tuples that will be used as arguments to 143 | ArgumentParser.add_argument(). 144 | """ 145 | args = [] 146 | 147 | @classmethod 148 | def help(cls): 149 | return textwrap.dedent(filter(None, cls.__doc__.splitlines())[0]) 150 | 151 | @classmethod 152 | def epilog(cls): 153 | return textwrap.dedent('\n\n'.join(cls.__doc__.split('\n\n')[1:])) 154 | 155 | def __init__(self, args, parser, commands, aliases, ui): 156 | """ 157 | args: an argparse.Namespace 158 | parser: the argparse.ArgumentParser 159 | commands: a dict of all Command classes keyed by __name__.lower() 160 | aliases: a dict of aliases keyed by alias 161 | """ 162 | self._args = args 163 | self._parser = parser 164 | self._commands = commands 165 | self._aliases = aliases 166 | self._ui = ui 167 | 168 | 169 | class Config(Command): 170 | """Show or update configuration.""" 171 | args = Command.args + [ 172 | lambda x: x.add_argument('--list', '-l', action='store_true', 173 | help='list all configuration options'), 174 | lambda x: x.add_argument('name', nargs='?', 175 | help='name of option to show, set or remove'), 176 | lambda x: x.add_argument('--remove', action='store_true', 177 | help='remove the specified option'), 178 | lambda x: x.add_argument('value', nargs='?', 179 | help='set value of given option'), 180 | ] 181 | 182 | def __call__(self): 183 | args = self._args 184 | if args.list: 185 | for section in conf.sections(): 186 | for option, value in conf.items(section): 187 | print('{}={}'.format('.'.join((section, option)), value)) 188 | elif not args.name: 189 | raise UserWarning('No configuration option given.') 190 | else: 191 | try: 192 | section, option = args.name.rsplit('.', 1) 193 | except ValueError: 194 | raise UserWarning('Invalid configuration option.') 195 | if not section or not option: 196 | raise UserWarning('Invalid configuration option.') 197 | 198 | if args.remove: 199 | # remove the option 200 | conf.remove_option(section, option) 201 | if not conf.items(section): 202 | conf.remove_section(section) 203 | conf.write() 204 | elif args.value: 205 | # set new value 206 | if not conf.has_section(section): 207 | conf.add_section(section) 208 | oldvalue = conf.get(section, option) \ 209 | if conf.has_option(section, option) else None 210 | conf.set(section, option, args.value) 211 | conf.write() 212 | print('{}: {} => {}'.format(args.name, oldvalue, args.value)) 213 | else: 214 | curvalue = conf.get(section, option) 215 | print('{}: {}'.format(args.name, curvalue)) 216 | 217 | 218 | class Help(Command): 219 | """Show help.""" 220 | args = Command.args + [ 221 | lambda x: x.add_argument('subcommand', metavar='SUBCOMMAND', nargs='?', 222 | help='show help for subcommand') 223 | ] 224 | 225 | def __call__(self): 226 | if not self._args.subcommand: 227 | self._parser.parse_args(['--help']) 228 | else: 229 | if self._args.subcommand in self._aliases: 230 | print("'{}': alias for {}".format( 231 | self._args.subcommand, 232 | self._aliases[self._args.subcommand] 233 | )) 234 | elif self._args.subcommand not in self._commands: 235 | print("unknown subcommand: '{}'".format(self._args.subcommand)) 236 | else: 237 | self._parser.parse_args([self._args.subcommand, '--help']) 238 | 239 | 240 | @with_server 241 | class BugzillaCommand(Command): 242 | def __init__(self, *args, **kwargs): 243 | super(BugzillaCommand, self).__init__(*args, **kwargs) 244 | self.bz = bugzilla.Bugzilla.from_config(conf, **self._args.__dict__) 245 | 246 | 247 | @with_bugs 248 | @with_optional_message 249 | class Assign(BugzillaCommand): 250 | """Assign bugs to the given user.""" 251 | args = BugzillaCommand.args + [ 252 | lambda x: x.add_argument('--to', metavar='ASSIGNEE', required=True, 253 | help='New assignee'), 254 | ] 255 | 256 | def __call__(self): 257 | args = self._args 258 | message = editor.input('Enter your comment.') if args.message is True \ 259 | else args.message 260 | return map( 261 | lambda x: self.bz.bug(x).set_assigned_to(args.to, comment=message), 262 | args.bugs 263 | ) 264 | 265 | 266 | @with_set('given bugs', 'blocked bugs', metavar='BUG', type=int) 267 | @with_add_remove('given bugs', 'blocked bugs', metavar='BUG', type=int) 268 | @with_bugs 269 | @with_optional_message 270 | class Block(BugzillaCommand): 271 | """Show or update block list of given bugs.""" 272 | def __call__(self): 273 | args = self._args 274 | bugs = map(self.bz.bug, args.bugs) 275 | if args.add or args.remove or args.set: 276 | message = editor.input('Enter your comment.') \ 277 | if args.message is True else args.message 278 | # update blocked bugs 279 | map( 280 | lambda x: self.bz.bug(x).update_block( 281 | add=args.add, 282 | remove=args.remove, 283 | set=args.set, 284 | comment=message 285 | ), 286 | args.bugs 287 | ) 288 | else: 289 | # show blocked bugs 290 | for bug in bugs: 291 | print('Bug {}:'.format(bug.bugno)) 292 | if bug.data['blocks']: 293 | print(' Blocked bugs: {}'.format( 294 | ', '.join(map(str, bug.data['blocks'])))) 295 | else: 296 | print(' No blocked bugs') 297 | 298 | 299 | @with_add_remove('given users', 'CC List', metavar='USER') 300 | @with_bugs 301 | @with_optional_message 302 | class CC(BugzillaCommand): 303 | """Show or update CC List.""" 304 | def __call__(self): 305 | args = self._args 306 | bugs = map(self.bz.bug, args.bugs) 307 | if args.add or args.remove: 308 | # get actual users 309 | getuser = lambda x: self.bz.match_one_user(x)['name'] 310 | add = map(getuser, args.add) if args.add else None 311 | remove = map(getuser, args.remove) if args.remove else None 312 | 313 | # get message 314 | message = editor.input('Enter your comment.') \ 315 | if args.message is True else args.message 316 | 317 | # update CC list 318 | map( 319 | lambda x: self.bz.bug(x).update_cc( 320 | add=add, 321 | remove=remove, 322 | comment=message 323 | ), 324 | args.bugs 325 | ) 326 | else: 327 | # show CC List 328 | for bug in bugs: 329 | print('Bug {}:'.format(bug.bugno)) 330 | if bug.data['cc']: 331 | print(' CC List: {}'.format( 332 | ', '.join(map(str, bug.data['cc'])))) 333 | else: 334 | print(' 0 users') 335 | 336 | 337 | @with_bugs 338 | @with_optional_message 339 | @with_limit(things='comments') 340 | class Comment(BugzillaCommand): 341 | """List comments or file a comment on the given bugs.""" 342 | args = BugzillaCommand.args + [ 343 | lambda x: x.add_argument('--reverse', action='store_true', 344 | default=True, 345 | help='Show from newest to oldest (the default).'), 346 | lambda x: x.add_argument('--forward', action='store_false', 347 | dest='reverse', 348 | help='Show from oldest to newest.'), 349 | lambda x: x.add_argument('--omit-empty', action='store_true', 350 | default=True, 351 | help='Omit empty comments (the default).'), 352 | lambda x: x.add_argument('--include-empty', action='store_false', 353 | dest='omit_empty', 354 | help='Include empty comments.'), 355 | lambda x: x.add_argument('--private', action='store_true', 356 | default=False, 357 | dest='is_private', 358 | help='Make comment private.'), 359 | lambda x: x.add_argument('--which', type=int, nargs='+', metavar='N', 360 | help='show only the given comment numbers'), 361 | ] 362 | 363 | formatstring = '{}\nauthor: {creator}\ntime: {time}\n\n{text}\n\n' 364 | 365 | def __call__(self): 366 | args = self._args 367 | message = editor.input('Enter your comment.') \ 368 | if args.message is True else args.message 369 | if message: 370 | map(lambda x: self.bz.bug(x).add_comment(message, args.is_private), args.bugs) 371 | else: 372 | def cmtfmt(bug): 373 | comments = sorted( 374 | enumerate(self.bz.bug(bug).comments), 375 | key=lambda x: int(x[1]['id']) 376 | ) 377 | if args.reverse: 378 | comments = list(reversed(comments)) 379 | if args.limit: 380 | comments = comments[:abs(args.limit)] 381 | 382 | return '=====\nBUG {}\n\n-----\n{}'.format( 383 | bug, 384 | '-----\n'.join( 385 | self.formatstring.format( 386 | 'comment: {}'.format(n) if n else 'description', 387 | **comment) 388 | for n, comment in comments 389 | if not (args.omit_empty and not comment['text']) 390 | and not (args.which and n not in args.which) 391 | ) 392 | ) 393 | print('\n'.join(map(cmtfmt, args.bugs))) 394 | 395 | 396 | @with_set('given bugs', 'depdendencies', metavar='BUG', type=int) 397 | @with_add_remove('given bugs', 'depdendencies', metavar='BUG', type=int) 398 | @with_bugs 399 | @with_optional_message 400 | class Depend(BugzillaCommand): 401 | """Show or update dependencies of given bugs.""" 402 | def __call__(self): 403 | args = self._args 404 | bugs = map(self.bz.bug, args.bugs) 405 | if args.add or args.remove or args.set: 406 | message = editor.input('Enter your comment.') \ 407 | if args.message is True else args.message 408 | # update dependencies 409 | map( 410 | lambda x: x.update_depend( 411 | add=args.add, 412 | remove=args.remove, 413 | set=args.set, 414 | comment=message 415 | ), 416 | bugs 417 | ) 418 | else: 419 | # show dependencies 420 | for bug in bugs: 421 | print('Bug {}:'.format(bug.bugno)) 422 | if bug.data['depends_on']: 423 | print(' Dependencies: {}'.format( 424 | ', '.join(map(str, bug.data['depends_on'])))) 425 | else: 426 | print(' No dependencies') 427 | 428 | 429 | @with_bugs 430 | class Desc(BugzillaCommand): 431 | """Show the description of the given bug(s).""" 432 | formatstring = 'author: {creator}\ntime: {time}\n\n{text}\n' 433 | 434 | def __call__(self): 435 | def _descfmt(bug): 436 | desc = self.bz.bug(bug).comments[0] 437 | return '=====\nBUG {}\n{}'.format( 438 | bug, 439 | self.formatstring.format(**desc) 440 | ) 441 | print('\n'.join(_descfmt(bug) for bug in self._args.bugs)) 442 | 443 | 444 | @with_bugs 445 | class Dump(BugzillaCommand): 446 | """Print internal representation of bug data.""" 447 | def __call__(self): 448 | bugs = (self.bz.bug(x) for x in self._args.bugs) 449 | print('\n'.join(str((x.data, x.comments)) for x in bugs)) 450 | 451 | 452 | @with_bugs 453 | class Edit(BugzillaCommand): 454 | """Edit the given bugs.""" 455 | args = BugzillaCommand.args + [ 456 | lambda x: x.add_argument('--priority', 457 | help='new priority'), 458 | lambda x: x.add_argument('--version', 459 | help='new version'), 460 | ] 461 | _fields = frozenset(['priority', 'version']) 462 | 463 | def __call__(self): 464 | for bug in (self.bz.bug(x) for x in self._args.bugs): 465 | kwargs = { 466 | k: getattr(self._args, k) 467 | for k in self._fields & self._args.__dict__.viewkeys() 468 | } 469 | bug.update(**kwargs) 470 | 471 | 472 | class Fields(BugzillaCommand): 473 | """List valid values for bug fields.""" 474 | def __call__(self): 475 | args = self._args 476 | fields = filter(lambda x: 'values' in x, self.bz.get_fields()) 477 | for field in fields: 478 | keyfn = lambda x: x.get('visibility_values') 479 | groups = itertools.groupby( 480 | sorted(field['values'], None, keyfn), 481 | keyfn 482 | ) 483 | print("{} :".format(field['name'])) 484 | for key, group in groups: 485 | keyfn = lambda x: int(x.get('sortkey', -1)) 486 | values = sorted(group, None, keyfn) 487 | if key: 488 | print(' {}: {}'.format( 489 | ','.join(key), 490 | ','.join(map(lambda x: x['name'], values)) 491 | )) 492 | else: 493 | value_names = (v.get('name') for v in values) 494 | print(' ', ','.join(s for s in value_names if s)) 495 | 496 | 497 | def _format_history(history): 498 | """Return a generator of formatted lines of history.""" 499 | widths = [max(len(str(h[i])) for h in history) for i in range(5)] 500 | template = '{:{}}' 501 | return (' | '.join( 502 | (itertools.starmap(template.format, zip(map(str, h), widths))) 503 | ) for h in history) 504 | 505 | 506 | @with_bugs 507 | class History(BugzillaCommand): 508 | """Show the history of the given bugs.""" 509 | def __call__(self): 510 | fields = ('WHO', 'WHEN', 'WHAT', 'REMOVED', 'ADDED') 511 | for bug in map(self.bz.bug, self._args.bugs): 512 | history = [] 513 | for h in bug.history: 514 | _history = [ 515 | ['', '', c['field_name'], c['removed'], c['added']] 516 | for c in h['changes'] 517 | ] 518 | _history[0][0] = h['who'] 519 | _history[0][1] = h['when'] 520 | history.extend(_history) 521 | print('History of Bug {}:'.format(bug.bugno)) 522 | for line in _format_history(history): 523 | print(' ' + line) 524 | print() 525 | 526 | 527 | @with_bugs 528 | class Info(BugzillaCommand): 529 | """Show detailed information about the given bugs.""" 530 | def __call__(self): 531 | args = self._args 532 | fields = config.show_fields 533 | for bug in map(self.bz.bug, args.bugs): 534 | print('Bug {}:'.format(bug.bugno)) 535 | fields = config.show_fields & bug.data.viewkeys() 536 | width = max(map(len, fields)) - min(map(len, fields)) + 2 537 | for field in fields: 538 | print(' {:{}} {}'.format(field + ':', width, bug.data[field])) 539 | print() 540 | 541 | 542 | @with_bugs 543 | class List(BugzillaCommand): 544 | """Show a one-line summary of the given bugs.""" 545 | def __call__(self): 546 | args = self._args 547 | lens = [len(str(x)) for x in args.bugs] 548 | width = max(lens) - min(lens) + 2 549 | for bug in map(self.bz.bug, args.bugs): 550 | print('Bug {:{}} {}'.format( 551 | str(bug.bugno) + ':', width, bug.data['summary'] 552 | )) 553 | 554 | 555 | class New(BugzillaCommand): 556 | """File a new bug.""" 557 | def __call__(self): 558 | # create new Bug 559 | b = bug.Bug(self.bz) 560 | 561 | # get mandatory fields 562 | fields = self.bz.get_fields() 563 | defaulted_fields = [ 564 | 'description', 'op_sys', 'rep_platform', 'priority', 'severity'] 565 | mandatory_fields = filter( 566 | lambda x: x['is_mandatory'] or x['name'] in defaulted_fields, 567 | fields) 568 | 569 | # first choose the product 570 | products = [x['name'] for x in self.bz.get_products()] 571 | default = None 572 | if 'default_product' in self.bz.config \ 573 | and self.bz.config['default_product'] in products: 574 | default = products.index(self.bz.config['default_product']) 575 | b.data['product'] = \ 576 | self._ui.choose('Choose a product', products, default=default) 577 | 578 | # fill out other mandatory fields 579 | for field in mandatory_fields: 580 | if field['name'] in b.data: 581 | continue # field is already defined 582 | if 'values' in field: 583 | values = self.bz.get_field_values( 584 | field['name'], 585 | visible_for=b.data 586 | ) 587 | # TODO handle select-multiple fields 588 | b.data[field['name']] = self._ui.choose( 589 | 'Choose the {}'.format(field['display_name']), 590 | map(lambda x: x['name'], values) 591 | ) 592 | else: 593 | # TODO take field types into account 594 | b.data[field['name']] = self._ui.text( 595 | 'Enter the {}'.format(field['display_name']) 596 | ) 597 | 598 | # fill out a comment ("Description") if not already defined 599 | if 'comment' not in b.data: 600 | b.data['comment'] = editor.input( 601 | 'Enter a description of the problem.' 602 | ) 603 | 604 | # list of create fields ripped from Bugzilla documentation 605 | # (this info is not introspectable as of Bugzilla 4.0) 606 | create_fields = [ 607 | 'product', 'component', 'summary', 'version', 'comment', 608 | 'op_sys', 'rep_platform', 'priority', 'severity', 'alias', 609 | 'assigned_to', 'cc', 'comment_is_private', 'groups', 610 | 'qa_contact', 'status', 'target_milestone', 611 | ] 612 | 613 | # let user choose which of these other fields to define 614 | optional_fields = [ 615 | x['display_name'] for x in fields 616 | if x['name'] in create_fields and x['name'] not in b.data 617 | ] 618 | 619 | # prompt user for the fields they wish to define 620 | user_fields = self._ui.chooseN( 621 | 'Set values for other fields?', 622 | optional_fields, 623 | default=[] 624 | ) 625 | 626 | # iterate over those fields, prompting user for values 627 | for field in [x for x in fields if x['display_name'] in user_fields]: 628 | if field['name'] in b.data: 629 | continue # field is already defined 630 | if 'values' in field: 631 | values = self.bz.get_field_values( 632 | field['name'], 633 | visible_for=b.data 634 | ) 635 | # TODO handle select-multiple fields 636 | b.data[field['name']] = self._ui.choose( 637 | 'Choose the {}'.format(field['display_name']), 638 | map(lambda x: x['name'], values) 639 | ) 640 | else: 641 | # TODO take field types into account 642 | if field['name'] == 'assigned_to': 643 | _input = curry(self._ui.user, bugzilla=self.bz) 644 | elif field['name'] == 'cc': 645 | _input = curry(self._ui.user_list, bugzilla=self.bz) 646 | else: 647 | _input = self._ui.text 648 | b.data[field['name']] = \ 649 | _input('Enter the {}'.format(field['display_name'])) 650 | 651 | # create the bug 652 | id = b.create() 653 | self._ui.show('Created Bug {}'.format(id)) 654 | 655 | 656 | @with_bugs 657 | class Priority(BugzillaCommand): 658 | """Set the priority on the given bugs.""" 659 | args = BugzillaCommand.args + [ 660 | lambda x: x.add_argument('--priority', required=True, 661 | help='new priority'), 662 | ] 663 | 664 | def __call__(self): 665 | for bug in (self.bz.bug(x) for x in self._args.bugs): 666 | bug.update(priority=self._args.priority) 667 | 668 | 669 | class Products(BugzillaCommand): 670 | """List the products of a Bugzilla instance.""" 671 | def __call__(self): 672 | products = self.bz.get_products() 673 | width = max(map(lambda x: len(x['name']), products)) + 1 674 | for product in products: 675 | print('{:{}} {}'.format( 676 | product['name'] + ':', width, product['description'] 677 | )) 678 | 679 | 680 | @with_bugs 681 | @with_optional_message 682 | class Status(BugzillaCommand): 683 | """Set the status of the given bugs. 684 | 685 | Description 686 | ----------- 687 | 688 | The ``status`` command is used to update the status and resolution of 689 | bugs. The status is always required unless ``-dupe-of`` is used (see 690 | below). It can be given as the argument to ``--status``, otherwise the 691 | user will be prompted to choose the status from a list. 692 | 693 | If the status is changing from one considered "open" to one not 694 | considered "open", a resolution is required. It can be given using 695 | ``--resolution``, otherwise the user will be prompted to choose the 696 | resolution from a list. 697 | 698 | Marking bugs as duplicates 699 | -------------------------- 700 | 701 | To set a bug as a duplicate, simply use ``--dupe-of ``. ``--status`` 702 | and ``--resolution`` will be ignored. Bugzilla will automatically set the 703 | status and resolution fields to appropriate values for duplicate bugs. 704 | """ 705 | 706 | args = BugzillaCommand.args + [ 707 | lambda x: x.add_argument('--status', 708 | help='Specify a resolution (case-insensitive).'), 709 | lambda x: x.add_argument('--resolution', 710 | help='Specify a resolution (case-insensitive).'), 711 | lambda x: x.add_argument('--dupe-of', type=int, metavar='BUG', 712 | help='The bug of which the given bugs are duplicates.'), 713 | ] 714 | 715 | def __call__(self): 716 | args = self._args 717 | message = editor.input('Enter your comment.') if args.message is True \ 718 | else args.message 719 | 720 | if args.dupe_of: 721 | # This is all we need; --status and --resolution are ignored 722 | return map( 723 | lambda x: self.bz.bug(x).set_dupe_of(args.dupe_of, message), 724 | args.bugs 725 | ) 726 | 727 | # get the values of the 'bug_status' field 728 | values = self.bz.get_field_values('bug_status') 729 | 730 | if args.status: 731 | status = args.status.upper() 732 | else: 733 | # choose status 734 | status = self._ui.choose( 735 | 'Choose a status', 736 | map(lambda x: x['name'], values) 737 | ) 738 | 739 | # check if the new status is "open" 740 | try: 741 | value = filter(lambda x: x['name'] == status, values)[0] 742 | is_open = value['is_open'] 743 | except IndexError: 744 | # no value matching the chosen status 745 | raise UserWarning("Invalid status:", status) 746 | 747 | # instantiate bugs 748 | bugs = map(self.bz.bug, args.bugs) 749 | 750 | resolution = None 751 | if not is_open: 752 | # The new status accepts a resolution. 753 | if args.resolution: 754 | # A resolution was supplied. 755 | resolution = args.resolution.upper() 756 | elif any(map(lambda x: x.is_open(), bugs)): 757 | # A resolution was not supplied, but one is required since 758 | # at least one of the bugs is currently open. Choose one. 759 | values = self.bz.get_field_values('resolution') 760 | resolution = self._ui.choose( 761 | 'Choose a resolution', 762 | map(lambda x: x['name'], values) 763 | ) 764 | 765 | return map( 766 | lambda x: self.bz.bug(x).set_status( 767 | status=status, 768 | resolution=resolution, 769 | comment=message 770 | ), 771 | args.bugs 772 | ) 773 | 774 | 775 | def _make_set_argument(arg): 776 | template = 'Only match bugs {{}}of the given {}({})'.format( 777 | arg, 's' if arg[-1] != 's' else 'es') 778 | return [ 779 | lambda x: x.add_argument('--' + arg, nargs='+', 780 | metavar=arg.upper(), 781 | help=template.format('')), 782 | lambda x: x.add_argument('--not-' + arg, nargs='+', 783 | metavar=arg.upper(), 784 | help=template.format('NOT ')), 785 | ] 786 | 787 | 788 | class Search(BugzillaCommand): 789 | """Search for bugs matching given criteria. 790 | 791 | If both '--foo' and '--not-foo' are given for any argument 'foo', 792 | the former takes precendence. 793 | """ 794 | args = BugzillaCommand.args + [ 795 | lambda x: x.add_argument('--summary', nargs='+', 796 | help='Match summary against any of the given substrings.'), 797 | ] 798 | simple_arguments = ['summary'] 799 | set_arguments = 'product', 'component', 'status', 'resolution', 'version' 800 | for x in set_arguments: 801 | args.extend(_make_set_argument(x)) 802 | 803 | def __call__(self): 804 | kwargs = { 805 | arg: getattr(self._args, arg) 806 | for arg in itertools.chain( 807 | self.simple_arguments, 808 | self.set_arguments, 809 | ('not_' + x for x in self.set_arguments) 810 | ) 811 | if getattr(self._args, arg) 812 | } 813 | 814 | bugs = list(bug.Bug.search(self.bz, **kwargs)) 815 | lens = [len(str(b.bugno)) for b in bugs] 816 | 817 | for _bug in bugs: 818 | print('Bug {:{}} {}'.format( 819 | str(_bug.bugno) + ':', max(lens) - min(lens) + 2, 820 | _bug.data['summary'] 821 | )) 822 | n = len(bugs) 823 | print('=> {} bug{} matched criteria'.format(n, 's' if n else '')) 824 | 825 | 826 | @with_bugs 827 | @with_optional_message 828 | @with_time 829 | class Time(BugzillaCommand): 830 | """Show or adjust times and estimates for the given bugs.""" 831 | def __call__(self): 832 | args = self._args 833 | 834 | message = editor.input('Enter your comment.') if args.message is True \ 835 | else args.message 836 | 837 | time_args = \ 838 | ['estimated_time', 'remaining_time', 'work_time', 'deadline'] 839 | if any(getattr(args, arg) is not None for arg in time_args): 840 | # adjust 841 | if len(args.bugs) != 1: 842 | # makes no sense to adjust times on several bugs at once 843 | raise UserWarning('Cannot adjust times on multiple bugs.') 844 | self.bz.bug(args.bugs[0]).update( 845 | estimated_time=args.estimated_time, 846 | remaining_time=args.remaining_time, 847 | work_time=args.work_time, 848 | deadline=args.deadline, 849 | comment=message 850 | ) 851 | else: 852 | # display 853 | # 854 | # As of Bugzilla 4.0.1, "actual_time" (total hours worked) is 855 | # not returned in bug.get. It can, however, be calculated from 856 | # the bug history. 857 | bugs = (self.bz.bug(bug) for bug in args.bugs) 858 | for bug in bugs: 859 | # if user is not in the "time-tracking" group, the fields will 860 | # be absent from bug data. first check that they're there. 861 | time_fields = ('deadline', 'estimated_time', 'remaining_time') 862 | if not all(x in bug.data for x in time_fields): 863 | print('User is not in the time-tracking group.') 864 | return 865 | print('Bug {}:'.format(bug.bugno)) 866 | print(' Estimated time: {}'.format(bug.data['estimated_time'])) 867 | print(' Remaining time: {}'.format(bug.data['remaining_time'])) 868 | print(' Deadline: {}'.format(bug.data['deadline'])) 869 | print(' Time worked: {}'.format(bug.actual_time())) 870 | 871 | 872 | # the list got too long; metaprogram it ^_^ 873 | commands = filter( 874 | lambda x: type(x) == type # is a class \ 875 | and issubclass(x, Command) # is a Command \ 876 | and x not in [Command, BugzillaCommand], # not abstract 877 | locals().items() 878 | ) 879 | -------------------------------------------------------------------------------- /gpl-3.0.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------