Debian Codegraph @

hgext/patchbomb.py

raw
1 # patchbomb.py - sending Mercurial changesets as patch emails
2 #
3 # Copyright 2005-2009 Olivia Mackall <[email protected]> and others
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 '''command to send changesets as (a series of) patch emails
9
10 The series is started off with a "[PATCH 0 of N]" introduction, which
11 describes the series as a whole.
12
13 Each patch email has a Subject line of "[PATCH M of N] ...", using the
14 first line of the changeset description as the subject text. The
15 message contains two or three body parts:
16
17 - The changeset description.
18 - [Optional] The result of running diffstat on the patch.
19 - The patch itself, as generated by :hg:`export`.
20
21 Each message refers to the first in the series using the In-Reply-To
22 and References headers, so they will show up as a sequence in threaded
23 mail and news readers, and in mail archives.
24
25 To configure other defaults, add a section like this to your
26 configuration file::
27
28 [email]
29 from = My Name <my@email>
30 to = recipient1, recipient2, ...
31 cc = cc1, cc2, ...
32 bcc = bcc1, bcc2, ...
33 reply-to = address1, address2, ...
34
35 Use ``[patchbomb]`` as configuration section name if you need to
36 override global ``[email]`` address settings.
37
38 Then you can use the :hg:`email` command to mail a series of
39 changesets as a patchbomb.
40
41 You can also either configure the method option in the email section
42 to be a sendmail compatible mailer or fill out the [smtp] section so
43 that the patchbomb extension can automatically send patchbombs
44 directly from the commandline. See the [email] and [smtp] sections in
45 hgrc(5) for details.
46
47 By default, :hg:`email` will prompt for a ``To`` or ``CC`` header if
48 you do not supply one via configuration or the command line. You can
49 override this to never prompt by configuring an empty value::
50
51 [email]
52 cc =
53
54 You can control the default inclusion of an introduction message with the
55 ``patchbomb.intro`` configuration option. The configuration is always
56 overwritten by command line flags like --intro and --desc::
57
58 [patchbomb]
59 intro=auto # include introduction message if more than 1 patch (default)
60 intro=never # never include an introduction message
61 intro=always # always include an introduction message
62
63 You can specify a template for flags to be added in subject prefixes. Flags
64 specified by --flag option are exported as ``{flags}`` keyword::
65
66 [patchbomb]
67 flagtemplate = "{separate(' ',
68 ifeq(branch, 'default', '', branch|upper),
69 flags)}"
70
71 You can set patchbomb to always ask for confirmation by setting
72 ``patchbomb.confirm`` to true.
73 '''
74
75 from __future__ import annotations
76
77 import email.encoders as emailencoders
78 import email.mime.base as emimebase
79 import email.mime.multipart as emimemultipart
80 import email.utils as eutil
81 import os
82 import socket
83
84 from mercurial.i18n import _
85 from mercurial.node import bin
86 from mercurial import (
87 cmdutil,
88 commands,
89 encoding,
90 error,
91 formatter,
92 logcmdutil,
93 mail,
94 patch,
95 pycompat,
96 registrar,
97 scmutil,
98 templater,
99 util,
100 )
101 from mercurial.repo import (
102 factory as repo_factory,
103 )
104 from mercurial.utils import (
105 dateutil,
106 urlutil,
107 )
108
109 stringio = util.stringio
110
111 cmdtable = {}
112 command = registrar.command(cmdtable)
113
114 configtable = {}
115 configitem = registrar.configitem(configtable)
116
117 configitem(
118 b'patchbomb',
119 b'bundletype',
120 default=None,
121 )
122 configitem(
123 b'patchbomb',
124 b'bcc',
125 default=None,
126 )
127 configitem(
128 b'patchbomb',
129 b'cc',
130 default=None,
131 )
132 configitem(
133 b'patchbomb',
134 b'confirm',
135 default=False,
136 )
137 configitem(
138 b'patchbomb',
139 b'flagtemplate',
140 default=None,
141 )
142 configitem(
143 b'patchbomb',
144 b'from',
145 default=None,
146 )
147 configitem(
148 b'patchbomb',
149 b'intro',
150 default=b'auto',
151 )
152 configitem(
153 b'patchbomb',
154 b'publicurl',
155 default=None,
156 )
157 configitem(
158 b'patchbomb',
159 b'reply-to',
160 default=None,
161 )
162 configitem(
163 b'patchbomb',
164 b'to',
165 default=None,
166 )
167
168 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
169 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
170 # be specifying the version(s) of Mercurial they are tested with, or
171 # leave the attribute unspecified.
172 testedwith = b'ships-with-hg-core'
173
174
175 def _addpullheader(seq, ctx):
176 """Add a header pointing to a public URL where the changeset is available"""
177 repo = ctx.repo()
178 # experimental config: patchbomb.publicurl
179 # waiting for some logic that check that the changeset are available on the
180 # destination before patchbombing anything.
181 publicurl = repo.ui.config(b'patchbomb', b'publicurl')
182 if publicurl:
183 return b'Available At %s\n# hg pull %s -r %s' % (
184 publicurl,
185 publicurl,
186 ctx,
187 )
188 return None
189
190
191 def uisetup(ui):
192 cmdutil.extraexport.append(b'pullurl')
193 cmdutil.extraexportmap[b'pullurl'] = _addpullheader
194
195
196 def reposetup(ui, repo):
197 if not repo.local():
198 return
199 repo._wlockfreeprefix.add(b'last-email.txt')
200
201
202 def prompt(ui, prompt, default=None, rest=b':'):
203 if default:
204 prompt += b' [%s]' % default
205 return ui.prompt(prompt + rest, default)
206
207
208 def introwanted(ui, opts, number):
209 '''is an introductory message apparently wanted?'''
210 introconfig = ui.config(b'patchbomb', b'intro')
211 if opts.get(b'intro') or opts.get(b'desc'):
212 intro = True
213 elif introconfig == b'always':
214 intro = True
215 elif introconfig == b'never':
216 intro = False
217 elif introconfig == b'auto':
218 intro = number > 1
219 else:
220 ui.write_err(
221 _(b'warning: invalid patchbomb.intro value "%s"\n') % introconfig
222 )
223 ui.write_err(_(b'(should be one of always, never, auto)\n'))
224 intro = number > 1
225 return intro
226
227
228 def _formatflags(ui, repo, rev, flags):
229 """build flag string optionally by template"""
230 tmpl = ui.config(b'patchbomb', b'flagtemplate')
231 if not tmpl:
232 return b' '.join(flags)
233 out = util.stringio()
234 spec = formatter.literal_templatespec(templater.unquotestring(tmpl))
235 with formatter.templateformatter(ui, out, b'patchbombflag', {}, spec) as fm:
236 fm.startitem()
237 fm.context(ctx=repo[rev])
238 fm.write(b'flags', b'%s', fm.formatlist(flags, name=b'flag'))
239 return out.getvalue()
240
241
242 def _formatprefix(ui, repo, rev, flags, idx, total, numbered):
243 """build prefix to patch subject"""
244 flag = _formatflags(ui, repo, rev, flags)
245 if flag:
246 flag = b' ' + flag
247
248 if not numbered:
249 return b'[PATCH%s]' % flag
250 else:
251 tlen = len(b"%d" % total)
252 return b'[PATCH %0*d of %d%s]' % (tlen, idx, total, flag)
253
254
255 def makepatch(
256 ui,
257 repo,
258 rev,
259 patchlines,
260 opts,
261 _charsets,
262 idx,
263 total,
264 numbered,
265 patchname=None,
266 ):
267 desc = []
268 node = None
269 body = b''
270
271 for line in patchlines:
272 if line.startswith(b'#'):
273 if line.startswith(b'# Node ID'):
274 node = line.split()[-1]
275 continue
276 if line.startswith(b'diff -r') or line.startswith(b'diff --git'):
277 break
278 desc.append(line)
279
280 if not patchname and not node:
281 raise ValueError
282
283 if opts.get(b'attach') and not opts.get(b'body'):
284 body = (
285 b'\n'.join(desc[1:]).strip()
286 or b'Patch subject is complete summary.'
287 )
288 body += b'\n\n\n'
289
290 if opts.get(b'plain'):
291 while patchlines and patchlines[0].startswith(b'# '):
292 patchlines.pop(0)
293 if patchlines:
294 patchlines.pop(0)
295 while patchlines and not patchlines[0].strip():
296 patchlines.pop(0)
297
298 ds = patch.diffstat(patchlines)
299 if opts.get(b'diffstat'):
300 body += ds + b'\n\n'
301
302 addattachment = opts.get(b'attach') or opts.get(b'inline')
303 if not addattachment or opts.get(b'body'):
304 body += b'\n'.join(patchlines)
305
306 if addattachment:
307 msg = emimemultipart.MIMEMultipart()
308 if body:
309 msg.attach(mail.mimeencode(ui, body, _charsets, opts.get(b'test')))
310 p = mail.mimetextpatch(
311 b'\n'.join(patchlines), 'x-patch', opts.get(b'test')
312 )
313 binnode = bin(node)
314 # if node is mq patch, it will have the patch file's name as a tag
315 if not patchname:
316 patchtags = [
317 t
318 for t in repo.nodetags(binnode)
319 if t.endswith(b'.patch') or t.endswith(b'.diff')
320 ]
321 if patchtags:
322 patchname = patchtags[0]
323 elif total > 1:
324 patchname = cmdutil.makefilename(
325 repo[node], b'%b-%n.patch', seqno=idx, total=total
326 )
327 else:
328 patchname = cmdutil.makefilename(repo[node], b'%b.patch')
329 disposition = r'inline'
330 if opts.get(b'attach'):
331 disposition = r'attachment'
332 p['Content-Disposition'] = (
333 disposition + '; filename=' + encoding.strfromlocal(patchname)
334 )
335 msg.attach(p)
336 else:
337 msg = mail.mimetextpatch(body, display=opts.get(b'test'))
338
339 prefix = _formatprefix(
340 ui, repo, rev, opts.get(b'flag'), idx, total, numbered
341 )
342 subj = desc[0].strip().rstrip(b'. ')
343 if not numbered:
344 subj = b' '.join([prefix, opts.get(b'subject') or subj])
345 else:
346 subj = b' '.join([prefix, subj])
347 msg['Subject'] = mail.headencode(ui, subj, _charsets, opts.get(b'test'))
348 msg['X-Mercurial-Node'] = pycompat.sysstr(node)
349 msg['X-Mercurial-Series-Index'] = '%i' % idx
350 msg['X-Mercurial-Series-Total'] = '%i' % total
351 return msg, subj, ds
352
353
354 def _getpatches(repo, revs, **opts):
355 """return a list of patches for a list of revisions
356
357 Each patch in the list is itself a list of lines.
358 """
359 ui = repo.ui
360 prev = repo[b'.'].rev()
361 for r in revs:
362 if r == prev and (repo[None].files() or repo[None].deleted()):
363 ui.warn(_(b'warning: working directory has uncommitted changes\n'))
364 output = stringio()
365 cmdutil.exportfile(
366 repo,
367 [r],
368 output,
369 opts=patch.difffeatureopts(
370 ui, pycompat.byteskwargs(opts), git=True
371 ),
372 )
373 yield output.getvalue().split(b'\n')
374
375
376 def _getbundle(repo, dest, **opts):
377 """return a bundle containing changesets missing in "dest"
378
379 The `opts` keyword-arguments are the same as the one accepted by the
380 `bundle` command.
381
382 The bundle is a returned as a single in-memory binary blob.
383 """
384 ui = repo.ui
385 tmpdir = pycompat.mkdtemp(prefix=b'hg-email-bundle-')
386 tmpfn = os.path.join(tmpdir, b'bundle')
387 btype = ui.config(b'patchbomb', b'bundletype')
388 if btype:
389 opts['type'] = btype
390 try:
391 dests = []
392 if dest:
393 dests = [dest]
394 commands.bundle(ui, repo, tmpfn, *dests, **opts)
395 return util.readfile(tmpfn)
396 finally:
397 try:
398 os.unlink(tmpfn)
399 except OSError:
400 pass
401 os.rmdir(tmpdir)
402
403
404 def _getdescription(repo, defaultbody, sender, **opts):
405 """obtain the body of the introduction message and return it
406
407 This is also used for the body of email with an attached bundle.
408
409 The body can be obtained either from the command line option or entered by
410 the user through the editor.
411 """
412 ui = repo.ui
413 if opts.get('desc'):
414 body = util.readfile(opts.get('desc'))
415 else:
416 ui.write(
417 _(b'\nWrite the introductory message for the patch series.\n\n')
418 )
419 body = ui.edit(
420 defaultbody, sender, repopath=repo.path, action=b'patchbombbody'
421 )
422
423 # Save series description in case sendmail fails
424 with repo.vfs(b'last-email.txt', b'wb') as msgfile:
425 msgfile.write(body)
426
427 return body
428
429
430 def _getbundlemsgs(repo, sender, bundle, **opts):
431 """Get the full email for sending a given bundle
432
433 This function returns a list of "email" tuples (subject, content, None).
434 The list is always one message long in that case.
435 """
436 ui = repo.ui
437 _charsets = mail._charsets(ui)
438 subj = opts.get('subject') or prompt(
439 ui, b'Subject:', b'A bundle for your repository'
440 )
441
442 body = _getdescription(repo, b'', sender, **opts)
443 msg = emimemultipart.MIMEMultipart()
444 if body:
445 msg.attach(mail.mimeencode(ui, body, _charsets, opts.get('test')))
446 datapart = emimebase.MIMEBase('application', 'x-mercurial-bundle')
447 datapart.set_payload(bundle)
448 bundlename = b'%s.hg' % opts.get('bundlename', b'bundle')
449 datapart.add_header(
450 'Content-Disposition',
451 'attachment',
452 filename=encoding.strfromlocal(bundlename),
453 )
454 emailencoders.encode_base64(datapart)
455 msg.attach(datapart)
456 msg['Subject'] = mail.headencode(ui, subj, _charsets, opts.get('test'))
457 return [(msg, subj, None)]
458
459
460 def _makeintro(repo, sender, revs, patches, **opts):
461 """make an introduction email, asking the user for content if needed
462
463 email is returned as (subject, body, cumulative-diffstat)"""
464 ui = repo.ui
465 _charsets = mail._charsets(ui)
466
467 # use the last revision which is likely to be a bookmarked head
468 prefix = _formatprefix(
469 ui, repo, revs.last(), opts.get('flag'), 0, len(patches), numbered=True
470 )
471 subj = opts.get('subject') or prompt(
472 ui, b'(optional) Subject: ', rest=prefix, default=b''
473 )
474 if not subj:
475 return None # skip intro if the user doesn't bother
476
477 subj = prefix + b' ' + subj
478
479 body = b''
480 if opts.get('diffstat'):
481 # generate a cumulative diffstat of the whole patch series
482 diffstat = patch.diffstat(sum(patches, []))
483 body = b'\n' + diffstat
484 else:
485 diffstat = None
486
487 body = _getdescription(repo, body, sender, **opts)
488 msg = mail.mimeencode(ui, body, _charsets, opts.get('test'))
489 msg['Subject'] = mail.headencode(ui, subj, _charsets, opts.get('test'))
490 return (msg, subj, diffstat)
491
492
493 def _getpatchmsgs(repo, sender, revs, patchnames=None, **opts):
494 """return a list of emails from a list of patches
495
496 This involves introduction message creation if necessary.
497
498 This function returns a list of "email" tuples (subject, content, None).
499 """
500 bytesopts = pycompat.byteskwargs(opts)
501 ui = repo.ui
502 _charsets = mail._charsets(ui)
503 patches = list(_getpatches(repo, revs, **opts))
504 msgs = []
505
506 ui.write(_(b'this patch series consists of %d patches.\n\n') % len(patches))
507
508 # build the intro message, or skip it if the user declines
509 if introwanted(ui, bytesopts, len(patches)):
510 msg = _makeintro(repo, sender, revs, patches, **opts)
511 if msg:
512 msgs.append(msg)
513
514 # are we going to send more than one message?
515 numbered = len(msgs) + len(patches) > 1
516
517 # now generate the actual patch messages
518 name = None
519 assert len(revs) == len(patches)
520 for i, (r, p) in enumerate(zip(revs, patches)):
521 if patchnames:
522 name = patchnames[i]
523 msg = makepatch(
524 ui,
525 repo,
526 r,
527 p,
528 bytesopts,
529 _charsets,
530 i + 1,
531 len(patches),
532 numbered,
533 name,
534 )
535 msgs.append(msg)
536
537 return msgs
538
539
540 def _getoutgoing(repo, dest, revs):
541 '''Return the revisions present locally but not in dest'''
542 ui = repo.ui
543 paths = urlutil.get_push_paths(repo, ui, [dest] if dest else None)
544 safe_paths = [urlutil.hidepassword(p.rawloc) for p in paths]
545 ui.status(_(b'comparing with %s\n') % b','.join(safe_paths))
546
547 revs = [r for r in revs if r >= 0]
548 if not revs:
549 revs = [repo.changelog.tiprev()]
550 revs = repo.revs(b'outgoing(%s) and ::%ld', dest or b'', revs)
551 if not revs:
552 ui.status(_(b"no changes found\n"))
553 return revs
554
555
556 def _msgid(node, timestamp):
557 try:
558 hostname = encoding.strfromlocal(encoding.environ[b'HGHOSTNAME'])
559 except KeyError:
560 hostname = socket.getfqdn()
561 return '<%s.%d@%s>' % (node, timestamp, hostname)
562
563
564 emailopts = [
565 (b'', b'body', None, _(b'send patches as inline message text (default)')),
566 (b'a', b'attach', None, _(b'send patches as attachments')),
567 (b'i', b'inline', None, _(b'send patches as inline attachments')),
568 (
569 b'',
570 b'bcc',
571 [],
572 _(b'email addresses of blind carbon copy recipients'),
573 _(b'EMAIL'),
574 ),
575 (b'c', b'cc', [], _(b'email addresses of copy recipients'), _(b'EMAIL')),
576 (b'', b'confirm', None, _(b'ask for confirmation before sending')),
577 (b'd', b'diffstat', None, _(b'add diffstat output to messages')),
578 (
579 b'',
580 b'date',
581 b'',
582 _(b'use the given date as the sending date'),
583 _(b'DATE'),
584 ),
585 (
586 b'',
587 b'desc',
588 b'',
589 _(b'use the given file as the series description'),
590 _(b'FILE'),
591 ),
592 (b'f', b'from', b'', _(b'email address of sender'), _(b'EMAIL')),
593 (b'n', b'test', None, _(b'print messages that would be sent')),
594 (
595 b'm',
596 b'mbox',
597 b'',
598 _(b'write messages to mbox file instead of sending them'),
599 _(b'FILE'),
600 ),
601 (
602 b'',
603 b'reply-to',
604 [],
605 _(b'email addresses replies should be sent to'),
606 _(b'EMAIL'),
607 ),
608 (
609 b's',
610 b'subject',
611 b'',
612 _(b'subject of first message (intro or single patch)'),
613 _(b'TEXT'),
614 ),
615 (
616 b'',
617 b'in-reply-to',
618 b'',
619 _(b'message identifier to reply to'),
620 _(b'MSGID'),
621 ),
622 (b'', b'flag', [], _(b'flags to add in subject prefixes'), _(b'FLAG')),
623 (b't', b'to', [], _(b'email addresses of recipients'), _(b'EMAIL')),
624 ]
625
626
627 @command(
628 b'email',
629 [
630 (b'g', b'git', None, _(b'use git extended diff format')),
631 (b'', b'plain', None, _(b'omit hg patch header')),
632 (
633 b'o',
634 b'outgoing',
635 None,
636 _(b'send changes not found in the target repository'),
637 ),
638 (
639 b'b',
640 b'bundle',
641 None,
642 _(b'send changes not in target as a binary bundle'),
643 ),
644 (
645 b'B',
646 b'bookmark',
647 b'',
648 _(b'send changes only reachable by given bookmark'),
649 _(b'BOOKMARK'),
650 ),
651 (
652 b'',
653 b'bundlename',
654 b'bundle',
655 _(b'name of the bundle attachment file'),
656 _(b'NAME'),
657 ),
658 (b'r', b'rev', [], _(b'a revision to send'), _(b'REV')),
659 (
660 b'',
661 b'force',
662 None,
663 _(
664 b'run even when remote repository is unrelated '
665 b'(with -b/--bundle)'
666 ),
667 ),
668 (
669 b'',
670 b'base',
671 [],
672 _(
673 b'a base changeset to specify instead of a destination '
674 b'(with -b/--bundle)'
675 ),
676 _(b'REV'),
677 ),
678 (
679 b'',
680 b'intro',
681 None,
682 _(b'send an introduction email for a single patch'),
683 ),
684 ]
685 + emailopts
686 + cmdutil.remoteopts,
687 _(b'hg email [OPTION]... [DEST]...'),
688 helpcategory=command.CATEGORY_IMPORT_EXPORT,
689 )
690 def email(ui, repo, *revs, **opts):
691 """send changesets by email
692
693 By default, diffs are sent in the format generated by
694 :hg:`export`, one per message. The series starts with a "[PATCH 0
695 of N]" introduction, which describes the series as a whole.
696
697 Each patch email has a Subject line of "[PATCH M of N] ...", using
698 the first line of the changeset description as the subject text.
699 The message contains two or three parts. First, the changeset
700 description.
701
702 With the -d/--diffstat option, if the diffstat program is
703 installed, the result of running diffstat on the patch is inserted.
704
705 Finally, the patch itself, as generated by :hg:`export`.
706
707 With the -d/--diffstat or --confirm options, you will be presented
708 with a final summary of all messages and asked for confirmation before
709 the messages are sent.
710
711 By default the patch is included as text in the email body for
712 easy reviewing. Using the -a/--attach option will instead create
713 an attachment for the patch. With -i/--inline an inline attachment
714 will be created. You can include a patch both as text in the email
715 body and as a regular or an inline attachment by combining the
716 -a/--attach or -i/--inline with the --body option.
717
718 With -B/--bookmark changesets reachable by the given bookmark are
719 selected.
720
721 With -o/--outgoing, emails will be generated for patches not found
722 in the destination repository (or only those which are ancestors
723 of the specified revisions if any are provided)
724
725 With -b/--bundle, changesets are selected as for --outgoing, but a
726 single email containing a binary Mercurial bundle as an attachment
727 will be sent. Use the ``patchbomb.bundletype`` config option to
728 control the bundle type as with :hg:`bundle --type`.
729
730 With -m/--mbox, instead of previewing each patchbomb message in a
731 pager or sending the messages directly, it will create a UNIX
732 mailbox file with the patch emails. This mailbox file can be
733 previewed with any mail user agent which supports UNIX mbox
734 files.
735
736 With -n/--test, all steps will run, but mail will not be sent.
737 You will be prompted for an email recipient address, a subject and
738 an introductory message describing the patches of your patchbomb.
739 Then when all is done, patchbomb messages are displayed.
740
741 In case email sending fails, you will find a backup of your series
742 introductory message in ``.hg/last-email.txt``.
743
744 The default behavior of this command can be customized through
745 configuration. (See :hg:`help patchbomb` for details)
746
747 Examples::
748
749 hg email -r 3000 # send patch 3000 only
750 hg email -r 3000 -r 3001 # send patches 3000 and 3001
751 hg email -r 3000:3005 # send patches 3000 through 3005
752 hg email 3000 # send patch 3000 (deprecated)
753
754 hg email -o # send all patches not in default
755 hg email -o DEST # send all patches not in DEST
756 hg email -o -r 3000 # send all ancestors of 3000 not in default
757 hg email -o -r 3000 DEST # send all ancestors of 3000 not in DEST
758
759 hg email -B feature # send all ancestors of feature bookmark
760
761 hg email -b # send bundle of all patches not in default
762 hg email -b DEST # send bundle of all patches not in DEST
763 hg email -b -r 3000 # bundle of all ancestors of 3000 not in default
764 hg email -b -r 3000 DEST # bundle of all ancestors of 3000 not in DEST
765
766 hg email -o -m mbox && # generate an mbox file...
767 mutt -R -f mbox # ... and view it with mutt
768 hg email -o -m mbox && # generate an mbox file ...
769 formail -s sendmail \\ # ... and use formail to send from the mbox
770 -bm -t < mbox # ... using sendmail
771
772 Before using this command, you will need to enable email in your
773 hgrc. See the [email] section in hgrc(5) for details.
774 """
775 opts = pycompat.byteskwargs(opts)
776
777 _charsets = mail._charsets(ui)
778
779 bundle = opts.get(b'bundle')
780 date = opts.get(b'date')
781 mbox = opts.get(b'mbox')
782 outgoing = opts.get(b'outgoing')
783 rev = opts.get(b'rev')
784 bookmark = opts.get(b'bookmark')
785
786 if not (opts.get(b'test') or mbox):
787 # really sending
788 mail.validateconfig(ui)
789
790 if not (revs or rev or outgoing or bundle or bookmark):
791 raise error.Abort(
792 _(b'specify at least one changeset with -B, -r or -o')
793 )
794
795 if outgoing and bundle:
796 raise error.Abort(
797 _(
798 b"--outgoing mode always on with --bundle;"
799 b" do not re-specify --outgoing"
800 )
801 )
802 cmdutil.check_at_most_one_arg(opts, b'rev', b'bookmark')
803
804 if outgoing or bundle:
805 if len(revs) > 1:
806 raise error.Abort(_(b"too many destinations"))
807 if revs:
808 dest = revs[0]
809 else:
810 dest = None
811 revs = []
812
813 if rev:
814 if revs:
815 raise error.Abort(_(b'use only one form to specify the revision'))
816 revs = rev
817 elif bookmark:
818 if bookmark not in repo._bookmarks:
819 raise error.Abort(_(b"bookmark '%s' not found") % bookmark)
820 revs = scmutil.bookmarkrevs(repo, bookmark)
821
822 revs = logcmdutil.revrange(repo, revs)
823 if outgoing:
824 revs = _getoutgoing(repo, dest, revs)
825 if bundle:
826 opts[b'revs'] = [b"%d" % r for r in revs]
827
828 # check if revision exist on the public destination
829 publicurl = repo.ui.config(b'patchbomb', b'publicurl')
830 if publicurl:
831 repo.ui.debug(b'checking that revision exist in the public repo\n')
832 try:
833 publicpeer = repo_factory.peer(repo, {}, publicurl)
834 except error.RepoError:
835 repo.ui.write_err(
836 _(b'unable to access public repo: %s\n') % publicurl
837 )
838 raise
839 if not publicpeer.capable(b'known'):
840 repo.ui.debug(b'skipping existence checks: public repo too old\n')
841 else:
842 out = [repo[r] for r in revs]
843 known = publicpeer.known(h.node() for h in out)
844 missing = []
845 for idx, h in enumerate(out):
846 if not known[idx]:
847 missing.append(h)
848 if missing:
849 if len(missing) > 1:
850 msg = _(b'public "%s" is missing %s and %i others')
851 msg %= (publicurl, missing[0], len(missing) - 1)
852 else:
853 msg = _(b'public url %s is missing %s')
854 msg %= (publicurl, missing[0])
855 missingrevs = [ctx.rev() for ctx in missing]
856 revhint = b' '.join(
857 b'-r %s' % h for h in repo.set(b'heads(%ld)', missingrevs)
858 )
859 hint = _(b"use 'hg push %s %s'") % (publicurl, revhint)
860 raise error.Abort(msg, hint=hint)
861
862 # start
863 if date:
864 start_time = dateutil.parsedate(date)
865 else:
866 start_time = dateutil.makedate()
867
868 def genmsgid(id):
869 return _msgid(id[:20], int(start_time[0]))
870
871 # deprecated config: patchbomb.from
872 sender = (
873 opts.get(b'from')
874 or ui.config(b'email', b'from')
875 or ui.config(b'patchbomb', b'from')
876 or prompt(ui, b'From', ui.username())
877 )
878
879 if bundle:
880 stropts = pycompat.strkwargs(opts)
881 bundledata = _getbundle(repo, dest, **stropts)
882 bundleopts = stropts.copy()
883 bundleopts.pop('bundle', None) # already processed
884 msgs = _getbundlemsgs(repo, sender, bundledata, **bundleopts)
885 else:
886 msgs = _getpatchmsgs(repo, sender, revs, **pycompat.strkwargs(opts))
887
888 showaddrs = []
889
890 def getaddrs(header, ask=False, default=None):
891 configkey = header.lower()
892 opt = header.replace(b'-', b'_').lower()
893 addrs = opts.get(opt)
894 if addrs:
895 showaddrs.append(b'%s: %s' % (header, b', '.join(addrs)))
896 return mail.addrlistencode(ui, addrs, _charsets, opts.get(b'test'))
897
898 # not on the command line: fallback to config and then maybe ask
899 addr = ui.config(b'email', configkey) or ui.config(
900 b'patchbomb', configkey
901 )
902 if not addr:
903 specified = ui.hasconfig(b'email', configkey) or ui.hasconfig(
904 b'patchbomb', configkey
905 )
906 if not specified and ask:
907 addr = prompt(ui, header, default=default)
908 if addr:
909 showaddrs.append(b'%s: %s' % (header, addr))
910 return mail.addrlistencode(ui, [addr], _charsets, opts.get(b'test'))
911 elif default:
912 return mail.addrlistencode(
913 ui, [default], _charsets, opts.get(b'test')
914 )
915 return []
916
917 to = getaddrs(b'To', ask=True)
918 if not to:
919 # we can get here in non-interactive mode
920 raise error.Abort(_(b'no recipient addresses provided'))
921 cc = getaddrs(b'Cc', ask=True, default=b'')
922 bcc = getaddrs(b'Bcc')
923 replyto = getaddrs(b'Reply-To')
924
925 confirm = ui.configbool(b'patchbomb', b'confirm')
926 confirm |= bool(opts.get(b'diffstat') or opts.get(b'confirm'))
927
928 if confirm:
929 ui.write(_(b'\nFinal summary:\n\n'), label=b'patchbomb.finalsummary')
930 ui.write((b'From: %s\n' % sender), label=b'patchbomb.from')
931 for addr in showaddrs:
932 ui.write(b'%s\n' % addr, label=b'patchbomb.to')
933 for m, subj, ds in msgs:
934 ui.write((b'Subject: %s\n' % subj), label=b'patchbomb.subject')
935 if ds:
936 ui.write(ds, label=b'patchbomb.diffstats')
937 ui.write(b'\n')
938 if ui.promptchoice(
939 _(b'are you sure you want to send (yn)?$$ &Yes $$ &No')
940 ):
941 raise error.Abort(_(b'patchbomb canceled'))
942
943 ui.write(b'\n')
944
945 parent = opts.get(b'in_reply_to') or None
946 # angle brackets may be omitted, they're not semantically part of the msg-id
947 if parent is not None:
948 parent = encoding.strfromlocal(parent)
949 if not parent.startswith('<'):
950 parent = '<' + parent
951 if not parent.endswith('>'):
952 parent += '>'
953
954 sender_addr = eutil.parseaddr(encoding.strfromlocal(sender))[1]
955 sender = mail.addressencode(ui, sender, _charsets, opts.get(b'test'))
956 sendmail = None
957 firstpatch = None
958 progress = ui.makeprogress(
959 _(b'sending'), unit=_(b'emails'), total=len(msgs)
960 )
961 for i, (m, subj, ds) in enumerate(msgs):
962 try:
963 m['Message-Id'] = genmsgid(m['X-Mercurial-Node'])
964 if not firstpatch:
965 firstpatch = m['Message-Id']
966 m['X-Mercurial-Series-Id'] = firstpatch
967 except TypeError:
968 m['Message-Id'] = genmsgid('patchbomb')
969 if parent:
970 m['In-Reply-To'] = parent
971 m['References'] = parent
972 if not parent or 'X-Mercurial-Node' not in m:
973 parent = m['Message-Id']
974
975 m['User-Agent'] = 'Mercurial-patchbomb/%s' % util.version().decode()
976 m['Date'] = eutil.formatdate(start_time[0], localtime=True)
977
978 start_time = (start_time[0] + 1, start_time[1])
979 m['From'] = sender
980 m['To'] = ', '.join(to)
981 if cc:
982 m['Cc'] = ', '.join(cc)
983 if bcc:
984 m['Bcc'] = ', '.join(bcc)
985 if replyto:
986 m['Reply-To'] = ', '.join(replyto)
987 if opts.get(b'test'):
988 ui.status(_(b'displaying '), subj, b' ...\n')
989 ui.pager(b'email')
990 generator = mail.Generator(ui, mangle_from_=False)
991 try:
992 generator.flatten(m, False)
993 ui.write(b'\n')
994 except BrokenPipeError:
995 pass
996 else:
997 if not sendmail:
998 sendmail = mail.connect(ui, mbox=mbox)
999 ui.status(_(b'sending '), subj, b' ...\n')
1000 progress.update(i, item=subj)
1001 if not mbox:
1002 # Exim does not remove the Bcc field
1003 del m['Bcc']
1004 fp = stringio()
1005 generator = mail.Generator(fp, mangle_from_=False)
1006 generator.flatten(m, False)
1007 alldests = to + bcc + cc
1008 sendmail(sender_addr, alldests, fp.getvalue())
1009
1010 progress.complete()