/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/bugtracker.py

  • Committer: John Arbash Meinel
  • Date: 2006-04-25 15:05:42 UTC
  • mfrom: (1185.85.85 bzr-encoding)
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: john@arbash-meinel.com-20060425150542-c7b518dca9928691
[merge] the old bzr-encoding changes, reparenting them on bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007-2010 Canonical Ltd
2
 
#
3
 
# This program is free software; you can redistribute it and/or modify
4
 
# it under the terms of the GNU General Public License as published by
5
 
# the Free Software Foundation; either version 2 of the License, or
6
 
# (at your option) any later version.
7
 
#
8
 
# This program is distributed in the hope that it will be useful,
9
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
 
# GNU General Public License for more details.
12
 
#
13
 
# You should have received a copy of the GNU General Public License
14
 
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
from __future__ import absolute_import
18
 
 
19
 
from . import (
20
 
    errors,
21
 
    registry,
22
 
    )
23
 
from .lazy_import import lazy_import
24
 
lazy_import(globals(), """
25
 
from breezy import urlutils
26
 
""")
27
 
 
28
 
 
29
 
"""Provides a shorthand for referring to bugs on a variety of bug trackers.
30
 
 
31
 
'commit --fixes' stores references to bugs as a <bug_url> -> <bug_status>
32
 
mapping in the properties for that revision.
33
 
 
34
 
However, it's inconvenient to type out full URLs for bugs on the command line,
35
 
particularly given that many users will be using only a single bug tracker per
36
 
branch.
37
 
 
38
 
Thus, this module provides a registry of types of bug tracker (e.g. Launchpad,
39
 
Trac). Given an abbreviated name (e.g. 'lp', 'twisted') and a branch with
40
 
configuration information, these tracker types can return an instance capable
41
 
of converting bug IDs into URLs.
42
 
"""
43
 
 
44
 
 
45
 
_bugs_help = """\
46
 
When making a commit, metadata about bugs fixed by that change can be
47
 
recorded by using the ``--fixes`` option. For each bug marked as fixed, an
48
 
entry is included in the 'bugs' revision property stating '<url> <status>'.
49
 
(The only ``status`` value currently supported is ``fixed.``)
50
 
 
51
 
The ``--fixes`` option allows you to specify a bug tracker and a bug identifier
52
 
rather than a full URL. This looks like::
53
 
 
54
 
    bzr commit --fixes <tracker>:<id>
55
 
 
56
 
or::
57
 
 
58
 
    bzr commit --fixes <id>
59
 
 
60
 
where "<tracker>" is an identifier for the bug tracker, and "<id>" is the
61
 
identifier for that bug within the bugtracker, usually the bug number.
62
 
If "<tracker>" is not specified the ``bugtracker`` set in the branch
63
 
or global configuration is used.
64
 
 
65
 
Bazaar knows about a few bug trackers that have many users. If
66
 
you use one of these bug trackers then there is no setup required to
67
 
use this feature, you just need to know the tracker identifier to use.
68
 
These are the bugtrackers that are built in:
69
 
 
70
 
  ============================ ============ ============
71
 
  URL                          Abbreviation Example
72
 
  ============================ ============ ============
73
 
  https://bugs.launchpad.net/  lp           lp:12345
74
 
  http://bugs.debian.org/      deb          deb:12345
75
 
  http://bugzilla.gnome.org/   gnome        gnome:12345
76
 
  ============================ ============ ============
77
 
 
78
 
For the bug trackers not listed above configuration is required.
79
 
Support for generating the URLs for any project using Bugzilla or Trac
80
 
is built in, along with a template mechanism for other bugtrackers with
81
 
simple URL schemes. If your bug tracker can't be described by one
82
 
of the schemes described below then you can write a plugin to support
83
 
it.
84
 
 
85
 
If you use Bugzilla or Trac, then you only need to set a configuration
86
 
variable which contains the base URL of the bug tracker. These options
87
 
can go into ``breezy.conf``, ``branch.conf`` or into a branch-specific
88
 
configuration section in ``locations.conf``.  You can set up these values
89
 
for each of the projects you work on.
90
 
 
91
 
Note: As you provide a short name for each tracker, you can specify one or
92
 
more bugs in one or more trackers at commit time if you wish.
93
 
 
94
 
Launchpad
95
 
---------
96
 
 
97
 
Use ``bzr commit --fixes lp:2`` to record that this commit fixes bug 2.
98
 
 
99
 
bugzilla_<tracker>_url
100
 
----------------------
101
 
 
102
 
If present, the location of the Bugzilla bug tracker referred to by
103
 
<tracker>. This option can then be used together with ``bzr commit
104
 
--fixes`` to mark bugs in that tracker as being fixed by that commit. For
105
 
example::
106
 
 
107
 
    bugzilla_squid_url = http://bugs.squid-cache.org
108
 
 
109
 
would allow ``bzr commit --fixes squid:1234`` to mark Squid's bug 1234 as
110
 
fixed.
111
 
 
112
 
trac_<tracker>_url
113
 
------------------
114
 
 
115
 
If present, the location of the Trac instance referred to by
116
 
<tracker>. This option can then be used together with ``bzr commit
117
 
--fixes`` to mark bugs in that tracker as being fixed by that commit. For
118
 
example::
119
 
 
120
 
    trac_twisted_url = http://www.twistedmatrix.com/trac
121
 
 
122
 
would allow ``bzr commit --fixes twisted:1234`` to mark Twisted's bug 1234 as
123
 
fixed.
124
 
 
125
 
bugtracker_<tracker>_url
126
 
------------------------
127
 
 
128
 
If present, the location of a generic bug tracker instance referred to by
129
 
<tracker>. The location must contain an ``{id}`` placeholder,
130
 
which will be replaced by a specific bug ID. This option can then be used
131
 
together with ``bzr commit --fixes`` to mark bugs in that tracker as being
132
 
fixed by that commit. For example::
133
 
 
134
 
    bugtracker_python_url = http://bugs.python.org/issue{id}
135
 
 
136
 
would allow ``bzr commit --fixes python:1234`` to mark bug 1234 in Python's
137
 
Roundup bug tracker as fixed, or::
138
 
 
139
 
    bugtracker_cpan_url = http://rt.cpan.org/Public/Bug/Display.html?id={id}
140
 
 
141
 
would allow ``bzr commit --fixes cpan:1234`` to mark bug 1234 in CPAN's
142
 
RT bug tracker as fixed, or::
143
 
 
144
 
    bugtracker_hudson_url = http://issues.hudson-ci.org/browse/{id}
145
 
 
146
 
would allow ``bzr commit --fixes hudson:HUDSON-1234`` to mark bug HUDSON-1234
147
 
in Hudson's JIRA bug tracker as fixed.
148
 
"""
149
 
 
150
 
 
151
 
class MalformedBugIdentifier(errors.BzrError):
152
 
 
153
 
    _fmt = ('Did not understand bug identifier %(bug_id)s: %(reason)s. '
154
 
            'See "brz help bugs" for more information on this feature.')
155
 
 
156
 
    def __init__(self, bug_id, reason):
157
 
        self.bug_id = bug_id
158
 
        self.reason = reason
159
 
 
160
 
 
161
 
class InvalidBugTrackerURL(errors.BzrError):
162
 
 
163
 
    _fmt = ("The URL for bug tracker \"%(abbreviation)s\" doesn't "
164
 
            "contain {id}: %(url)s")
165
 
 
166
 
    def __init__(self, abbreviation, url):
167
 
        self.abbreviation = abbreviation
168
 
        self.url = url
169
 
 
170
 
 
171
 
class UnknownBugTrackerAbbreviation(errors.BzrError):
172
 
 
173
 
    _fmt = ("Cannot find registered bug tracker called %(abbreviation)s "
174
 
            "on %(branch)s")
175
 
 
176
 
    def __init__(self, abbreviation, branch):
177
 
        self.abbreviation = abbreviation
178
 
        self.branch = branch
179
 
 
180
 
 
181
 
class InvalidLineInBugsProperty(errors.BzrError):
182
 
 
183
 
    _fmt = ("Invalid line in bugs property: '%(line)s'")
184
 
 
185
 
    def __init__(self, line):
186
 
        self.line = line
187
 
 
188
 
 
189
 
class InvalidBugUrl(errors.BzrError):
190
 
 
191
 
    _fmt = "Invalid bug URL: %(url)s"
192
 
 
193
 
    def __init__(self, url):
194
 
        self.url = url
195
 
 
196
 
 
197
 
class InvalidBugStatus(errors.BzrError):
198
 
 
199
 
    _fmt = ("Invalid bug status: '%(status)s'")
200
 
 
201
 
    def __init__(self, status):
202
 
        self.status = status
203
 
 
204
 
 
205
 
def get_bug_url(abbreviated_bugtracker_name, branch, bug_id):
206
 
    """Return a URL pointing to the canonical web page of the bug identified by
207
 
    'bug_id'.
208
 
    """
209
 
    tracker = tracker_registry.get_tracker(abbreviated_bugtracker_name, branch)
210
 
    return tracker.get_bug_url(bug_id)
211
 
 
212
 
 
213
 
class TrackerRegistry(registry.Registry):
214
 
    """Registry of bug tracker types."""
215
 
 
216
 
    def get_tracker(self, abbreviated_bugtracker_name, branch):
217
 
        """Return the first registered tracker that understands
218
 
        'abbreviated_bugtracker_name'.
219
 
 
220
 
        If no such tracker is found, raise KeyError.
221
 
        """
222
 
        for tracker_name in self.keys():
223
 
            tracker_type = self.get(tracker_name)
224
 
            tracker = tracker_type.get(abbreviated_bugtracker_name, branch)
225
 
            if tracker is not None:
226
 
                return tracker
227
 
        raise UnknownBugTrackerAbbreviation(
228
 
            abbreviated_bugtracker_name, branch)
229
 
 
230
 
    def help_topic(self, topic):
231
 
        return _bugs_help
232
 
 
233
 
 
234
 
tracker_registry = TrackerRegistry()
235
 
"""Registry of bug trackers."""
236
 
 
237
 
 
238
 
class BugTracker(object):
239
 
    """Base class for bug trackers."""
240
 
 
241
 
    def check_bug_id(self, bug_id):
242
 
        """Check that the bug_id is valid.
243
 
 
244
 
        The base implementation assumes that all bug_ids are valid.
245
 
        """
246
 
 
247
 
    def get_bug_url(self, bug_id):
248
 
        """Return the URL for bug_id. Raise an error if bug ID is malformed."""
249
 
        self.check_bug_id(bug_id)
250
 
        return self._get_bug_url(bug_id)
251
 
 
252
 
    def _get_bug_url(self, bug_id):
253
 
        """Given a validated bug_id, return the bug's web page's URL."""
254
 
 
255
 
 
256
 
class IntegerBugTracker(BugTracker):
257
 
    """A bug tracker that only allows integer bug IDs."""
258
 
 
259
 
    def check_bug_id(self, bug_id):
260
 
        try:
261
 
            int(bug_id)
262
 
        except ValueError:
263
 
            raise MalformedBugIdentifier(bug_id, "Must be an integer")
264
 
 
265
 
 
266
 
class UniqueIntegerBugTracker(IntegerBugTracker):
267
 
    """A style of bug tracker that exists in one place only, such as Launchpad.
268
 
 
269
 
    If you have one of these trackers then register an instance passing in an
270
 
    abbreviated name for the bug tracker and a base URL. The bug ids are
271
 
    appended directly to the URL.
272
 
    """
273
 
 
274
 
    def __init__(self, abbreviated_bugtracker_name, base_url):
275
 
        self.abbreviation = abbreviated_bugtracker_name
276
 
        self.base_url = base_url
277
 
 
278
 
    def get(self, abbreviated_bugtracker_name, branch):
279
 
        """Returns the tracker if the abbreviation matches, otherwise ``None``.
280
 
        """
281
 
        if abbreviated_bugtracker_name != self.abbreviation:
282
 
            return None
283
 
        return self
284
 
 
285
 
    def _get_bug_url(self, bug_id):
286
 
        """Return the URL for bug_id."""
287
 
        return self.base_url + str(bug_id)
288
 
 
289
 
 
290
 
class ProjectIntegerBugTracker(IntegerBugTracker):
291
 
    """A bug tracker that exists in one place only with per-project ids.
292
 
 
293
 
    If you have one of these trackers then register an instance passing in an
294
 
    abbreviated name for the bug tracker and a base URL. The bug ids are
295
 
    appended directly to the URL.
296
 
    """
297
 
 
298
 
    def __init__(self, abbreviated_bugtracker_name, base_url):
299
 
        self.abbreviation = abbreviated_bugtracker_name
300
 
        self._base_url = base_url
301
 
 
302
 
    def get(self, abbreviated_bugtracker_name, branch):
303
 
        """Returns the tracker if the abbreviation matches, otherwise ``None``.
304
 
        """
305
 
        if abbreviated_bugtracker_name != self.abbreviation:
306
 
            return None
307
 
        return self
308
 
 
309
 
    def check_bug_id(self, bug_id):
310
 
        try:
311
 
            (project, bug_id) = bug_id.rsplit('/', 1)
312
 
        except ValueError:
313
 
            raise MalformedBugIdentifier(bug_id, "Expected format: project/id")
314
 
        try:
315
 
            int(bug_id)
316
 
        except ValueError:
317
 
            raise MalformedBugIdentifier(bug_id, "Bug id must be an integer")
318
 
 
319
 
    def _get_bug_url(self, bug_id):
320
 
        (project, bug_id) = bug_id.rsplit('/', 1)
321
 
        """Return the URL for bug_id."""
322
 
        if '{id}' not in self._base_url:
323
 
            raise InvalidBugTrackerURL(self._abbreviation, self._base_url)
324
 
        if '{project}' not in self._base_url:
325
 
            raise InvalidBugTrackerURL(self._abbreviation, self._base_url)
326
 
        return self._base_url.replace(
327
 
            '{project}', project).replace('{id}', str(bug_id))
328
 
 
329
 
 
330
 
tracker_registry.register(
331
 
    'launchpad', UniqueIntegerBugTracker('lp', 'https://launchpad.net/bugs/'))
332
 
 
333
 
 
334
 
tracker_registry.register(
335
 
    'debian', UniqueIntegerBugTracker('deb', 'http://bugs.debian.org/'))
336
 
 
337
 
 
338
 
tracker_registry.register(
339
 
    'gnome', UniqueIntegerBugTracker(
340
 
        'gnome', 'http://bugzilla.gnome.org/show_bug.cgi?id='))
341
 
 
342
 
 
343
 
tracker_registry.register(
344
 
    'github', ProjectIntegerBugTracker(
345
 
        'github', 'https://github.com/{project}/issues/{id}'))
346
 
 
347
 
 
348
 
class URLParametrizedBugTracker(BugTracker):
349
 
    """A type of bug tracker that can be found on a variety of different sites,
350
 
    and thus needs to have the base URL configured.
351
 
 
352
 
    Looks for a config setting in the form '<type_name>_<abbreviation>_url'.
353
 
    `type_name` is the name of the type of tracker and `abbreviation`
354
 
    is a short name for the particular instance.
355
 
    """
356
 
 
357
 
    def get(self, abbreviation, branch):
358
 
        config = branch.get_config()
359
 
        url = config.get_user_option(
360
 
            "%s_%s_url" % (self.type_name, abbreviation), expand=False)
361
 
        if url is None:
362
 
            return None
363
 
        self._base_url = url
364
 
        return self
365
 
 
366
 
    def __init__(self, type_name, bug_area):
367
 
        self.type_name = type_name
368
 
        self._bug_area = bug_area
369
 
 
370
 
    def _get_bug_url(self, bug_id):
371
 
        """Return a URL for a bug on this Trac instance."""
372
 
        return urlutils.join(self._base_url, self._bug_area) + str(bug_id)
373
 
 
374
 
 
375
 
class URLParametrizedIntegerBugTracker(IntegerBugTracker,
376
 
                                       URLParametrizedBugTracker):
377
 
    """A type of bug tracker that  only allows integer bug IDs.
378
 
 
379
 
    This can be found on a variety of different sites, and thus needs to have
380
 
    the base URL configured.
381
 
 
382
 
    Looks for a config setting in the form '<type_name>_<abbreviation>_url'.
383
 
    `type_name` is the name of the type of tracker (e.g. 'bugzilla' or 'trac')
384
 
    and `abbreviation` is a short name for the particular instance (e.g.
385
 
    'squid' or 'apache').
386
 
    """
387
 
 
388
 
 
389
 
tracker_registry.register(
390
 
    'trac', URLParametrizedIntegerBugTracker('trac', 'ticket/'))
391
 
 
392
 
tracker_registry.register(
393
 
    'bugzilla',
394
 
    URLParametrizedIntegerBugTracker('bugzilla', 'show_bug.cgi?id='))
395
 
 
396
 
 
397
 
class GenericBugTracker(URLParametrizedBugTracker):
398
 
    """Generic bug tracker specified by an URL template."""
399
 
 
400
 
    def __init__(self):
401
 
        super(GenericBugTracker, self).__init__('bugtracker', None)
402
 
 
403
 
    def get(self, abbreviation, branch):
404
 
        self._abbreviation = abbreviation
405
 
        return super(GenericBugTracker, self).get(abbreviation, branch)
406
 
 
407
 
    def _get_bug_url(self, bug_id):
408
 
        """Given a validated bug_id, return the bug's web page's URL."""
409
 
        if '{id}' not in self._base_url:
410
 
            raise InvalidBugTrackerURL(self._abbreviation, self._base_url)
411
 
        return self._base_url.replace('{id}', str(bug_id))
412
 
 
413
 
 
414
 
tracker_registry.register('generic', GenericBugTracker())
415
 
 
416
 
 
417
 
FIXED = 'fixed'
418
 
RELATED = 'related'
419
 
 
420
 
ALLOWED_BUG_STATUSES = {FIXED, RELATED}
421
 
 
422
 
 
423
 
def encode_fixes_bug_urls(bug_urls):
424
 
    """Get the revision property value for a commit that fixes bugs.
425
 
 
426
 
    :param bug_urls: An iterable of (escaped URL, tag) tuples. These normally
427
 
        come from `get_bug_url`.
428
 
    :return: A string that will be set as the 'bugs' property of a revision
429
 
        as part of a commit.
430
 
    """
431
 
    lines = []
432
 
    for (url, tag) in bug_urls:
433
 
        if ' ' in url:
434
 
            raise InvalidBugUrl(url)
435
 
        lines.append('%s %s' % (url, tag))
436
 
    return '\n'.join(lines)
437
 
 
438
 
 
439
 
def decode_bug_urls(bug_text):
440
 
    """Decode a bug property text.
441
 
 
442
 
    :param bug_text: Contents of a bugs property
443
 
    :return: iterator over (url, status) tuples
444
 
    """
445
 
    for line in bug_text.splitlines():
446
 
        try:
447
 
            url, status = line.split(None, 2)
448
 
        except ValueError:
449
 
            raise InvalidLineInBugsProperty(line)
450
 
        if status not in ALLOWED_BUG_STATUSES:
451
 
            raise InvalidBugStatus(status)
452
 
        yield url, status