Debian Codegraph @

hgext/bugzilla.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # bugzilla.py - bugzilla integration for mercurial
2 #
3 # Copyright 2006 Vadim Gelfer <[email protected]>
4 # Copyright 2011-4 Jim Hague <[email protected]>
5 #
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
8
9 '''hooks for integrating with the Bugzilla bug tracker
10
11 This hook extension adds comments on bugs in Bugzilla when changesets
12 that refer to bugs by Bugzilla ID are seen. The comment is formatted using
13 the Mercurial template mechanism.
14
15 The bug references can optionally include an update for Bugzilla of the
16 hours spent working on the bug. Bugs can also be marked fixed.
17
18 Four basic modes of access to Bugzilla are provided:
19
20 1. Access via the Bugzilla REST-API. Requires bugzilla 5.0 or later.
21
22 2. Access via the Bugzilla XMLRPC interface. Requires Bugzilla 3.4 or later.
23
24 3. Check data via the Bugzilla XMLRPC interface and submit bug change
25 via email to Bugzilla email interface. Requires Bugzilla 3.4 or later.
26
27 4. Writing directly to the Bugzilla database. Only Bugzilla installations
28 using MySQL are supported. Requires Python MySQLdb.
29
30 Writing directly to the database is susceptible to schema changes, and
31 relies on a Bugzilla contrib script to send out bug change
32 notification emails. This script runs as the user running Mercurial,
33 must be run on the host with the Bugzilla install, and requires
34 permission to read Bugzilla configuration details and the necessary
35 MySQL user and password to have full access rights to the Bugzilla
36 database. For these reasons this access mode is now considered
37 deprecated, and will not be updated for new Bugzilla versions going
38 forward. Only adding comments is supported in this access mode.
39
40 Access via XMLRPC needs a Bugzilla username and password to be specified
41 in the configuration. Comments are added under that username. Since the
42 configuration must be readable by all Mercurial users, it is recommended
43 that the rights of that user are restricted in Bugzilla to the minimum
44 necessary to add comments. Marking bugs fixed requires Bugzilla 4.0 and later.
45
46 Access via XMLRPC/email uses XMLRPC to query Bugzilla, but sends
47 email to the Bugzilla email interface to submit comments to bugs.
48 The From: address in the email is set to the email address of the Mercurial
49 user, so the comment appears to come from the Mercurial user. In the event
50 that the Mercurial user email is not recognized by Bugzilla as a Bugzilla
51 user, the email associated with the Bugzilla username used to log into
52 Bugzilla is used instead as the source of the comment. Marking bugs fixed
53 works on all supported Bugzilla versions.
54
55 Access via the REST-API needs either a Bugzilla username and password
56 or an apikey specified in the configuration. Comments are made under
57 the given username or the user associated with the apikey in Bugzilla.
58
59 Configuration items common to all access modes:
60
61 bugzilla.version
62 The access type to use. Values recognized are:
63
64 :``restapi``: Bugzilla REST-API, Bugzilla 5.0 and later.
65 :``xmlrpc``: Bugzilla XMLRPC interface.
66 :``xmlrpc+email``: Bugzilla XMLRPC and email interfaces.
67 :``3.0``: MySQL access, Bugzilla 3.0 and later.
68 :``2.18``: MySQL access, Bugzilla 2.18 and up to but not
69 including 3.0.
70 :``2.16``: MySQL access, Bugzilla 2.16 and up to but not
71 including 2.18.
72
73 bugzilla.regexp
74 Regular expression to match bug IDs for update in changeset commit message.
75 It must contain one "()" named group ``<ids>`` containing the bug
76 IDs separated by non-digit characters. It may also contain
77 a named group ``<hours>`` with a floating-point number giving the
78 hours worked on the bug. If no named groups are present, the first
79 "()" group is assumed to contain the bug IDs, and work time is not
80 updated. The default expression matches ``Bug 1234``, ``Bug no. 1234``,
81 ``Bug number 1234``, ``Bugs 1234,5678``, ``Bug 1234 and 5678`` and
82 variations thereof, followed by an hours number prefixed by ``h`` or
83 ``hours``, e.g. ``hours 1.5``. Matching is case insensitive.
84
85 bugzilla.fixregexp
86 Regular expression to match bug IDs for marking fixed in changeset
87 commit message. This must contain a "()" named group ``<ids>` containing
88 the bug IDs separated by non-digit characters. It may also contain
89 a named group ``<hours>`` with a floating-point number giving the
90 hours worked on the bug. If no named groups are present, the first
91 "()" group is assumed to contain the bug IDs, and work time is not
92 updated. The default expression matches ``Fixes 1234``, ``Fixes bug 1234``,
93 ``Fixes bugs 1234,5678``, ``Fixes 1234 and 5678`` and
94 variations thereof, followed by an hours number prefixed by ``h`` or
95 ``hours``, e.g. ``hours 1.5``. Matching is case insensitive.
96
97 bugzilla.fixstatus
98 The status to set a bug to when marking fixed. Default ``RESOLVED``.
99
100 bugzilla.fixresolution
101 The resolution to set a bug to when marking fixed. Default ``FIXED``.
102
103 bugzilla.style
104 The style file to use when formatting comments.
105
106 bugzilla.template
107 Template to use when formatting comments. Overrides style if
108 specified. In addition to the usual Mercurial keywords, the
109 extension specifies:
110
111 :``{bug}``: The Bugzilla bug ID.
112 :``{root}``: The full pathname of the Mercurial repository.
113 :``{webroot}``: Stripped pathname of the Mercurial repository.
114 :``{hgweb}``: Base URL for browsing Mercurial repositories.
115
116 Default ``changeset {node|short} in repo {root} refers to bug
117 {bug}.\\ndetails:\\n\\t{desc|tabindent}``
118
119 bugzilla.strip
120 The number of path separator characters to strip from the front of
121 the Mercurial repository path (``{root}`` in templates) to produce
122 ``{webroot}``. For example, a repository with ``{root}``
123 ``/var/local/my-project`` with a strip of 2 gives a value for
124 ``{webroot}`` of ``my-project``. Default 0.
125
126 web.baseurl
127 Base URL for browsing Mercurial repositories. Referenced from
128 templates as ``{hgweb}``.
129
130 Configuration items common to XMLRPC+email and MySQL access modes:
131
132 bugzilla.usermap
133 Path of file containing Mercurial committer email to Bugzilla user email
134 mappings. If specified, the file should contain one mapping per
135 line::
136
137 committer = Bugzilla user
138
139 See also the ``[usermap]`` section.
140
141 The ``[usermap]`` section is used to specify mappings of Mercurial
142 committer email to Bugzilla user email. See also ``bugzilla.usermap``.
143 Contains entries of the form ``committer = Bugzilla user``.
144
145 XMLRPC and REST-API access mode configuration:
146
147 bugzilla.bzurl
148 The base URL for the Bugzilla installation.
149 Default ``http://localhost/bugzilla``.
150
151 bugzilla.user
152 The username to use to log into Bugzilla via XMLRPC. Default
153 ``bugs``.
154
155 bugzilla.password
156 The password for Bugzilla login.
157
158 REST-API access mode uses the options listed above as well as:
159
160 bugzilla.apikey
161 An apikey generated on the Bugzilla instance for api access.
162 Using an apikey removes the need to store the user and password
163 options.
164
165 XMLRPC+email access mode uses the XMLRPC access mode configuration items,
166 and also:
167
168 bugzilla.bzemail
169 The Bugzilla email address.
170
171 In addition, the Mercurial email settings must be configured. See the
172 documentation in hgrc(5), sections ``[email]`` and ``[smtp]``.
173
174 MySQL access mode configuration:
175
176 bugzilla.host
177 Hostname of the MySQL server holding the Bugzilla database.
178 Default ``localhost``.
179
180 bugzilla.db
181 Name of the Bugzilla database in MySQL. Default ``bugs``.
182
183 bugzilla.user
184 Username to use to access MySQL server. Default ``bugs``.
185
186 bugzilla.password
187 Password to use to access MySQL server.
188
189 bugzilla.timeout
190 Database connection timeout (seconds). Default 5.
191
192 bugzilla.bzuser
193 Fallback Bugzilla user name to record comments with, if changeset
194 committer cannot be found as a Bugzilla user.
195
196 bugzilla.bzdir
197 Bugzilla install directory. Used by default notify. Default
198 ``/var/www/html/bugzilla``.
199
200 bugzilla.notify
201 The command to run to get Bugzilla to send bug change notification
202 emails. Substitutes from a map with 3 keys, ``bzdir``, ``id`` (bug
203 id) and ``user`` (committer bugzilla email). Default depends on
204 version; from 2.18 it is "cd %(bzdir)s && perl -T
205 contrib/sendbugmail.pl %(id)s %(user)s".
206
207 Activating the extension::
208
209 [extensions]
210 bugzilla =
211
212 [hooks]
213 # run bugzilla hook on every change pulled or pushed in here
214 incoming.bugzilla = python:hgext.bugzilla.hook
215
216 Example configurations:
217
218 XMLRPC example configuration. This uses the Bugzilla at
219 ``http://my-project.org/bugzilla``, logging in as user
220 ``[email protected]`` with password ``plugh``. It is used with a
221 collection of Mercurial repositories in ``/var/local/hg/repos/``,
222 with a web interface at ``http://my-project.org/hg``. ::
223
224 [bugzilla]
225 bzurl=http://my-project.org/bugzilla
226 [email protected]
227 password=plugh
228 version=xmlrpc
229 template=Changeset {node|short} in {root|basename}.
230 {hgweb}/{webroot}/rev/{node|short}\\n
231 {desc}\\n
232 strip=5
233
234 [web]
235 baseurl=http://my-project.org/hg
236
237 XMLRPC+email example configuration. This uses the Bugzilla at
238 ``http://my-project.org/bugzilla``, logging in as user
239 ``[email protected]`` with password ``plugh``. It is used with a
240 collection of Mercurial repositories in ``/var/local/hg/repos/``,
241 with a web interface at ``http://my-project.org/hg``. Bug comments
242 are sent to the Bugzilla email address
243 ``[email protected]``. ::
244
245 [bugzilla]
246 bzurl=http://my-project.org/bugzilla
247 [email protected]
248 password=plugh
249 version=xmlrpc+email
250 [email protected]
251 template=Changeset {node|short} in {root|basename}.
252 {hgweb}/{webroot}/rev/{node|short}\\n
253 {desc}\\n
254 strip=5
255
256 [web]
257 baseurl=http://my-project.org/hg
258
259 [usermap]
260 [email protected][email protected]
261
262 MySQL example configuration. This has a local Bugzilla 3.2 installation
263 in ``/opt/bugzilla-3.2``. The MySQL database is on ``localhost``,
264 the Bugzilla database name is ``bugs`` and MySQL is
265 accessed with MySQL username ``bugs`` password ``XYZZY``. It is used
266 with a collection of Mercurial repositories in ``/var/local/hg/repos/``,
267 with a web interface at ``http://my-project.org/hg``. ::
268
269 [bugzilla]
270 host=localhost
271 password=XYZZY
272 version=3.0
273 [email protected]
274 bzdir=/opt/bugzilla-3.2
275 template=Changeset {node|short} in {root|basename}.
276 {hgweb}/{webroot}/rev/{node|short}\\n
277 {desc}\\n
278 strip=5
279
280 [web]
281 baseurl=http://my-project.org/hg
282
283 [usermap]
284 [email protected][email protected]
285
286 All the above add a comment to the Bugzilla bug record of the form::
287
288 Changeset 3b16791d6642 in repository-name.
289 http://my-project.org/hg/repository-name/rev/3b16791d6642
290
291 Changeset commit comment. Bug 1234.
292 '''
293
294 from __future__ import annotations
295
296 import json
297 import re
298 import time
299
300 from mercurial.i18n import _
301 from mercurial.node import short
302 from mercurial import (
303 error,
304 logcmdutil,
305 mail,
306 pycompat,
307 registrar,
308 url,
309 util,
310 )
311 from mercurial.utils import (
312 procutil,
313 stringutil,
314 )
315
316 xmlrpclib = util.xmlrpclib
317
318 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
319 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
320 # be specifying the version(s) of Mercurial they are tested with, or
321 # leave the attribute unspecified.
322 testedwith = b'ships-with-hg-core'
323
324 configtable = {}
325 configitem = registrar.configitem(configtable)
326
327 configitem(
328 b'bugzilla',
329 b'apikey',
330 default=b'',
331 )
332 configitem(
333 b'bugzilla',
334 b'bzdir',
335 default=b'/var/www/html/bugzilla',
336 )
337 configitem(
338 b'bugzilla',
339 b'bzemail',
340 default=None,
341 )
342 configitem(
343 b'bugzilla',
344 b'bzurl',
345 default=b'http://localhost/bugzilla/',
346 )
347 configitem(
348 b'bugzilla',
349 b'bzuser',
350 default=None,
351 )
352 configitem(
353 b'bugzilla',
354 b'db',
355 default=b'bugs',
356 )
357 configitem(
358 b'bugzilla',
359 b'fixregexp',
360 default=(
361 br'fix(?:es)?\s*(?:bugs?\s*)?,?\s*'
362 br'(?:nos?\.?|num(?:ber)?s?)?\s*'
363 br'(?P<ids>(?:#?\d+\s*(?:,?\s*(?:and)?)?\s*)+)'
364 br'\.?\s*(?:h(?:ours?)?\s*(?P<hours>\d*(?:\.\d+)?))?'
365 ),
366 )
367 configitem(
368 b'bugzilla',
369 b'fixresolution',
370 default=b'FIXED',
371 )
372 configitem(
373 b'bugzilla',
374 b'fixstatus',
375 default=b'RESOLVED',
376 )
377 configitem(
378 b'bugzilla',
379 b'host',
380 default=b'localhost',
381 )
382 configitem(
383 b'bugzilla',
384 b'notify',
385 default=configitem.dynamicdefault,
386 )
387 configitem(
388 b'bugzilla',
389 b'password',
390 default=None,
391 )
392 configitem(
393 b'bugzilla',
394 b'regexp',
395 default=(
396 br'bugs?\s*,?\s*(?:#|nos?\.?|num(?:ber)?s?)?\s*'
397 br'(?P<ids>(?:\d+\s*(?:,?\s*(?:and)?)?\s*)+)'
398 br'\.?\s*(?:h(?:ours?)?\s*(?P<hours>\d*(?:\.\d+)?))?'
399 ),
400 )
401 configitem(
402 b'bugzilla',
403 b'strip',
404 default=0,
405 )
406 configitem(
407 b'bugzilla',
408 b'style',
409 default=None,
410 )
411 configitem(
412 b'bugzilla',
413 b'template',
414 default=None,
415 )
416 configitem(
417 b'bugzilla',
418 b'timeout',
419 default=5,
420 )
421 configitem(
422 b'bugzilla',
423 b'user',
424 default=b'bugs',
425 )
426 configitem(
427 b'bugzilla',
428 b'usermap',
429 default=None,
430 )
431 configitem(
432 b'bugzilla',
433 b'version',
434 default=None,
435 )
436
437
438 class bzaccess:
439 '''Base class for access to Bugzilla.'''
440
441 def __init__(self, ui):
442 self.ui = ui
443 usermap = self.ui.config(b'bugzilla', b'usermap')
444 if usermap:
445 self.ui.readconfig(usermap, sections=[b'usermap'])
446
447 def map_committer(self, user):
448 '''map name of committer to Bugzilla user name.'''
449 for committer, bzuser in self.ui.configitems(b'usermap'):
450 if committer.lower() == user.lower():
451 return bzuser
452 return user
453
454 # Methods to be implemented by access classes.
455 #
456 # 'bugs' is a dict keyed on bug id, where values are a dict holding
457 # updates to bug state. Recognized dict keys are:
458 #
459 # 'hours': Value, float containing work hours to be updated.
460 # 'fix': If key present, bug is to be marked fixed. Value ignored.
461
462 def filter_real_bug_ids(self, bugs):
463 '''remove bug IDs that do not exist in Bugzilla from bugs.'''
464
465 def filter_cset_known_bug_ids(self, node, bugs):
466 '''remove bug IDs where node occurs in comment text from bugs.'''
467
468 def updatebug(self, bugid, newstate, text, committer):
469 """update the specified bug. Add comment text and set new states.
470
471 If possible add the comment as being from the committer of
472 the changeset. Otherwise use the default Bugzilla user.
473 """
474
475 def notify(self, bugs, committer):
476 """Force sending of Bugzilla notification emails.
477
478 Only required if the access method does not trigger notification
479 emails automatically.
480 """
481
482
483 # Bugzilla via direct access to MySQL database.
484 class bzmysql(bzaccess):
485 """Support for direct MySQL access to Bugzilla.
486
487 The earliest Bugzilla version this is tested with is version 2.16.
488
489 If your Bugzilla is version 3.4 or above, you are strongly
490 recommended to use the XMLRPC access method instead.
491 """
492
493 @staticmethod
494 def sql_buglist(ids):
495 '''return SQL-friendly list of bug ids'''
496 return b'(' + b','.join(map(str, ids)) + b')'
497
498 _MySQLdb = None
499
500 def __init__(self, ui):
501 try:
502 import MySQLdb as mysql
503
504 bzmysql._MySQLdb = mysql
505 except ImportError as err:
506 raise error.Abort(
507 _(b'python mysql support not available: %s') % err
508 )
509
510 bzaccess.__init__(self, ui)
511
512 host = self.ui.config(b'bugzilla', b'host')
513 user = self.ui.config(b'bugzilla', b'user')
514 passwd = self.ui.config(b'bugzilla', b'password')
515 db = self.ui.config(b'bugzilla', b'db')
516 timeout = self.ui.configint(b'bugzilla', b'timeout')
517 self.ui.note(
518 _(b'connecting to %s:%s as %s, password %s\n')
519 % (host, db, user, b'*' * len(passwd))
520 )
521 self.conn = bzmysql._MySQLdb.connect(
522 host=host, user=user, passwd=passwd, db=db, connect_timeout=timeout
523 )
524 self.cursor = self.conn.cursor()
525 self.longdesc_id = self.get_longdesc_id()
526 self.user_ids = {}
527 self.default_notify = b"cd %(bzdir)s && ./processmail %(id)s %(user)s"
528
529 def run(self, *args, **kwargs):
530 '''run a query.'''
531 self.ui.note(_(b'query: %s %s\n') % (args, kwargs))
532 try:
533 self.cursor.execute(*args, **kwargs)
534 except bzmysql._MySQLdb.MySQLError:
535 self.ui.note(_(b'failed query: %s %s\n') % (args, kwargs))
536 raise
537
538 def get_longdesc_id(self):
539 '''get identity of longdesc field'''
540 self.run(b'select fieldid from fielddefs where name = "longdesc"')
541 ids = self.cursor.fetchall()
542 if len(ids) != 1:
543 raise error.Abort(_(b'unknown database schema'))
544 return ids[0][0]
545
546 def filter_real_bug_ids(self, bugs):
547 '''filter not-existing bugs from set.'''
548 self.run(
549 b'select bug_id from bugs where bug_id in %s'
550 % bzmysql.sql_buglist(bugs.keys())
551 )
552 existing = [id for (id,) in self.cursor.fetchall()]
553 for id in bugs.keys():
554 if id not in existing:
555 self.ui.status(_(b'bug %d does not exist\n') % id)
556 del bugs[id]
557
558 def filter_cset_known_bug_ids(self, node, bugs):
559 '''filter bug ids that already refer to this changeset from set.'''
560 self.run(
561 '''select bug_id from longdescs where
562 bug_id in %s and thetext like "%%%s%%"'''
563 % (bzmysql.sql_buglist(bugs.keys()), short(node))
564 )
565 for (id,) in self.cursor.fetchall():
566 self.ui.status(
567 _(b'bug %d already knows about changeset %s\n')
568 % (id, short(node))
569 )
570 del bugs[id]
571
572 def notify(self, bugs, committer):
573 '''tell bugzilla to send mail.'''
574 self.ui.status(_(b'telling bugzilla to send mail:\n'))
575 (user, userid) = self.get_bugzilla_user(committer)
576 for id in bugs.keys():
577 self.ui.status(_(b' bug %s\n') % id)
578 cmdfmt = self.ui.config(b'bugzilla', b'notify', self.default_notify)
579 bzdir = self.ui.config(b'bugzilla', b'bzdir')
580 try:
581 # Backwards-compatible with old notify string, which
582 # took one string. This will throw with a new format
583 # string.
584 cmd = cmdfmt % id
585 except TypeError:
586 cmd = cmdfmt % {b'bzdir': bzdir, b'id': id, b'user': user}
587 self.ui.note(_(b'running notify command %s\n') % cmd)
588 fp = procutil.popen(b'(%s) 2>&1' % cmd, b'rb')
589 out = util.fromnativeeol(fp.read())
590 ret = fp.close()
591 if ret:
592 self.ui.warn(out)
593 raise error.Abort(
594 _(b'bugzilla notify command %s') % procutil.explainexit(ret)
595 )
596 self.ui.status(_(b'done\n'))
597
598 def get_user_id(self, user):
599 '''look up numeric bugzilla user id.'''
600 try:
601 return self.user_ids[user]
602 except KeyError:
603 try:
604 userid = int(user)
605 except ValueError:
606 self.ui.note(_(b'looking up user %s\n') % user)
607 self.run(
608 '''select userid from profiles
609 where login_name like %s''',
610 user,
611 )
612 all = self.cursor.fetchall()
613 if len(all) != 1:
614 raise KeyError(user)
615 userid = int(all[0][0])
616 self.user_ids[user] = userid
617 return userid
618
619 def get_bugzilla_user(self, committer):
620 """See if committer is a registered bugzilla user. Return
621 bugzilla username and userid if so. If not, return default
622 bugzilla username and userid."""
623 user = self.map_committer(committer)
624 try:
625 userid = self.get_user_id(user)
626 except KeyError:
627 try:
628 defaultuser = self.ui.config(b'bugzilla', b'bzuser')
629 if not defaultuser:
630 raise error.Abort(
631 _(b'cannot find bugzilla user id for %s') % user
632 )
633 userid = self.get_user_id(defaultuser)
634 user = defaultuser
635 except KeyError:
636 raise error.Abort(
637 _(b'cannot find bugzilla user id for %s or %s')
638 % (user, defaultuser)
639 )
640 return (user, userid)
641
642 def updatebug(self, bugid, newstate, text, committer):
643 """update bug state with comment text.
644
645 Try adding comment as committer of changeset, otherwise as
646 default bugzilla user."""
647 if len(newstate) > 0:
648 self.ui.warn(_(b"Bugzilla/MySQL cannot update bug state\n"))
649
650 (user, userid) = self.get_bugzilla_user(committer)
651 now = time.strftime('%Y-%m-%d %H:%M:%S')
652 self.run(
653 '''insert into longdescs
654 (bug_id, who, bug_when, thetext)
655 values (%s, %s, %s, %s)''',
656 (bugid, userid, now, text),
657 )
658 self.run(
659 '''insert into bugs_activity (bug_id, who, bug_when, fieldid)
660 values (%s, %s, %s, %s)''',
661 (bugid, userid, now, self.longdesc_id),
662 )
663 self.conn.commit()
664
665
666 class bzmysql_2_18(bzmysql):
667 '''support for bugzilla 2.18 series.'''
668
669 def __init__(self, ui):
670 bzmysql.__init__(self, ui)
671 self.default_notify = (
672 b"cd %(bzdir)s && perl -T contrib/sendbugmail.pl %(id)s %(user)s"
673 )
674
675
676 class bzmysql_3_0(bzmysql_2_18):
677 '''support for bugzilla 3.0 series.'''
678
679 def __init__(self, ui):
680 bzmysql_2_18.__init__(self, ui)
681
682 def get_longdesc_id(self):
683 '''get identity of longdesc field'''
684 self.run(b'select id from fielddefs where name = "longdesc"')
685 ids = self.cursor.fetchall()
686 if len(ids) != 1:
687 raise error.Abort(_(b'unknown database schema'))
688 return ids[0][0]
689
690
691 # Bugzilla via XMLRPC interface.
692
693
694 class cookietransportrequest:
695 """A Transport request method that retains cookies over its lifetime.
696
697 The regular xmlrpclib transports ignore cookies. Which causes
698 a bit of a problem when you need a cookie-based login, as with
699 the Bugzilla XMLRPC interface prior to 4.4.3.
700
701 So this is a helper for defining a Transport which looks for
702 cookies being set in responses and saves them to add to all future
703 requests.
704 """
705
706 # Inspiration drawn from
707 # http://blog.godson.in/2010/09/how-to-make-python-xmlrpclib-client.html
708 # http://www.itkovian.net/base/transport-class-for-pythons-xml-rpc-lib/
709
710 cookies = []
711
712 def send_cookies(self, connection):
713 if self.cookies:
714 for cookie in self.cookies:
715 connection.putheader(b"Cookie", cookie)
716
717 def request(self, host, handler, request_body, verbose=0):
718 self.verbose = verbose
719 self.accept_gzip_encoding = False
720
721 # issue XML-RPC request
722 h = self.make_connection(host)
723 if verbose:
724 h.set_debuglevel(1)
725
726 self.send_request(h, handler, request_body)
727 self.send_host(h, host)
728 self.send_cookies(h)
729 self.send_user_agent(h)
730 self.send_content(h, request_body)
731
732 # Deal with differences between Python 2.6 and 2.7.
733 # In the former h is a HTTP(S). In the latter it's a
734 # HTTP(S)Connection. Luckily, the 2.6 implementation of
735 # HTTP(S) has an underlying HTTP(S)Connection, so extract
736 # that and use it.
737 try:
738 response = h.getresponse()
739 except AttributeError:
740 response = h._conn.getresponse()
741
742 # Add any cookie definitions to our list.
743 for header in response.msg.getallmatchingheaders(b"Set-Cookie"):
744 val = header.split(b": ", 1)[1]
745 cookie = val.split(b";", 1)[0]
746 self.cookies.append(cookie)
747
748 if response.status != 200:
749 raise xmlrpclib.ProtocolError(
750 host + handler,
751 response.status,
752 response.reason,
753 response.msg.headers,
754 )
755
756 payload = response.read()
757 parser, unmarshaller = self.getparser()
758 parser.feed(payload)
759 parser.close()
760
761 return unmarshaller.close()
762
763
764 # The explicit calls to the underlying xmlrpclib __init__() methods are
765 # necessary. The xmlrpclib.Transport classes are old-style classes, and
766 # it turns out their __init__() doesn't get called when doing multiple
767 # inheritance with a new-style class.
768 class cookietransport(cookietransportrequest, xmlrpclib.Transport):
769 def __init__(self, use_datetime=0):
770 if hasattr(xmlrpclib.Transport, "__init__"):
771 xmlrpclib.Transport.__init__(self, use_datetime)
772
773
774 class cookiesafetransport(cookietransportrequest, xmlrpclib.SafeTransport):
775 def __init__(self, use_datetime=0):
776 if hasattr(xmlrpclib.Transport, "__init__"):
777 xmlrpclib.SafeTransport.__init__(self, use_datetime)
778
779
780 class bzxmlrpc(bzaccess):
781 """Support for access to Bugzilla via the Bugzilla XMLRPC API.
782
783 Requires a minimum Bugzilla version 3.4.
784 """
785
786 def __init__(self, ui):
787 bzaccess.__init__(self, ui)
788
789 bzweb = self.ui.config(b'bugzilla', b'bzurl')
790 bzweb = bzweb.rstrip(b"/") + b"/xmlrpc.cgi"
791
792 user = self.ui.config(b'bugzilla', b'user')
793 passwd = self.ui.config(b'bugzilla', b'password')
794
795 self.fixstatus = self.ui.config(b'bugzilla', b'fixstatus')
796 self.fixresolution = self.ui.config(b'bugzilla', b'fixresolution')
797
798 self.bzproxy = xmlrpclib.ServerProxy(
799 pycompat.strurl(bzweb), self.transport(bzweb)
800 )
801 ver = self.bzproxy.Bugzilla.version()[b'version'].split(b'.')
802 self.bzvermajor = int(ver[0])
803 self.bzverminor = int(ver[1])
804 login = self.bzproxy.User.login(
805 {b'login': user, b'password': passwd, b'restrict_login': True}
806 )
807 self.bztoken = login.get(b'token', b'')
808
809 def transport(self, uri):
810 if util.urlreq.urlparse(uri, b"http")[0] == b"https":
811 return cookiesafetransport()
812 else:
813 return cookietransport()
814
815 def get_bug_comments(self, id):
816 """Return a string with all comment text for a bug."""
817 c = self.bzproxy.Bug.comments(
818 {b'ids': [id], b'include_fields': [b'text'], b'token': self.bztoken}
819 )
820 return b''.join(
821 [t[b'text'] for t in c[b'bugs'][b'%d' % id][b'comments']]
822 )
823
824 def filter_real_bug_ids(self, bugs):
825 probe = self.bzproxy.Bug.get(
826 {
827 b'ids': sorted(bugs.keys()),
828 b'include_fields': [],
829 b'permissive': True,
830 b'token': self.bztoken,
831 }
832 )
833 for badbug in probe[b'faults']:
834 id = badbug[b'id']
835 self.ui.status(_(b'bug %d does not exist\n') % id)
836 del bugs[id]
837
838 def filter_cset_known_bug_ids(self, node, bugs):
839 for id in sorted(bugs.keys()):
840 if self.get_bug_comments(id).find(short(node)) != -1:
841 self.ui.status(
842 _(b'bug %d already knows about changeset %s\n')
843 % (id, short(node))
844 )
845 del bugs[id]
846
847 def updatebug(self, bugid, newstate, text, committer):
848 args = {}
849 if b'hours' in newstate:
850 args[b'work_time'] = newstate[b'hours']
851
852 if self.bzvermajor >= 4:
853 args[b'ids'] = [bugid]
854 args[b'comment'] = {b'body': text}
855 if b'fix' in newstate:
856 args[b'status'] = self.fixstatus
857 args[b'resolution'] = self.fixresolution
858 args[b'token'] = self.bztoken
859 self.bzproxy.Bug.update(args)
860 else:
861 if b'fix' in newstate:
862 self.ui.warn(
863 _(
864 b"Bugzilla/XMLRPC needs Bugzilla 4.0 or later "
865 b"to mark bugs fixed\n"
866 )
867 )
868 args[b'id'] = bugid
869 args[b'comment'] = text
870 self.bzproxy.Bug.add_comment(args)
871
872
873 class bzxmlrpcemail(bzxmlrpc):
874 """Read data from Bugzilla via XMLRPC, send updates via email.
875
876 Advantages of sending updates via email:
877 1. Comments can be added as any user, not just logged in user.
878 2. Bug statuses or other fields not accessible via XMLRPC can
879 potentially be updated.
880
881 There is no XMLRPC function to change bug status before Bugzilla
882 4.0, so bugs cannot be marked fixed via XMLRPC before Bugzilla 4.0.
883 But bugs can be marked fixed via email from 3.4 onwards.
884 """
885
886 # The email interface changes subtly between 3.4 and 3.6. In 3.4,
887 # in-email fields are specified as '@<fieldname> = <value>'. In
888 # 3.6 this becomes '@<fieldname> <value>'. And fieldname @bug_id
889 # in 3.4 becomes @id in 3.6. 3.6 and 4.0 both maintain backwards
890 # compatibility, but rather than rely on this use the new format for
891 # 4.0 onwards.
892
893 def __init__(self, ui):
894 bzxmlrpc.__init__(self, ui)
895
896 self.bzemail = self.ui.config(b'bugzilla', b'bzemail')
897 if not self.bzemail:
898 raise error.Abort(_(b"configuration 'bzemail' missing"))
899 mail.validateconfig(self.ui)
900
901 def makecommandline(self, fieldname, value):
902 if self.bzvermajor >= 4:
903 return b"@%s %s" % (fieldname, pycompat.bytestr(value))
904 else:
905 if fieldname == b"id":
906 fieldname = b"bug_id"
907 return b"@%s = %s" % (fieldname, pycompat.bytestr(value))
908
909 def send_bug_modify_email(self, bugid, commands, comment, committer):
910 """send modification message to Bugzilla bug via email.
911
912 The message format is documented in the Bugzilla email_in.pl
913 specification. commands is a list of command lines, comment is the
914 comment text.
915
916 To stop users from crafting commit comments with
917 Bugzilla commands, specify the bug ID via the message body, rather
918 than the subject line, and leave a blank line after it.
919 """
920 user = self.map_committer(committer)
921 matches = self.bzproxy.User.get(
922 {b'match': [user], b'token': self.bztoken}
923 )
924 if not matches[b'users']:
925 user = self.ui.config(b'bugzilla', b'user')
926 matches = self.bzproxy.User.get(
927 {b'match': [user], b'token': self.bztoken}
928 )
929 if not matches[b'users']:
930 raise error.Abort(
931 _(b"default bugzilla user %s email not found") % user
932 )
933 user = matches[b'users'][0][b'email']
934 commands.append(self.makecommandline(b"id", bugid))
935
936 text = b"\n".join(commands) + b"\n\n" + comment
937
938 _charsets = mail._charsets(self.ui)
939 user = mail.addressencode(self.ui, user, _charsets)
940 bzemail = mail.addressencode(self.ui, self.bzemail, _charsets)
941 msg = mail.mimeencode(self.ui, text, _charsets)
942 msg[b'From'] = user
943 msg[b'To'] = bzemail
944 msg[b'Subject'] = mail.headencode(
945 self.ui, b"Bug modification", _charsets
946 )
947 sendmail = mail.connect(self.ui)
948 sendmail(user, bzemail, msg.as_string())
949
950 def updatebug(self, bugid, newstate, text, committer):
951 cmds = []
952 if b'hours' in newstate:
953 cmds.append(self.makecommandline(b"work_time", newstate[b'hours']))
954 if b'fix' in newstate:
955 cmds.append(self.makecommandline(b"bug_status", self.fixstatus))
956 cmds.append(self.makecommandline(b"resolution", self.fixresolution))
957 self.send_bug_modify_email(bugid, cmds, text, committer)
958
959
960 class NotFound(LookupError):
961 pass
962
963
964 class bzrestapi(bzaccess):
965 """Read and write bugzilla data using the REST API available since
966 Bugzilla 5.0.
967 """
968
969 def __init__(self, ui):
970 bzaccess.__init__(self, ui)
971 bz = self.ui.config(b'bugzilla', b'bzurl')
972 self.bzroot = b'/'.join([bz, b'rest'])
973 self.apikey = self.ui.config(b'bugzilla', b'apikey')
974 self.user = self.ui.config(b'bugzilla', b'user')
975 self.passwd = self.ui.config(b'bugzilla', b'password')
976 self.fixstatus = self.ui.config(b'bugzilla', b'fixstatus')
977 self.fixresolution = self.ui.config(b'bugzilla', b'fixresolution')
978
979 def apiurl(self, targets, include_fields=None):
980 url = b'/'.join([self.bzroot] + [pycompat.bytestr(t) for t in targets])
981 qv = {}
982 if self.apikey:
983 qv[b'api_key'] = self.apikey
984 elif self.user and self.passwd:
985 qv[b'login'] = self.user
986 qv[b'password'] = self.passwd
987 if include_fields:
988 qv[b'include_fields'] = include_fields
989 if qv:
990 url = b'%s?%s' % (url, util.urlreq.urlencode(qv))
991 return url
992
993 def _fetch(self, burl):
994 try:
995 resp = url.open(self.ui, burl)
996 return pycompat.json_loads(resp.read())
997 except util.urlerr.httperror as inst:
998 if inst.code == 401:
999 raise error.Abort(_(b'authorization failed'))
1000 if inst.code == 404:
1001 raise NotFound()
1002 else:
1003 raise
1004
1005 def _submit(self, burl, data, method=b'POST'):
1006 data = json.dumps(data)
1007 if method == b'PUT':
1008
1009 class putrequest(util.urlreq.request):
1010 def get_method(self):
1011 return b'PUT'
1012
1013 request_type = putrequest
1014 else:
1015 request_type = util.urlreq.request
1016 req = request_type(burl, data, {b'Content-Type': b'application/json'})
1017 try:
1018 resp = url.opener(self.ui).open(req)
1019 return pycompat.json_loads(resp.read())
1020 except util.urlerr.httperror as inst:
1021 if inst.code == 401:
1022 raise error.Abort(_(b'authorization failed'))
1023 if inst.code == 404:
1024 raise NotFound()
1025 else:
1026 raise
1027
1028 def filter_real_bug_ids(self, bugs):
1029 '''remove bug IDs that do not exist in Bugzilla from bugs.'''
1030 badbugs = set()
1031 for bugid in bugs:
1032 burl = self.apiurl((b'bug', bugid), include_fields=b'status')
1033 try:
1034 self._fetch(burl)
1035 except NotFound:
1036 badbugs.add(bugid)
1037 for bugid in badbugs:
1038 del bugs[bugid]
1039
1040 def filter_cset_known_bug_ids(self, node, bugs):
1041 '''remove bug IDs where node occurs in comment text from bugs.'''
1042 sn = short(node)
1043 for bugid in bugs.keys():
1044 burl = self.apiurl(
1045 (b'bug', bugid, b'comment'), include_fields=b'text'
1046 )
1047 result = self._fetch(burl)
1048 comments = result[b'bugs'][pycompat.bytestr(bugid)][b'comments']
1049 if any(sn in c[b'text'] for c in comments):
1050 self.ui.status(
1051 _(b'bug %d already knows about changeset %s\n')
1052 % (bugid, sn)
1053 )
1054 del bugs[bugid]
1055
1056 def updatebug(self, bugid, newstate, text, committer):
1057 """update the specified bug. Add comment text and set new states.
1058
1059 If possible add the comment as being from the committer of
1060 the changeset. Otherwise use the default Bugzilla user.
1061 """
1062 bugmod = {}
1063 if b'hours' in newstate:
1064 bugmod[b'work_time'] = newstate[b'hours']
1065 if b'fix' in newstate:
1066 bugmod[b'status'] = self.fixstatus
1067 bugmod[b'resolution'] = self.fixresolution
1068 if bugmod:
1069 # if we have to change the bugs state do it here
1070 bugmod[b'comment'] = {
1071 b'comment': text,
1072 b'is_private': False,
1073 b'is_markdown': False,
1074 }
1075 burl = self.apiurl((b'bug', bugid))
1076 self._submit(burl, bugmod, method=b'PUT')
1077 self.ui.debug(b'updated bug %s\n' % bugid)
1078 else:
1079 burl = self.apiurl((b'bug', bugid, b'comment'))
1080 self._submit(
1081 burl,
1082 {
1083 b'comment': text,
1084 b'is_private': False,
1085 b'is_markdown': False,
1086 },
1087 )
1088 self.ui.debug(b'added comment to bug %s\n' % bugid)
1089
1090 def notify(self, bugs, committer):
1091 """Force sending of Bugzilla notification emails.
1092
1093 Only required if the access method does not trigger notification
1094 emails automatically.
1095 """
1096 pass
1097
1098
1099 class bugzilla:
1100 # supported versions of bugzilla. different versions have
1101 # different schemas.
1102 _versions = {
1103 b'2.16': bzmysql,
1104 b'2.18': bzmysql_2_18,
1105 b'3.0': bzmysql_3_0,
1106 b'xmlrpc': bzxmlrpc,
1107 b'xmlrpc+email': bzxmlrpcemail,
1108 b'restapi': bzrestapi,
1109 }
1110
1111 def __init__(self, ui, repo):
1112 self.ui = ui
1113 self.repo = repo
1114
1115 bzversion = self.ui.config(b'bugzilla', b'version')
1116 try:
1117 bzclass = bugzilla._versions[bzversion]
1118 except KeyError:
1119 raise error.Abort(
1120 _(b'bugzilla version %s not supported') % bzversion
1121 )
1122 self.bzdriver = bzclass(self.ui)
1123
1124 self.bug_re = re.compile(
1125 self.ui.config(b'bugzilla', b'regexp'), re.IGNORECASE
1126 )
1127 self.fix_re = re.compile(
1128 self.ui.config(b'bugzilla', b'fixregexp'), re.IGNORECASE
1129 )
1130 self.split_re = re.compile(br'\D+')
1131
1132 def find_bugs(self, ctx):
1133 """return bugs dictionary created from commit comment.
1134
1135 Extract bug info from changeset comments. Filter out any that are
1136 not known to Bugzilla, and any that already have a reference to
1137 the given changeset in their comments.
1138 """
1139 start = 0
1140 bugs = {}
1141 bugmatch = self.bug_re.search(ctx.description(), start)
1142 fixmatch = self.fix_re.search(ctx.description(), start)
1143 while True:
1144 bugattribs = {}
1145 if not bugmatch and not fixmatch:
1146 break
1147 if not bugmatch:
1148 m = fixmatch
1149 elif not fixmatch:
1150 m = bugmatch
1151 else:
1152 if bugmatch.start() < fixmatch.start():
1153 m = bugmatch
1154 else:
1155 m = fixmatch
1156 start = m.end()
1157 if m is bugmatch:
1158 bugmatch = self.bug_re.search(ctx.description(), start)
1159 if b'fix' in bugattribs:
1160 del bugattribs[b'fix']
1161 else:
1162 fixmatch = self.fix_re.search(ctx.description(), start)
1163 bugattribs[b'fix'] = None
1164
1165 try:
1166 ids = m.group(b'ids')
1167 except IndexError:
1168 ids = m.group(1)
1169 try:
1170 hours = float(m.group(b'hours'))
1171 bugattribs[b'hours'] = hours
1172 except IndexError:
1173 pass
1174 except TypeError:
1175 pass
1176 except ValueError:
1177 self.ui.status(_(b"%s: invalid hours\n") % m.group(b'hours'))
1178
1179 for id in self.split_re.split(ids):
1180 if not id:
1181 continue
1182 bugs[int(id)] = bugattribs
1183 if bugs:
1184 self.bzdriver.filter_real_bug_ids(bugs)
1185 if bugs:
1186 self.bzdriver.filter_cset_known_bug_ids(ctx.node(), bugs)
1187 return bugs
1188
1189 def update(self, bugid, newstate, ctx):
1190 '''update bugzilla bug with reference to changeset.'''
1191
1192 def webroot(root):
1193 """strip leading prefix of repo root and turn into
1194 url-safe path."""
1195 count = self.ui.configint(b'bugzilla', b'strip')
1196 root = util.pconvert(root)
1197 while count > 0:
1198 c = root.find(b'/')
1199 if c == -1:
1200 break
1201 root = root[c + 1 :]
1202 count -= 1
1203 return root
1204
1205 mapfile = None
1206 tmpl = self.ui.config(b'bugzilla', b'template')
1207 if not tmpl:
1208 mapfile = self.ui.config(b'bugzilla', b'style')
1209 if not mapfile and not tmpl:
1210 tmpl = _(
1211 b'changeset {node|short} in repo {root} refers '
1212 b'to bug {bug}.\ndetails:\n\t{desc|tabindent}'
1213 )
1214 spec = logcmdutil.templatespec(tmpl, mapfile)
1215 t = logcmdutil.changesettemplater(self.ui, self.repo, spec)
1216 self.ui.pushbuffer()
1217 t.show(
1218 ctx,
1219 changes=ctx.changeset(),
1220 bug=pycompat.bytestr(bugid),
1221 hgweb=self.ui.config(b'web', b'baseurl'),
1222 root=self.repo.root,
1223 webroot=webroot(self.repo.root),
1224 )
1225 data = self.ui.popbuffer()
1226 self.bzdriver.updatebug(
1227 bugid, newstate, data, stringutil.email(ctx.user())
1228 )
1229
1230 def notify(self, bugs, committer):
1231 '''ensure Bugzilla users are notified of bug change.'''
1232 self.bzdriver.notify(bugs, committer)
1233
1234
1235 def hook(ui, repo, hooktype, node=None, **kwargs):
1236 """add comment to bugzilla for each changeset that refers to a
1237 bugzilla bug id. only add a comment once per bug, so same change
1238 seen multiple times does not fill bug with duplicate data."""
1239 if node is None:
1240 raise error.Abort(
1241 _(b'hook type %s does not pass a changeset id') % hooktype
1242 )
1243 try:
1244 bz = bugzilla(ui, repo)
1245 ctx = repo[node]
1246 bugs = bz.find_bugs(ctx)
1247 if bugs:
1248 for bug in bugs:
1249 bz.update(bug, bugs[bug], ctx)
1250 bz.notify(bugs, stringutil.email(ctx.user()))
1251 except Exception as e:
1252 raise error.Abort(_(b'Bugzilla error: %s') % stringutil.forcebytestr(e))