Debian Codegraph @

hgext/bugzilla.py

raw ◀ ▶
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 _(b' (try installing the %s package)') % b'python3-mysqldb'
509 )
510
511 bzaccess.__init__(self, ui)
512
513 host = self.ui.config(b'bugzilla', b'host')
514 user = self.ui.config(b'bugzilla', b'user')
515 passwd = self.ui.config(b'bugzilla', b'password')
516 db = self.ui.config(b'bugzilla', b'db')
517 timeout = self.ui.configint(b'bugzilla', b'timeout')
518 self.ui.note(
519 _(b'connecting to %s:%s as %s, password %s\n')
520 % (host, db, user, b'*' * len(passwd))
521 )
522 self.conn = bzmysql._MySQLdb.connect(
523 host=host, user=user, passwd=passwd, db=db, connect_timeout=timeout
524 )
525 self.cursor = self.conn.cursor()
526 self.longdesc_id = self.get_longdesc_id()
527 self.user_ids = {}
528 self.default_notify = b"cd %(bzdir)s && ./processmail %(id)s %(user)s"
529
530 def run(self, *args, **kwargs):
531 '''run a query.'''
532 self.ui.note(_(b'query: %s %s\n') % (args, kwargs))
533 try:
534 self.cursor.execute(*args, **kwargs)
535 except bzmysql._MySQLdb.MySQLError:
536 self.ui.note(_(b'failed query: %s %s\n') % (args, kwargs))
537 raise
538
539 def get_longdesc_id(self):
540 '''get identity of longdesc field'''
541 self.run(b'select fieldid from fielddefs where name = "longdesc"')
542 ids = self.cursor.fetchall()
543 if len(ids) != 1:
544 raise error.Abort(_(b'unknown database schema'))
545 return ids[0][0]
546
547 def filter_real_bug_ids(self, bugs):
548 '''filter not-existing bugs from set.'''
549 self.run(
550 b'select bug_id from bugs where bug_id in %s'
551 % bzmysql.sql_buglist(bugs.keys())
552 )
553 existing = [id for (id,) in self.cursor.fetchall()]
554 for id in bugs.keys():
555 if id not in existing:
556 self.ui.status(_(b'bug %d does not exist\n') % id)
557 del bugs[id]
558
559 def filter_cset_known_bug_ids(self, node, bugs):
560 '''filter bug ids that already refer to this changeset from set.'''
561 self.run(
562 '''select bug_id from longdescs where
563 bug_id in %s and thetext like "%%%s%%"'''
564 % (bzmysql.sql_buglist(bugs.keys()), short(node))
565 )
566 for (id,) in self.cursor.fetchall():
567 self.ui.status(
568 _(b'bug %d already knows about changeset %s\n')
569 % (id, short(node))
570 )
571 del bugs[id]
572
573 def notify(self, bugs, committer):
574 '''tell bugzilla to send mail.'''
575 self.ui.status(_(b'telling bugzilla to send mail:\n'))
576 (user, userid) = self.get_bugzilla_user(committer)
577 for id in bugs.keys():
578 self.ui.status(_(b' bug %s\n') % id)
579 cmdfmt = self.ui.config(b'bugzilla', b'notify', self.default_notify)
580 bzdir = self.ui.config(b'bugzilla', b'bzdir')
581 try:
582 # Backwards-compatible with old notify string, which
583 # took one string. This will throw with a new format
584 # string.
585 cmd = cmdfmt % id
586 except TypeError:
587 cmd = cmdfmt % {b'bzdir': bzdir, b'id': id, b'user': user}
588 self.ui.note(_(b'running notify command %s\n') % cmd)
589 fp = procutil.popen(b'(%s) 2>&1' % cmd, b'rb')
590 out = util.fromnativeeol(fp.read())
591 ret = fp.close()
592 if ret:
593 self.ui.warn(out)
594 raise error.Abort(
595 _(b'bugzilla notify command %s') % procutil.explainexit(ret)
596 )
597 self.ui.status(_(b'done\n'))
598
599 def get_user_id(self, user):
600 '''look up numeric bugzilla user id.'''
601 try:
602 return self.user_ids[user]
603 except KeyError:
604 try:
605 userid = int(user)
606 except ValueError:
607 self.ui.note(_(b'looking up user %s\n') % user)
608 self.run(
609 '''select userid from profiles
610 where login_name like %s''',
611 user,
612 )
613 all = self.cursor.fetchall()
614 if len(all) != 1:
615 raise KeyError(user)
616 userid = int(all[0][0])
617 self.user_ids[user] = userid
618 return userid
619
620 def get_bugzilla_user(self, committer):
621 """See if committer is a registered bugzilla user. Return
622 bugzilla username and userid if so. If not, return default
623 bugzilla username and userid."""
624 user = self.map_committer(committer)
625 try:
626 userid = self.get_user_id(user)
627 except KeyError:
628 try:
629 defaultuser = self.ui.config(b'bugzilla', b'bzuser')
630 if not defaultuser:
631 raise error.Abort(
632 _(b'cannot find bugzilla user id for %s') % user
633 )
634 userid = self.get_user_id(defaultuser)
635 user = defaultuser
636 except KeyError:
637 raise error.Abort(
638 _(b'cannot find bugzilla user id for %s or %s')
639 % (user, defaultuser)
640 )
641 return (user, userid)
642
643 def updatebug(self, bugid, newstate, text, committer):
644 """update bug state with comment text.
645
646 Try adding comment as committer of changeset, otherwise as
647 default bugzilla user."""
648 if len(newstate) > 0:
649 self.ui.warn(_(b"Bugzilla/MySQL cannot update bug state\n"))
650
651 (user, userid) = self.get_bugzilla_user(committer)
652 now = time.strftime('%Y-%m-%d %H:%M:%S')
653 self.run(
654 '''insert into longdescs
655 (bug_id, who, bug_when, thetext)
656 values (%s, %s, %s, %s)''',
657 (bugid, userid, now, text),
658 )
659 self.run(
660 '''insert into bugs_activity (bug_id, who, bug_when, fieldid)
661 values (%s, %s, %s, %s)''',
662 (bugid, userid, now, self.longdesc_id),
663 )
664 self.conn.commit()
665
666
667 class bzmysql_2_18(bzmysql):
668 '''support for bugzilla 2.18 series.'''
669
670 def __init__(self, ui):
671 bzmysql.__init__(self, ui)
672 self.default_notify = (
673 b"cd %(bzdir)s && perl -T contrib/sendbugmail.pl %(id)s %(user)s"
674 )
675
676
677 class bzmysql_3_0(bzmysql_2_18):
678 '''support for bugzilla 3.0 series.'''
679
680 def __init__(self, ui):
681 bzmysql_2_18.__init__(self, ui)
682
683 def get_longdesc_id(self):
684 '''get identity of longdesc field'''
685 self.run(b'select id from fielddefs where name = "longdesc"')
686 ids = self.cursor.fetchall()
687 if len(ids) != 1:
688 raise error.Abort(_(b'unknown database schema'))
689 return ids[0][0]
690
691
692 # Bugzilla via XMLRPC interface.
693
694
695 class cookietransportrequest:
696 """A Transport request method that retains cookies over its lifetime.
697
698 The regular xmlrpclib transports ignore cookies. Which causes
699 a bit of a problem when you need a cookie-based login, as with
700 the Bugzilla XMLRPC interface prior to 4.4.3.
701
702 So this is a helper for defining a Transport which looks for
703 cookies being set in responses and saves them to add to all future
704 requests.
705 """
706
707 # Inspiration drawn from
708 # http://blog.godson.in/2010/09/how-to-make-python-xmlrpclib-client.html
709 # http://www.itkovian.net/base/transport-class-for-pythons-xml-rpc-lib/
710
711 cookies = []
712
713 def send_cookies(self, connection):
714 if self.cookies:
715 for cookie in self.cookies:
716 connection.putheader(b"Cookie", cookie)
717
718 def request(self, host, handler, request_body, verbose=0):
719 self.verbose = verbose
720 self.accept_gzip_encoding = False
721
722 # issue XML-RPC request
723 h = self.make_connection(host)
724 if verbose:
725 h.set_debuglevel(1)
726
727 self.send_request(h, handler, request_body)
728 self.send_host(h, host)
729 self.send_cookies(h)
730 self.send_user_agent(h)
731 self.send_content(h, request_body)
732
733 # Deal with differences between Python 2.6 and 2.7.
734 # In the former h is a HTTP(S). In the latter it's a
735 # HTTP(S)Connection. Luckily, the 2.6 implementation of
736 # HTTP(S) has an underlying HTTP(S)Connection, so extract
737 # that and use it.
738 try:
739 response = h.getresponse()
740 except AttributeError:
741 response = h._conn.getresponse()
742
743 # Add any cookie definitions to our list.
744 for header in response.msg.getallmatchingheaders(b"Set-Cookie"):
745 val = header.split(b": ", 1)[1]
746 cookie = val.split(b";", 1)[0]
747 self.cookies.append(cookie)
748
749 if response.status != 200:
750 raise xmlrpclib.ProtocolError(
751 host + handler,
752 response.status,
753 response.reason,
754 response.msg.headers,
755 )
756
757 payload = response.read()
758 parser, unmarshaller = self.getparser()
759 parser.feed(payload)
760 parser.close()
761
762 return unmarshaller.close()
763
764
765 # The explicit calls to the underlying xmlrpclib __init__() methods are
766 # necessary. The xmlrpclib.Transport classes are old-style classes, and
767 # it turns out their __init__() doesn't get called when doing multiple
768 # inheritance with a new-style class.
769 class cookietransport(cookietransportrequest, xmlrpclib.Transport):
770 def __init__(self, use_datetime=0):
771 if hasattr(xmlrpclib.Transport, "__init__"):
772 xmlrpclib.Transport.__init__(self, use_datetime)
773
774
775 class cookiesafetransport(cookietransportrequest, xmlrpclib.SafeTransport):
776 def __init__(self, use_datetime=0):
777 if hasattr(xmlrpclib.Transport, "__init__"):
778 xmlrpclib.SafeTransport.__init__(self, use_datetime)
779
780
781 class bzxmlrpc(bzaccess):
782 """Support for access to Bugzilla via the Bugzilla XMLRPC API.
783
784 Requires a minimum Bugzilla version 3.4.
785 """
786
787 def __init__(self, ui):
788 bzaccess.__init__(self, ui)
789
790 bzweb = self.ui.config(b'bugzilla', b'bzurl')
791 bzweb = bzweb.rstrip(b"/") + b"/xmlrpc.cgi"
792
793 user = self.ui.config(b'bugzilla', b'user')
794 passwd = self.ui.config(b'bugzilla', b'password')
795
796 self.fixstatus = self.ui.config(b'bugzilla', b'fixstatus')
797 self.fixresolution = self.ui.config(b'bugzilla', b'fixresolution')
798
799 self.bzproxy = xmlrpclib.ServerProxy(
800 pycompat.strurl(bzweb), self.transport(bzweb)
801 )
802 ver = self.bzproxy.Bugzilla.version()[b'version'].split(b'.')
803 self.bzvermajor = int(ver[0])
804 self.bzverminor = int(ver[1])
805 login = self.bzproxy.User.login(
806 {b'login': user, b'password': passwd, b'restrict_login': True}
807 )
808 self.bztoken = login.get(b'token', b'')
809
810 def transport(self, uri):
811 if util.urlreq.urlparse(uri, b"http")[0] == b"https":
812 return cookiesafetransport()
813 else:
814 return cookietransport()
815
816 def get_bug_comments(self, id):
817 """Return a string with all comment text for a bug."""
818 c = self.bzproxy.Bug.comments(
819 {b'ids': [id], b'include_fields': [b'text'], b'token': self.bztoken}
820 )
821 return b''.join(
822 [t[b'text'] for t in c[b'bugs'][b'%d' % id][b'comments']]
823 )
824
825 def filter_real_bug_ids(self, bugs):
826 probe = self.bzproxy.Bug.get(
827 {
828 b'ids': sorted(bugs.keys()),
829 b'include_fields': [],
830 b'permissive': True,
831 b'token': self.bztoken,
832 }
833 )
834 for badbug in probe[b'faults']:
835 id = badbug[b'id']
836 self.ui.status(_(b'bug %d does not exist\n') % id)
837 del bugs[id]
838
839 def filter_cset_known_bug_ids(self, node, bugs):
840 for id in sorted(bugs.keys()):
841 if self.get_bug_comments(id).find(short(node)) != -1:
842 self.ui.status(
843 _(b'bug %d already knows about changeset %s\n')
844 % (id, short(node))
845 )
846 del bugs[id]
847
848 def updatebug(self, bugid, newstate, text, committer):
849 args = {}
850 if b'hours' in newstate:
851 args[b'work_time'] = newstate[b'hours']
852
853 if self.bzvermajor >= 4:
854 args[b'ids'] = [bugid]
855 args[b'comment'] = {b'body': text}
856 if b'fix' in newstate:
857 args[b'status'] = self.fixstatus
858 args[b'resolution'] = self.fixresolution
859 args[b'token'] = self.bztoken
860 self.bzproxy.Bug.update(args)
861 else:
862 if b'fix' in newstate:
863 self.ui.warn(
864 _(
865 b"Bugzilla/XMLRPC needs Bugzilla 4.0 or later "
866 b"to mark bugs fixed\n"
867 )
868 )
869 args[b'id'] = bugid
870 args[b'comment'] = text
871 self.bzproxy.Bug.add_comment(args)
872
873
874 class bzxmlrpcemail(bzxmlrpc):
875 """Read data from Bugzilla via XMLRPC, send updates via email.
876
877 Advantages of sending updates via email:
878 1. Comments can be added as any user, not just logged in user.
879 2. Bug statuses or other fields not accessible via XMLRPC can
880 potentially be updated.
881
882 There is no XMLRPC function to change bug status before Bugzilla
883 4.0, so bugs cannot be marked fixed via XMLRPC before Bugzilla 4.0.
884 But bugs can be marked fixed via email from 3.4 onwards.
885 """
886
887 # The email interface changes subtly between 3.4 and 3.6. In 3.4,
888 # in-email fields are specified as '@<fieldname> = <value>'. In
889 # 3.6 this becomes '@<fieldname> <value>'. And fieldname @bug_id
890 # in 3.4 becomes @id in 3.6. 3.6 and 4.0 both maintain backwards
891 # compatibility, but rather than rely on this use the new format for
892 # 4.0 onwards.
893
894 def __init__(self, ui):
895 bzxmlrpc.__init__(self, ui)
896
897 self.bzemail = self.ui.config(b'bugzilla', b'bzemail')
898 if not self.bzemail:
899 raise error.Abort(_(b"configuration 'bzemail' missing"))
900 mail.validateconfig(self.ui)
901
902 def makecommandline(self, fieldname, value):
903 if self.bzvermajor >= 4:
904 return b"@%s %s" % (fieldname, pycompat.bytestr(value))
905 else:
906 if fieldname == b"id":
907 fieldname = b"bug_id"
908 return b"@%s = %s" % (fieldname, pycompat.bytestr(value))
909
910 def send_bug_modify_email(self, bugid, commands, comment, committer):
911 """send modification message to Bugzilla bug via email.
912
913 The message format is documented in the Bugzilla email_in.pl
914 specification. commands is a list of command lines, comment is the
915 comment text.
916
917 To stop users from crafting commit comments with
918 Bugzilla commands, specify the bug ID via the message body, rather
919 than the subject line, and leave a blank line after it.
920 """
921 user = self.map_committer(committer)
922 matches = self.bzproxy.User.get(
923 {b'match': [user], b'token': self.bztoken}
924 )
925 if not matches[b'users']:
926 user = self.ui.config(b'bugzilla', b'user')
927 matches = self.bzproxy.User.get(
928 {b'match': [user], b'token': self.bztoken}
929 )
930 if not matches[b'users']:
931 raise error.Abort(
932 _(b"default bugzilla user %s email not found") % user
933 )
934 user = matches[b'users'][0][b'email']
935 commands.append(self.makecommandline(b"id", bugid))
936
937 text = b"\n".join(commands) + b"\n\n" + comment
938
939 _charsets = mail._charsets(self.ui)
940 user = mail.addressencode(self.ui, user, _charsets)
941 bzemail = mail.addressencode(self.ui, self.bzemail, _charsets)
942 msg = mail.mimeencode(self.ui, text, _charsets)
943 msg[b'From'] = user
944 msg[b'To'] = bzemail
945 msg[b'Subject'] = mail.headencode(
946 self.ui, b"Bug modification", _charsets
947 )
948 sendmail = mail.connect(self.ui)
949 sendmail(user, bzemail, msg.as_string())
950
951 def updatebug(self, bugid, newstate, text, committer):
952 cmds = []
953 if b'hours' in newstate:
954 cmds.append(self.makecommandline(b"work_time", newstate[b'hours']))
955 if b'fix' in newstate:
956 cmds.append(self.makecommandline(b"bug_status", self.fixstatus))
957 cmds.append(self.makecommandline(b"resolution", self.fixresolution))
958 self.send_bug_modify_email(bugid, cmds, text, committer)
959
960
961 class NotFound(LookupError):
962 pass
963
964
965 class bzrestapi(bzaccess):
966 """Read and write bugzilla data using the REST API available since
967 Bugzilla 5.0.
968 """
969
970 def __init__(self, ui):
971 bzaccess.__init__(self, ui)
972 bz = self.ui.config(b'bugzilla', b'bzurl')
973 self.bzroot = b'/'.join([bz, b'rest'])
974 self.apikey = self.ui.config(b'bugzilla', b'apikey')
975 self.user = self.ui.config(b'bugzilla', b'user')
976 self.passwd = self.ui.config(b'bugzilla', b'password')
977 self.fixstatus = self.ui.config(b'bugzilla', b'fixstatus')
978 self.fixresolution = self.ui.config(b'bugzilla', b'fixresolution')
979
980 def apiurl(self, targets, include_fields=None):
981 url = b'/'.join([self.bzroot] + [pycompat.bytestr(t) for t in targets])
982 qv = {}
983 if self.apikey:
984 qv[b'api_key'] = self.apikey
985 elif self.user and self.passwd:
986 qv[b'login'] = self.user
987 qv[b'password'] = self.passwd
988 if include_fields:
989 qv[b'include_fields'] = include_fields
990 if qv:
991 url = b'%s?%s' % (url, util.urlreq.urlencode(qv))
992 return url
993
994 def _fetch(self, burl):
995 try:
996 resp = url.open(self.ui, burl)
997 return pycompat.json_loads(resp.read())
998 except util.urlerr.httperror as inst:
999 if inst.code == 401:
1000 raise error.Abort(_(b'authorization failed'))
1001 if inst.code == 404:
1002 raise NotFound()
1003 else:
1004 raise
1005
1006 def _submit(self, burl, data, method=b'POST'):
1007 data = json.dumps(data)
1008 if method == b'PUT':
1009
1010 class putrequest(util.urlreq.request):
1011 def get_method(self):
1012 return b'PUT'
1013
1014 request_type = putrequest
1015 else:
1016 request_type = util.urlreq.request
1017 req = request_type(burl, data, {b'Content-Type': b'application/json'})
1018 try:
1019 resp = url.opener(self.ui).open(req)
1020 return pycompat.json_loads(resp.read())
1021 except util.urlerr.httperror as inst:
1022 if inst.code == 401:
1023 raise error.Abort(_(b'authorization failed'))
1024 if inst.code == 404:
1025 raise NotFound()
1026 else:
1027 raise
1028
1029 def filter_real_bug_ids(self, bugs):
1030 '''remove bug IDs that do not exist in Bugzilla from bugs.'''
1031 badbugs = set()
1032 for bugid in bugs:
1033 burl = self.apiurl((b'bug', bugid), include_fields=b'status')
1034 try:
1035 self._fetch(burl)
1036 except NotFound:
1037 badbugs.add(bugid)
1038 for bugid in badbugs:
1039 del bugs[bugid]
1040
1041 def filter_cset_known_bug_ids(self, node, bugs):
1042 '''remove bug IDs where node occurs in comment text from bugs.'''
1043 sn = short(node)
1044 for bugid in bugs.keys():
1045 burl = self.apiurl(
1046 (b'bug', bugid, b'comment'), include_fields=b'text'
1047 )
1048 result = self._fetch(burl)
1049 comments = result[b'bugs'][pycompat.bytestr(bugid)][b'comments']
1050 if any(sn in c[b'text'] for c in comments):
1051 self.ui.status(
1052 _(b'bug %d already knows about changeset %s\n')
1053 % (bugid, sn)
1054 )
1055 del bugs[bugid]
1056
1057 def updatebug(self, bugid, newstate, text, committer):
1058 """update the specified bug. Add comment text and set new states.
1059
1060 If possible add the comment as being from the committer of
1061 the changeset. Otherwise use the default Bugzilla user.
1062 """
1063 bugmod = {}
1064 if b'hours' in newstate:
1065 bugmod[b'work_time'] = newstate[b'hours']
1066 if b'fix' in newstate:
1067 bugmod[b'status'] = self.fixstatus
1068 bugmod[b'resolution'] = self.fixresolution
1069 if bugmod:
1070 # if we have to change the bugs state do it here
1071 bugmod[b'comment'] = {
1072 b'comment': text,
1073 b'is_private': False,
1074 b'is_markdown': False,
1075 }
1076 burl = self.apiurl((b'bug', bugid))
1077 self._submit(burl, bugmod, method=b'PUT')
1078 self.ui.debug(b'updated bug %s\n' % bugid)
1079 else:
1080 burl = self.apiurl((b'bug', bugid, b'comment'))
1081 self._submit(
1082 burl,
1083 {
1084 b'comment': text,
1085 b'is_private': False,
1086 b'is_markdown': False,
1087 },
1088 )
1089 self.ui.debug(b'added comment to bug %s\n' % bugid)
1090
1091 def notify(self, bugs, committer):
1092 """Force sending of Bugzilla notification emails.
1093
1094 Only required if the access method does not trigger notification
1095 emails automatically.
1096 """
1097 pass
1098
1099
1100 class bugzilla:
1101 # supported versions of bugzilla. different versions have
1102 # different schemas.
1103 _versions = {
1104 b'2.16': bzmysql,
1105 b'2.18': bzmysql_2_18,
1106 b'3.0': bzmysql_3_0,
1107 b'xmlrpc': bzxmlrpc,
1108 b'xmlrpc+email': bzxmlrpcemail,
1109 b'restapi': bzrestapi,
1110 }
1111
1112 def __init__(self, ui, repo):
1113 self.ui = ui
1114 self.repo = repo
1115
1116 bzversion = self.ui.config(b'bugzilla', b'version')
1117 try:
1118 bzclass = bugzilla._versions[bzversion]
1119 except KeyError:
1120 raise error.Abort(
1121 _(b'bugzilla version %s not supported') % bzversion
1122 )
1123 self.bzdriver = bzclass(self.ui)
1124
1125 self.bug_re = re.compile(
1126 self.ui.config(b'bugzilla', b'regexp'), re.IGNORECASE
1127 )
1128 self.fix_re = re.compile(
1129 self.ui.config(b'bugzilla', b'fixregexp'), re.IGNORECASE
1130 )
1131 self.split_re = re.compile(br'\D+')
1132
1133 def find_bugs(self, ctx):
1134 """return bugs dictionary created from commit comment.
1135
1136 Extract bug info from changeset comments. Filter out any that are
1137 not known to Bugzilla, and any that already have a reference to
1138 the given changeset in their comments.
1139 """
1140 start = 0
1141 bugs = {}
1142 bugmatch = self.bug_re.search(ctx.description(), start)
1143 fixmatch = self.fix_re.search(ctx.description(), start)
1144 while True:
1145 bugattribs = {}
1146 if not bugmatch and not fixmatch:
1147 break
1148 if not bugmatch:
1149 m = fixmatch
1150 elif not fixmatch:
1151 m = bugmatch
1152 else:
1153 if bugmatch.start() < fixmatch.start():
1154 m = bugmatch
1155 else:
1156 m = fixmatch
1157 start = m.end()
1158 if m is bugmatch:
1159 bugmatch = self.bug_re.search(ctx.description(), start)
1160 if b'fix' in bugattribs:
1161 del bugattribs[b'fix']
1162 else:
1163 fixmatch = self.fix_re.search(ctx.description(), start)
1164 bugattribs[b'fix'] = None
1165
1166 try:
1167 ids = m.group(b'ids')
1168 except IndexError:
1169 ids = m.group(1)
1170 try:
1171 hours = float(m.group(b'hours'))
1172 bugattribs[b'hours'] = hours
1173 except IndexError:
1174 pass
1175 except TypeError:
1176 pass
1177 except ValueError:
1178 self.ui.status(_(b"%s: invalid hours\n") % m.group(b'hours'))
1179
1180 for id in self.split_re.split(ids):
1181 if not id:
1182 continue
1183 bugs[int(id)] = bugattribs
1184 if bugs:
1185 self.bzdriver.filter_real_bug_ids(bugs)
1186 if bugs:
1187 self.bzdriver.filter_cset_known_bug_ids(ctx.node(), bugs)
1188 return bugs
1189
1190 def update(self, bugid, newstate, ctx):
1191 '''update bugzilla bug with reference to changeset.'''
1192
1193 def webroot(root):
1194 """strip leading prefix of repo root and turn into
1195 url-safe path."""
1196 count = self.ui.configint(b'bugzilla', b'strip')
1197 root = util.pconvert(root)
1198 while count > 0:
1199 c = root.find(b'/')
1200 if c == -1:
1201 break
1202 root = root[c + 1 :]
1203 count -= 1
1204 return root
1205
1206 mapfile = None
1207 tmpl = self.ui.config(b'bugzilla', b'template')
1208 if not tmpl:
1209 mapfile = self.ui.config(b'bugzilla', b'style')
1210 if not mapfile and not tmpl:
1211 tmpl = _(
1212 b'changeset {node|short} in repo {root} refers '
1213 b'to bug {bug}.\ndetails:\n\t{desc|tabindent}'
1214 )
1215 spec = logcmdutil.templatespec(tmpl, mapfile)
1216 t = logcmdutil.changesettemplater(self.ui, self.repo, spec)
1217 self.ui.pushbuffer()
1218 t.show(
1219 ctx,
1220 changes=ctx.changeset(),
1221 bug=pycompat.bytestr(bugid),
1222 hgweb=self.ui.config(b'web', b'baseurl'),
1223 root=self.repo.root,
1224 webroot=webroot(self.repo.root),
1225 )
1226 data = self.ui.popbuffer()
1227 self.bzdriver.updatebug(
1228 bugid, newstate, data, stringutil.email(ctx.user())
1229 )
1230
1231 def notify(self, bugs, committer):
1232 '''ensure Bugzilla users are notified of bug change.'''
1233 self.bzdriver.notify(bugs, committer)
1234
1235
1236 def hook(ui, repo, hooktype, node=None, **kwargs):
1237 """add comment to bugzilla for each changeset that refers to a
1238 bugzilla bug id. only add a comment once per bug, so same change
1239 seen multiple times does not fill bug with duplicate data."""
1240 if node is None:
1241 raise error.Abort(
1242 _(b'hook type %s does not pass a changeset id') % hooktype
1243 )
1244 try:
1245 bz = bugzilla(ui, repo)
1246 ctx = repo[node]
1247 bugs = bz.find_bugs(ctx)
1248 if bugs:
1249 for bug in bugs:
1250 bz.update(bug, bugs[bug], ctx)
1251 bz.notify(bugs, stringutil.email(ctx.user()))
1252 except Exception as e:
1253 raise error.Abort(_(b'Bugzilla error: %s') % stringutil.forcebytestr(e))