Imported bugzilla extension from mercurial 1.3.1.
1 # bugzilla.py - bugzilla integration for mercurial
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2, incorporated herein by reference.
8 '''hooks for integrating with the Bugzilla bug tracker
10 This hook extension adds comments on bugs in Bugzilla when changesets
11 that refer to bugs by Bugzilla ID are seen. The hook does not change
14 The hook updates the Bugzilla database directly. Only Bugzilla
15 installations using MySQL are supported.
17 The hook relies on a Bugzilla script to send bug change notification
18 emails. That script changes between Bugzilla versions; the
19 'processmail' script used prior to 2.18 is replaced in 2.18 and
20 subsequent versions by 'config/sendbugmail.pl'. Note that these will
21 be run by Mercurial as the user pushing the change; you will need to
22 ensure the Bugzilla install file permissions are set appropriately.
24 Configuring the extension:
28 host Hostname of the MySQL server holding the Bugzilla
30 db Name of the Bugzilla database in MySQL. Default 'bugs'.
31 user Username to use to access MySQL server. Default 'bugs'.
32 password Password to use to access MySQL server.
33 timeout Database connection timeout (seconds). Default 5.
34 version Bugzilla version. Specify '3.0' for Bugzilla versions
35 3.0 and later, '2.18' for Bugzilla versions from 2.18
36 and '2.16' for versions prior to 2.18.
37 bzuser Fallback Bugzilla user name to record comments with, if
38 changeset committer cannot be found as a Bugzilla user.
39 bzdir Bugzilla install directory. Used by default notify.
40 Default '/var/www/html/bugzilla'.
41 notify The command to run to get Bugzilla to send bug change
42 notification emails. Substitutes from a map with 3
43 keys, 'bzdir', 'id' (bug id) and 'user' (committer
44 bugzilla email). Default depends on version; from 2.18
45 it is "cd %(bzdir)s && perl -T contrib/sendbugmail.pl
47 regexp Regular expression to match bug IDs in changeset commit
48 message. Must contain one "()" group. The default
49 expression matches 'Bug 1234', 'Bug no. 1234', 'Bug
50 number 1234', 'Bugs 1234,5678', 'Bug 1234 and 5678' and
51 variations thereof. Matching is case insensitive.
52 style The style file to use when formatting comments.
53 template Template to use when formatting comments. Overrides
54 style if specified. In addition to the usual Mercurial
55 keywords, the extension specifies:
56 {bug} The Bugzilla bug ID.
57 {root} The full pathname of the Mercurial
59 {webroot} Stripped pathname of the Mercurial
61 {hgweb} Base URL for browsing Mercurial
63 Default 'changeset {node|short} in repo {root} refers '
64 'to bug {bug}.\\ndetails:\\n\\t{desc|tabindent}'
65 strip The number of slashes to strip from the front of {root}
66 to produce {webroot}. Default 0.
67 usermap Path of file containing Mercurial committer ID to
68 Bugzilla user ID mappings. If specified, the file
69 should contain one mapping per line,
70 "committer"="Bugzilla user". See also the [usermap]
74 Any entries in this section specify mappings of Mercurial
75 committer ID to Bugzilla user ID. See also [bugzilla].usermap.
76 "committer"="Bugzilla user"
79 baseurl Base URL for browsing Mercurial repositories. Reference
80 from templates as {hgweb}.
82 Activating the extension:
88 # run bugzilla hook on every change pulled or pushed in here
89 incoming.bugzilla = python:hgext.bugzilla.hook
91 Example configuration:
93 This example configuration is for a collection of Mercurial
94 repositories in /var/local/hg/repos/ used with a local Bugzilla 3.2
95 installation in /opt/bugzilla-3.2.
102 bzdir=/opt/bugzilla-3.2
103 template=Changeset {node|short} in {root|basename}.\\n{hgweb}/{webroot}/rev/{node|short}\\n\\n{desc}\\n
107 baseurl=http://dev.domain.com/hg
112 Commits add a comment to the Bugzilla bug record of the form:
114 Changeset 3b16791d6642 in repository-name.
115 http://dev.domain.com/hg/repository-name/rev/3b16791d6642
117 Changeset commit comment. Bug 1234.
120 from mercurial.i18n import _
121 from mercurial.node import short
122 from mercurial import cmdutil, templater, util
128 return '(' + ','.join(map(str, ids)) + ')'
130 class bugzilla_2_16(object):
131 '''support for bugzilla version 2.16.'''
133 def __init__(self, ui):
135 host = self.ui.config('bugzilla', 'host', 'localhost')
136 user = self.ui.config('bugzilla', 'user', 'bugs')
137 passwd = self.ui.config('bugzilla', 'password')
138 db = self.ui.config('bugzilla', 'db', 'bugs')
139 timeout = int(self.ui.config('bugzilla', 'timeout', 5))
140 usermap = self.ui.config('bugzilla', 'usermap')
142 self.ui.readconfig(usermap, sections=['usermap'])
143 self.ui.note(_('connecting to %s:%s as %s, password %s\n') %
144 (host, db, user, '*' * len(passwd)))
145 self.conn = MySQLdb.connect(host=host, user=user, passwd=passwd,
146 db=db, connect_timeout=timeout)
147 self.cursor = self.conn.cursor()
148 self.longdesc_id = self.get_longdesc_id()
150 self.default_notify = "cd %(bzdir)s && ./processmail %(id)s %(user)s"
152 def run(self, *args, **kwargs):
154 self.ui.note(_('query: %s %s\n') % (args, kwargs))
156 self.cursor.execute(*args, **kwargs)
157 except MySQLdb.MySQLError:
158 self.ui.note(_('failed query: %s %s\n') % (args, kwargs))
161 def get_longdesc_id(self):
162 '''get identity of longdesc field'''
163 self.run('select fieldid from fielddefs where name = "longdesc"')
164 ids = self.cursor.fetchall()
166 raise util.Abort(_('unknown database schema'))
169 def filter_real_bug_ids(self, ids):
170 '''filter not-existing bug ids from list.'''
171 self.run('select bug_id from bugs where bug_id in %s' % buglist(ids))
172 return sorted([c[0] for c in self.cursor.fetchall()])
174 def filter_unknown_bug_ids(self, node, ids):
175 '''filter bug ids from list that already refer to this changeset.'''
177 self.run('''select bug_id from longdescs where
178 bug_id in %s and thetext like "%%%s%%"''' %
179 (buglist(ids), short(node)))
181 for (id,) in self.cursor.fetchall():
182 self.ui.status(_('bug %d already knows about changeset %s\n') %
185 return sorted(unknown)
187 def notify(self, ids, committer):
188 '''tell bugzilla to send mail.'''
190 self.ui.status(_('telling bugzilla to send mail:\n'))
191 (user, userid) = self.get_bugzilla_user(committer)
193 self.ui.status(_(' bug %s\n') % id)
194 cmdfmt = self.ui.config('bugzilla', 'notify', self.default_notify)
195 bzdir = self.ui.config('bugzilla', 'bzdir', '/var/www/html/bugzilla')
197 # Backwards-compatible with old notify string, which
198 # took one string. This will throw with a new format
202 cmd = cmdfmt % {'bzdir': bzdir, 'id': id, 'user': user}
203 self.ui.note(_('running notify command %s\n') % cmd)
204 fp = util.popen('(%s) 2>&1' % cmd)
209 raise util.Abort(_('bugzilla notify command %s') %
210 util.explain_exit(ret)[0])
211 self.ui.status(_('done\n'))
213 def get_user_id(self, user):
214 '''look up numeric bugzilla user id.'''
216 return self.user_ids[user]
221 self.ui.note(_('looking up user %s\n') % user)
222 self.run('''select userid from profiles
223 where login_name like %s''', user)
224 all = self.cursor.fetchall()
227 userid = int(all[0][0])
228 self.user_ids[user] = userid
231 def map_committer(self, user):
232 '''map name of committer to bugzilla user name.'''
233 for committer, bzuser in self.ui.configitems('usermap'):
234 if committer.lower() == user.lower():
238 def get_bugzilla_user(self, committer):
239 '''see if committer is a registered bugzilla user. Return
240 bugzilla username and userid if so. If not, return default
241 bugzilla username and userid.'''
242 user = self.map_committer(committer)
244 userid = self.get_user_id(user)
247 defaultuser = self.ui.config('bugzilla', 'bzuser')
249 raise util.Abort(_('cannot find bugzilla user id for %s') %
251 userid = self.get_user_id(defaultuser)
254 raise util.Abort(_('cannot find bugzilla user id for %s or %s') %
256 return (user, userid)
258 def add_comment(self, bugid, text, committer):
259 '''add comment to bug. try adding comment as committer of
260 changeset, otherwise as default bugzilla user.'''
261 (user, userid) = self.get_bugzilla_user(committer)
262 now = time.strftime('%Y-%m-%d %H:%M:%S')
263 self.run('''insert into longdescs
264 (bug_id, who, bug_when, thetext)
265 values (%s, %s, %s, %s)''',
266 (bugid, userid, now, text))
267 self.run('''insert into bugs_activity (bug_id, who, bug_when, fieldid)
268 values (%s, %s, %s, %s)''',
269 (bugid, userid, now, self.longdesc_id))
272 class bugzilla_2_18(bugzilla_2_16):
273 '''support for bugzilla 2.18 series.'''
275 def __init__(self, ui):
276 bugzilla_2_16.__init__(self, ui)
277 self.default_notify = "cd %(bzdir)s && perl -T contrib/sendbugmail.pl %(id)s %(user)s"
279 class bugzilla_3_0(bugzilla_2_18):
280 '''support for bugzilla 3.0 series.'''
282 def __init__(self, ui):
283 bugzilla_2_18.__init__(self, ui)
285 def get_longdesc_id(self):
286 '''get identity of longdesc field'''
287 self.run('select id from fielddefs where name = "longdesc"')
288 ids = self.cursor.fetchall()
290 raise util.Abort(_('unknown database schema'))
293 class bugzilla(object):
294 # supported versions of bugzilla. different versions have
297 '2.16': bugzilla_2_16,
298 '2.18': bugzilla_2_18,
302 _default_bug_re = (r'bugs?\s*,?\s*(?:#|nos?\.?|num(?:ber)?s?)?\s*'
303 r'((?:\d+\s*(?:,?\s*(?:and)?)?\s*)+)')
307 def __init__(self, ui, repo):
312 '''return object that knows how to talk to bugzilla version in
315 if bugzilla._bz is None:
316 bzversion = self.ui.config('bugzilla', 'version')
318 bzclass = bugzilla._versions[bzversion]
320 raise util.Abort(_('bugzilla version %s not supported') %
322 bugzilla._bz = bzclass(self.ui)
325 def __getattr__(self, key):
326 return getattr(self.bz(), key)
331 def find_bug_ids(self, ctx):
332 '''find valid bug ids that are referred to in changeset
333 comments and that do not already have references to this
336 if bugzilla._bug_re is None:
337 bugzilla._bug_re = re.compile(
338 self.ui.config('bugzilla', 'regexp', bugzilla._default_bug_re),
340 bugzilla._split_re = re.compile(r'\D+')
344 m = bugzilla._bug_re.search(ctx.description(), start)
348 for id in bugzilla._split_re.split(m.group(1)):
352 ids = self.filter_real_bug_ids(ids)
354 ids = self.filter_unknown_bug_ids(ctx.node(), ids)
357 def update(self, bugid, ctx):
358 '''update bugzilla bug with reference to changeset.'''
361 '''strip leading prefix of repo root and turn into
363 count = int(self.ui.config('bugzilla', 'strip', 0))
364 root = util.pconvert(root)
373 mapfile = self.ui.config('bugzilla', 'style')
374 tmpl = self.ui.config('bugzilla', 'template')
375 t = cmdutil.changeset_templater(self.ui, self.repo,
376 False, None, mapfile, False)
377 if not mapfile and not tmpl:
378 tmpl = _('changeset {node|short} in repo {root} refers '
379 'to bug {bug}.\ndetails:\n\t{desc|tabindent}')
381 tmpl = templater.parsestring(tmpl, quoted=False)
384 t.show(ctx, changes=ctx.changeset(),
386 hgweb=self.ui.config('web', 'baseurl'),
388 webroot=webroot(self.repo.root))
389 data = self.ui.popbuffer()
390 self.add_comment(bugid, data, util.email(ctx.user()))
392 def hook(ui, repo, hooktype, node=None, **kwargs):
393 '''add comment to bugzilla for each changeset that refers to a
394 bugzilla bug id. only add a comment once per bug, so same change
395 seen multiple times does not fill bug with duplicate data.'''
397 import MySQLdb as mysql
400 except ImportError, err:
401 raise util.Abort(_('python mysql support not available: %s') % err)
404 raise util.Abort(_('hook type %s does not pass a changeset id') %
407 bz = bugzilla(ui, repo)
409 ids = bz.find_bug_ids(ctx)
413 bz.notify(ids, util.email(ctx.user()))
414 except MySQLdb.MySQLError, err:
415 raise util.Abort(_('database error: %s') % err[1])