Debian Codegraph @

hgext/notify.py

raw
1 # notify.py - email notifications for mercurial
2 #
3 # Copyright 2006 Vadim Gelfer <[email protected]>
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 '''hooks for sending email push notifications
9
10 This extension implements hooks to send email notifications when
11 changesets are sent from or received by the local repository.
12
13 First, enable the extension as explained in :hg:`help extensions`, and
14 register the hook you want to run. ``incoming`` and ``changegroup`` hooks
15 are run when changesets are received, while ``outgoing`` hooks are for
16 changesets sent to another repository::
17
18 [hooks]
19 # one email for each incoming changeset
20 incoming.notify = python:hgext.notify.hook
21 # one email for all incoming changesets
22 changegroup.notify = python:hgext.notify.hook
23
24 # one email for all outgoing changesets
25 outgoing.notify = python:hgext.notify.hook
26
27 This registers the hooks. To enable notification, subscribers must
28 be assigned to repositories. The ``[usersubs]`` section maps multiple
29 repositories to a given recipient. The ``[reposubs]`` section maps
30 multiple recipients to a single repository::
31
32 [usersubs]
33 # key is subscriber email, value is a comma-separated list of repo patterns
34 user@host = pattern
35
36 [reposubs]
37 # key is repo pattern, value is a comma-separated list of subscriber emails
38 pattern = user@host
39
40 A ``pattern`` is a ``glob`` matching the absolute path to a repository,
41 optionally combined with a revset expression. A revset expression, if
42 present, is separated from the glob by a hash. Example::
43
44 [reposubs]
45 */widgets#branch(release) = [email protected]
46
47 This sends to ``[email protected]`` whenever a changeset on the ``release``
48 branch triggers a notification in any repository ending in ``widgets``.
49
50 In order to place them under direct user management, ``[usersubs]`` and
51 ``[reposubs]`` sections may be placed in a separate ``hgrc`` file and
52 incorporated by reference::
53
54 [notify]
55 config = /path/to/subscriptionsfile
56
57 Notifications will not be sent until the ``notify.test`` value is set
58 to ``False``; see below.
59
60 Notifications content can be tweaked with the following configuration entries:
61
62 notify.test
63 If ``True``, print messages to stdout instead of sending them. Default: True.
64
65 notify.sources
66 Space-separated list of change sources. Notifications are activated only
67 when a changeset's source is in this list. Sources may be:
68
69 :``serve``: changesets received via http or ssh
70 :``pull``: changesets received via ``hg pull``
71 :``unbundle``: changesets received via ``hg unbundle``
72 :``push``: changesets sent or received via ``hg push``
73 :``bundle``: changesets sent via ``hg unbundle``
74
75 Default: serve.
76
77 notify.strip
78 Number of leading slashes to strip from url paths. By default, notifications
79 reference repositories with their absolute path. ``notify.strip`` lets you
80 turn them into relative paths. For example, ``notify.strip=3`` will change
81 ``/long/path/repository`` into ``repository``. Default: 0.
82
83 notify.domain
84 Default email domain for sender or recipients with no explicit domain.
85 It is also used for the domain part of the ``Message-Id`` when using
86 ``notify.messageidseed``.
87
88 notify.messageidseed
89 Create deterministic ``Message-Id`` headers for the mails based on the seed
90 and the revision identifier of the first commit in the changeset.
91
92 notify.style
93 Style file to use when formatting emails.
94
95 notify.template
96 Template to use when formatting emails.
97
98 notify.incoming
99 Template to use when run as an incoming hook, overriding ``notify.template``.
100
101 notify.outgoing
102 Template to use when run as an outgoing hook, overriding ``notify.template``.
103
104 notify.changegroup
105 Template to use when running as a changegroup hook, overriding
106 ``notify.template``.
107
108 notify.maxdiff
109 Maximum number of diff lines to include in notification email. Set to 0
110 to disable the diff, or -1 to include all of it. Default: 300.
111
112 notify.maxdiffstat
113 Maximum number of diffstat lines to include in notification email. Set to -1
114 to include all of it. Default: -1.
115
116 notify.maxsubject
117 Maximum number of characters in email's subject line. Default: 67.
118
119 notify.diffstat
120 Set to True to include a diffstat before diff content. Default: True.
121
122 notify.showfunc
123 If set, override ``diff.showfunc`` for the diff content. Default: None.
124
125 notify.merge
126 If True, send notifications for merge changesets. Default: True.
127
128 notify.mbox
129 If set, append mails to this mbox file instead of sending. Default: None.
130
131 notify.fromauthor
132 If set, use the committer of the first changeset in a changegroup for
133 the "From" field of the notification mail. If not set, take the user
134 from the pushing repo. Default: False.
135
136 notify.reply-to-predecessor (EXPERIMENTAL)
137 If set and the changeset has a predecessor in the repository, try to thread
138 the notification mail with the predecessor. This adds the "In-Reply-To" header
139 to the notification mail with a reference to the predecessor with the smallest
140 revision number. Mail threads can still be torn, especially when changesets
141 are folded.
142
143 This option must be used in combination with ``notify.messageidseed``.
144
145 If set, the following entries will also be used to customize the
146 notifications:
147
148 email.from
149 Email ``From`` address to use if none can be found in the generated
150 email content.
151
152 web.baseurl
153 Root repository URL to combine with repository paths when making
154 references. See also ``notify.strip``.
155
156 '''
157
158 from __future__ import annotations
159
160 import email.errors as emailerrors
161 import email.utils as emailutils
162 import fnmatch
163 import hashlib
164 import socket
165 import time
166
167 from mercurial.i18n import _
168 from mercurial import (
169 encoding,
170 error,
171 logcmdutil,
172 mail,
173 obsutil,
174 patch,
175 pycompat,
176 registrar,
177 util,
178 )
179 from mercurial.utils import (
180 dateutil,
181 stringutil,
182 )
183
184 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
185 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
186 # be specifying the version(s) of Mercurial they are tested with, or
187 # leave the attribute unspecified.
188 testedwith = b'ships-with-hg-core'
189
190 configtable = {}
191 configitem = registrar.configitem(configtable)
192
193 configitem(
194 b'notify',
195 b'changegroup',
196 default=None,
197 )
198 configitem(
199 b'notify',
200 b'config',
201 default=None,
202 )
203 configitem(
204 b'notify',
205 b'diffstat',
206 default=True,
207 )
208 configitem(
209 b'notify',
210 b'domain',
211 default=None,
212 )
213 configitem(
214 b'notify',
215 b'messageidseed',
216 default=None,
217 )
218 configitem(
219 b'notify',
220 b'fromauthor',
221 default=None,
222 )
223 configitem(
224 b'notify',
225 b'incoming',
226 default=None,
227 )
228 configitem(
229 b'notify',
230 b'maxdiff',
231 default=300,
232 )
233 configitem(
234 b'notify',
235 b'maxdiffstat',
236 default=-1,
237 )
238 configitem(
239 b'notify',
240 b'maxsubject',
241 default=67,
242 )
243 configitem(
244 b'notify',
245 b'mbox',
246 default=None,
247 )
248 configitem(
249 b'notify',
250 b'merge',
251 default=True,
252 )
253 configitem(
254 b'notify',
255 b'outgoing',
256 default=None,
257 )
258 configitem(
259 b'notify',
260 b'reply-to-predecessor',
261 default=False,
262 )
263 configitem(
264 b'notify',
265 b'sources',
266 default=b'serve',
267 )
268 configitem(
269 b'notify',
270 b'showfunc',
271 default=None,
272 )
273 configitem(
274 b'notify',
275 b'strip',
276 default=0,
277 )
278 configitem(
279 b'notify',
280 b'style',
281 default=None,
282 )
283 configitem(
284 b'notify',
285 b'template',
286 default=None,
287 )
288 configitem(
289 b'notify',
290 b'test',
291 default=True,
292 )
293
294 # template for single changeset can include email headers.
295 single_template = b'''
296 Subject: changeset in {webroot}: {desc|firstline|strip}
297 From: {author}
298
299 changeset {node|short} in {root}
300 details: {baseurl}{webroot}?cmd=changeset;node={node|short}
301 description:
302 \t{desc|tabindent|strip}
303 '''.lstrip()
304
305 # template for multiple changesets should not contain email headers,
306 # because only first set of headers will be used and result will look
307 # strange.
308 multiple_template = b'''
309 changeset {node|short} in {root}
310 details: {baseurl}{webroot}?cmd=changeset;node={node|short}
311 summary: {desc|firstline}
312 '''
313
314 deftemplates = {
315 b'changegroup': multiple_template,
316 }
317
318
319 class notifier:
320 '''email notification class.'''
321
322 def __init__(self, ui, repo, hooktype):
323 self.ui = ui
324 cfg = self.ui.config(b'notify', b'config')
325 if cfg:
326 self.ui.readconfig(cfg, sections=[b'usersubs', b'reposubs'])
327 self.repo = repo
328 self.stripcount = self.ui.configint(b'notify', b'strip')
329 self.root = self.strip(self.repo.root)
330 self.domain = self.ui.config(b'notify', b'domain')
331 self.mbox = self.ui.config(b'notify', b'mbox')
332 self.test = self.ui.configbool(b'notify', b'test')
333 self.charsets = mail._charsets(self.ui)
334 self.subs = self.subscribers()
335 self.merge = self.ui.configbool(b'notify', b'merge')
336 self.showfunc = self.ui.configbool(b'notify', b'showfunc')
337 self.messageidseed = self.ui.config(b'notify', b'messageidseed')
338 self.reply = self.ui.configbool(b'notify', b'reply-to-predecessor')
339
340 if self.reply and not self.messageidseed:
341 raise error.Abort(
342 _(
343 b'notify.reply-to-predecessor used without '
344 b'notify.messageidseed'
345 )
346 )
347
348 if self.showfunc is None:
349 self.showfunc = self.ui.configbool(b'diff', b'showfunc')
350
351 mapfile = None
352 template = self.ui.config(b'notify', hooktype) or self.ui.config(
353 b'notify', b'template'
354 )
355 if not template:
356 mapfile = self.ui.config(b'notify', b'style')
357 if not mapfile and not template:
358 template = deftemplates.get(hooktype) or single_template
359 spec = logcmdutil.templatespec(template, mapfile)
360 self.t = logcmdutil.changesettemplater(self.ui, self.repo, spec)
361
362 def strip(self, path):
363 '''strip leading slashes from local path, turn into web-safe path.'''
364
365 path = util.pconvert(path)
366 count = self.stripcount
367 while count > 0:
368 c = path.find(b'/')
369 if c == -1:
370 break
371 path = path[c + 1 :]
372 count -= 1
373 return path
374
375 def fixmail(self, addr):
376 '''try to clean up email addresses.'''
377
378 addr = stringutil.email(addr.strip())
379 if self.domain:
380 a = addr.find(b'@localhost')
381 if a != -1:
382 addr = addr[:a]
383 if b'@' not in addr:
384 return addr + b'@' + self.domain
385 return addr
386
387 def subscribers(self):
388 '''return list of email addresses of subscribers to this repo.'''
389 subs = set()
390 for user, pats in self.ui.configitems(b'usersubs'):
391 for pat in pats.split(b','):
392 if b'#' in pat:
393 pat, revs = pat.split(b'#', 1)
394 else:
395 revs = None
396 if fnmatch.fnmatch(self.repo.root, pat.strip()):
397 subs.add((self.fixmail(user), revs))
398 for pat, users in self.ui.configitems(b'reposubs'):
399 if b'#' in pat:
400 pat, revs = pat.split(b'#', 1)
401 else:
402 revs = None
403 if fnmatch.fnmatch(self.repo.root, pat):
404 for user in users.split(b','):
405 subs.add((self.fixmail(user), revs))
406 return [
407 (mail.addressencode(self.ui, s, self.charsets, self.test), r)
408 for s, r in sorted(subs)
409 ]
410
411 def node(self, ctx, **props):
412 '''format one changeset, unless it is a suppressed merge.'''
413 if not self.merge and len(ctx.parents()) > 1:
414 return False
415 self.t.show(
416 ctx,
417 changes=ctx.changeset(),
418 baseurl=self.ui.config(b'web', b'baseurl'),
419 root=self.repo.root,
420 webroot=self.root,
421 **props,
422 )
423 return True
424
425 def skipsource(self, source):
426 '''true if incoming changes from this source should be skipped.'''
427 ok_sources = self.ui.config(b'notify', b'sources').split()
428 return source not in ok_sources
429
430 def send(self, ctx, count, data):
431 '''send message.'''
432
433 # Select subscribers by revset
434 subs = set()
435 for sub, spec in self.subs:
436 if spec is None:
437 subs.add(sub)
438 continue
439 try:
440 revs = self.repo.revs(b'%r and %d:', spec, ctx.rev())
441 except error.RepoLookupError:
442 continue
443 if len(revs):
444 subs.add(sub)
445 continue
446 if len(subs) == 0:
447 self.ui.debug(
448 b'notify: no subscribers to selected repo and revset\n'
449 )
450 return
451
452 try:
453 msg = mail.parsebytes(data)
454 except emailerrors.MessageParseError as inst:
455 raise error.Abort(stringutil.forcebytestr(inst))
456
457 # store sender and subject
458 sender = msg['From']
459 subject = msg['Subject']
460 if sender is not None:
461 sender = mail.headdecode(sender)
462 if subject is not None:
463 subject = mail.headdecode(subject)
464 del msg['From'], msg['Subject']
465
466 if not msg.is_multipart():
467 # create fresh mime message from scratch
468 # (multipart templates must take care of this themselves)
469 headers = msg.items()
470 payload = msg.get_payload(decode=True)
471 # for notification prefer readability over data precision
472 msg = mail.mimeencode(self.ui, payload, self.charsets, self.test)
473 # reinstate custom headers
474 for k, v in headers:
475 msg[k] = v
476
477 msg['Date'] = encoding.strfromlocal(
478 dateutil.datestr(format=b"%a, %d %b %Y %H:%M:%S %1%2")
479 )
480
481 # try to make subject line exist and be useful
482 if not subject:
483 if count > 1:
484 subject = _(b'%s: %d new changesets') % (self.root, count)
485 else:
486 s = ctx.description().lstrip().split(b'\n', 1)[0].rstrip()
487 subject = b'%s: %s' % (self.root, s)
488 maxsubject = self.ui.configint(b'notify', b'maxsubject')
489 if maxsubject:
490 subject = stringutil.ellipsis(subject, maxsubject)
491 msg['Subject'] = mail.headencode(
492 self.ui, subject, self.charsets, self.test
493 )
494
495 # try to make message have proper sender
496 if not sender:
497 sender = self.ui.config(b'email', b'from') or self.ui.username()
498 if b'@' not in sender or b'@localhost' in sender:
499 sender = self.fixmail(sender)
500 msg['From'] = mail.addressencode(
501 self.ui, sender, self.charsets, self.test
502 )
503
504 msg['X-Hg-Notification'] = 'changeset %s' % ctx
505 if not msg['Message-Id']:
506 msg['Message-Id'] = messageid(ctx, self.domain, self.messageidseed)
507 if self.reply:
508 unfi = self.repo.unfiltered()
509 has_node = unfi.changelog.index.has_node
510 predecessors = [
511 unfi[ctx2]
512 for ctx2 in obsutil.allpredecessors(unfi.obsstore, [ctx.node()])
513 if ctx2 != ctx.node() and has_node(ctx2)
514 ]
515 if predecessors:
516 # There is at least one predecessor, so which to pick?
517 # Ideally, there is a unique root because changesets have
518 # been evolved/rebased one step at a time. In this case,
519 # just picking the oldest known changeset provides a stable
520 # base. It doesn't help when changesets are folded. Any
521 # better solution would require storing more information
522 # in the repository.
523 pred = min(predecessors, key=lambda ctx: ctx.rev())
524 msg['In-Reply-To'] = messageid(
525 pred, self.domain, self.messageidseed
526 )
527 msg['To'] = ', '.join(sorted(subs))
528
529 msgtext = msg.as_bytes()
530 if self.test:
531 self.ui.write(msgtext)
532 if not msgtext.endswith(b'\n'):
533 self.ui.write(b'\n')
534 else:
535 self.ui.status(
536 _(b'notify: sending %d subscribers %d changes\n')
537 % (len(subs), count)
538 )
539 mail.sendmail(
540 self.ui,
541 emailutils.parseaddr(msg['From'])[1],
542 subs,
543 msgtext,
544 mbox=self.mbox,
545 )
546
547 def diff(self, ctx, ref=None):
548 maxdiff = self.ui.configint(b'notify', b'maxdiff')
549 prev = ctx.p1().node()
550 if ref:
551 ref = ref.node()
552 else:
553 ref = ctx.node()
554 diffopts = patch.diffallopts(self.ui)
555 diffopts.showfunc = self.showfunc
556 chunks = patch.diff(self.repo, prev, ref, opts=diffopts)
557 difflines = b''.join(chunks).splitlines()
558
559 if self.ui.configbool(b'notify', b'diffstat'):
560 maxdiffstat = self.ui.configint(b'notify', b'maxdiffstat')
561 s = patch.diffstat(difflines)
562 # s may be nil, don't include the header if it is
563 if s:
564 if maxdiffstat >= 0 and s.count(b"\n") > maxdiffstat + 1:
565 s = s.split(b"\n")
566 msg = _(b'\ndiffstat (truncated from %d to %d lines):\n\n')
567 self.ui.write(msg % (len(s) - 2, maxdiffstat))
568 self.ui.write(b"\n".join(s[:maxdiffstat] + s[-2:]))
569 else:
570 self.ui.write(_(b'\ndiffstat:\n\n%s') % s)
571
572 if maxdiff == 0:
573 return
574 elif maxdiff > 0 and len(difflines) > maxdiff:
575 msg = _(b'\ndiffs (truncated from %d to %d lines):\n\n')
576 self.ui.write(msg % (len(difflines), maxdiff))
577 difflines = difflines[:maxdiff]
578 elif difflines:
579 self.ui.write(_(b'\ndiffs (%d lines):\n\n') % len(difflines))
580
581 self.ui.write(b"\n".join(difflines))
582
583
584 def hook(ui, repo, hooktype, node=None, source=None, **kwargs):
585 """send email notifications to interested subscribers.
586
587 if used as changegroup hook, send one email for all changesets in
588 changegroup. else send one email per changeset."""
589
590 n = notifier(ui, repo, hooktype)
591 ctx = repo.unfiltered()[node]
592
593 if not n.subs:
594 ui.debug(b'notify: no subscribers to repository %s\n' % n.root)
595 return
596 if n.skipsource(source):
597 ui.debug(b'notify: changes have source "%s" - skipping\n' % source)
598 return
599
600 ui.pushbuffer()
601 data = b''
602 count = 0
603 author = b''
604 if hooktype == b'changegroup' or hooktype == b'outgoing':
605 for rev in repo.changelog.revs(start=ctx.rev()):
606 if n.node(repo[rev]):
607 count += 1
608 if not author:
609 author = repo[rev].user()
610 else:
611 data += ui.popbuffer()
612 ui.note(
613 _(b'notify: suppressing notification for merge %d:%s\n')
614 % (rev, repo[rev].hex()[:12])
615 )
616 ui.pushbuffer()
617 if count:
618 n.diff(ctx, repo[b'tip'])
619 elif ctx.rev() in repo:
620 if not n.node(ctx):
621 ui.popbuffer()
622 ui.note(
623 _(b'notify: suppressing notification for merge %d:%s\n')
624 % (ctx.rev(), ctx.hex()[:12])
625 )
626 return
627 count += 1
628 n.diff(ctx)
629 if not author:
630 author = ctx.user()
631
632 data += ui.popbuffer()
633 fromauthor = ui.config(b'notify', b'fromauthor')
634 if author and fromauthor:
635 data = b'\n'.join([b'From: %s' % author, data])
636
637 if count:
638 n.send(ctx, count, data)
639
640
641 def messageid(ctx, domain, messageidseed):
642 if domain and messageidseed:
643 host = domain
644 else:
645 host = encoding.strtolocal(socket.getfqdn())
646 if messageidseed:
647 messagehash = hashlib.sha512(ctx.hex() + messageidseed)
648 messageid = b'<hg.%s@%s>' % (
649 pycompat.sysbytes(messagehash.hexdigest()[:64]),
650 host,
651 )
652 else:
653 messageid = b'<hg.%s.%d.%d@%s>' % (
654 ctx,
655 int(time.time()),
656 hash(ctx.repo().root),
657 host,
658 )
659 return encoding.strfromlocal(messageid)