Pass the --in-reply-to and --no-thread options to git send-email
[stgit] / stgit / commands / mail.py
1 __copyright__ = """
2 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License version 2 as
6 published by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 """
17
18 import sys, os, re, time, datetime, socket, smtplib, getpass
19 import email, email.Utils, email.Header
20 from stgit.argparse import opt
21 from stgit.commands.common import *
22 from stgit.utils import *
23 from stgit.out import *
24 from stgit import argparse, stack, git, version, templates
25 from stgit.config import config
26 from stgit.run import Run
27 from stgit.lib import git as gitlib
28
29 help = 'Send a patch or series of patches by e-mail'
30 kind = 'patch'
31 usage = [' [options] [--] [<patch1>] [<patch2>] [<patch3>..<patch4>]']
32 description = r"""
33 Send a patch or a range of patches by e-mail using the SMTP server
34 specified by the 'stgit.smtpserver' configuration option, or the
35 '--smtp-server' command line option. This option can also be an
36 absolute path to 'sendmail' followed by command line arguments.
37
38 The From address and the e-mail format are generated from the template
39 file passed as argument to '--template' (defaulting to
40 '.git/patchmail.tmpl' or '~/.stgit/templates/patchmail.tmpl' or
41 '/usr/share/stgit/templates/patchmail.tmpl'). A patch can be sent as
42 attachment using the --attach option in which case the
43 'mailattch.tmpl' template will be used instead of 'patchmail.tmpl'.
44
45 The To/Cc/Bcc addresses can either be added to the template file or
46 passed via the corresponding command line options. They can be e-mail
47 addresses or aliases which are automatically expanded to the values
48 stored in the [mail "alias"] section of GIT configuration files.
49
50 A preamble e-mail can be sent using the '--cover' and/or
51 '--edit-cover' options. The first allows the user to specify a file to
52 be used as a template. The latter option will invoke the editor on the
53 specified file (defaulting to '.git/covermail.tmpl' or
54 '~/.stgit/templates/covermail.tmpl' or
55 '/usr/share/stgit/templates/covermail.tmpl').
56
57 All the subsequent e-mails appear as replies to the first e-mail sent
58 (either the preamble or the first patch). E-mails can be seen as
59 replies to a different e-mail by using the '--in-reply-to' option.
60
61 SMTP authentication is also possible with '--smtp-user' and
62 '--smtp-password' options, also available as configuration settings:
63 'smtpuser' and 'smtppassword'. TLS encryption can be enabled by
64 '--smtp-tls' option and 'smtptls' setting.
65
66 The following variables are accepted by both the preamble and the
67 patch e-mail templates:
68
69 %(diffstat)s - diff statistics
70 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
71 %(patchnr)s - patch number
72 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
73 %(totalnr)s - total number of patches to be sent
74 %(version)s - ' version' string passed on the command line (or empty)
75
76 In addition to the common variables, the preamble e-mail template
77 accepts the following:
78
79 %(shortlog)s - first line of each patch description, listed by author
80
81 In addition to the common variables, the patch e-mail template accepts
82 the following:
83
84 %(authdate)s - patch creation date
85 %(authemail)s - author's email
86 %(authname)s - author's name
87 %(commemail)s - committer's e-mail
88 %(commname)s - committer's name
89 %(diff)s - unified diff of the patch
90 %(fromauth)s - 'From: author\n\n' if different from sender
91 %(longdescr)s - the rest of the patch description, after the first line
92 %(patch)s - patch name
93 %(prefix)s - 'prefix ' string passed on the command line
94 %(shortdescr)s - the first line of the patch description"""
95
96 args = [argparse.patch_range(argparse.applied_patches,
97 argparse.unapplied_patches,
98 argparse.hidden_patches)]
99 options = [
100 opt('-a', '--all', action = 'store_true',
101 short = 'E-mail all the applied patches'),
102 opt('--to', action = 'append',
103 short = 'Add TO to the To: list'),
104 opt('--cc', action = 'append',
105 short = 'Add CC to the Cc: list'),
106 opt('--bcc', action = 'append',
107 short = 'Add BCC to the Bcc: list'),
108 opt('--auto', action = 'store_true',
109 short = 'Automatically cc the patch signers'),
110 opt('--no-thread', action = 'store_true',
111 short = 'Do not send subsequent messages as replies'),
112 opt('--unrelated', action = 'store_true',
113 short = 'Send patches without sequence numbering'),
114 opt('--attach', action = 'store_true',
115 short = 'Send a patch as attachment'),
116 opt('-v', '--version', metavar = 'VERSION',
117 short = 'Add VERSION to the [PATCH ...] prefix'),
118 opt('--prefix', metavar = 'PREFIX',
119 short = 'Add PREFIX to the [... PATCH ...] prefix'),
120 opt('-t', '--template', metavar = 'FILE',
121 short = 'Use FILE as the message template'),
122 opt('-c', '--cover', metavar = 'FILE',
123 short = 'Send FILE as the cover message'),
124 opt('-e', '--edit-cover', action = 'store_true',
125 short = 'Edit the cover message before sending'),
126 opt('-E', '--edit-patches', action = 'store_true',
127 short = 'Edit each patch before sending'),
128 opt('-s', '--sleep', type = 'int', metavar = 'SECONDS',
129 short = 'Sleep for SECONDS between e-mails sending'),
130 opt('--in-reply-to', metavar = 'REFID',
131 short = 'Use REFID as the reference id'),
132 opt('--smtp-server', metavar = 'HOST[:PORT] or "/path/to/sendmail -t -i"',
133 short = 'SMTP server or command to use for sending mail'),
134 opt('-u', '--smtp-user', metavar = 'USER',
135 short = 'Username for SMTP authentication'),
136 opt('-p', '--smtp-password', metavar = 'PASSWORD',
137 short = 'Password for SMTP authentication'),
138 opt('-T', '--smtp-tls', action = 'store_true',
139 short = 'Use SMTP with TLS encryption'),
140 opt('-b', '--branch', args = [argparse.stg_branches],
141 short = 'Use BRANCH instead of the default branch'),
142 opt('-m', '--mbox', action = 'store_true',
143 short = 'Generate an mbox file instead of sending'),
144 opt('--git', action = 'store_true',
145 short = 'Use git send-email (EXPERIMENTAL)')
146 ] + argparse.diff_opts_option()
147
148 directory = DirectoryHasRepository(log = False)
149
150 def __get_sender():
151 """Return the 'authname <authemail>' string as read from the
152 configuration file
153 """
154 sender=config.get('stgit.sender')
155 if not sender:
156 try:
157 sender = str(git.user())
158 except git.GitException:
159 try:
160 sender = str(git.author())
161 except git.GitException:
162 pass
163 if not sender:
164 raise CmdException, ('Unknown sender name and e-mail; you should'
165 ' for example set git config user.name and'
166 ' user.email')
167 sender = email.Utils.parseaddr(sender)
168
169 return email.Utils.formataddr(address_or_alias(sender))
170
171 def __addr_list(msg, header):
172 return [addr for name, addr in
173 email.Utils.getaddresses(msg.get_all(header, []))]
174
175 def __parse_addresses(msg):
176 """Return a two elements tuple: (from, [to])
177 """
178 from_addr_list = __addr_list(msg, 'From')
179 if len(from_addr_list) == 0:
180 raise CmdException, 'No "From" address'
181
182 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
183 + __addr_list(msg, 'Bcc')
184 if len(to_addr_list) == 0:
185 raise CmdException, 'No "To/Cc/Bcc" addresses'
186
187 return (from_addr_list[0], set(to_addr_list))
188
189 def __send_message_sendmail(sendmail, msg):
190 """Send the message using the sendmail command.
191 """
192 cmd = sendmail.split()
193 Run(*cmd).raw_input(msg).discard_output()
194
195 def __send_message_smtp(smtpserver, from_addr, to_addr_list, msg, options):
196 """Send the message using the given SMTP server
197 """
198 smtppassword = options.smtp_password or config.get('stgit.smtppassword')
199 smtpuser = options.smtp_user or config.get('stgit.smtpuser')
200 smtpusetls = options.smtp_tls or config.get('stgit.smtptls') == 'yes'
201
202 if (smtppassword and not smtpuser):
203 raise CmdException('SMTP password supplied, username needed')
204 if (smtpusetls and not smtpuser):
205 raise CmdException('SMTP over TLS requested, username needed')
206 if (smtpuser and not smtppassword):
207 smtppassword = getpass.getpass("Please enter SMTP password: ")
208
209 try:
210 s = smtplib.SMTP(smtpserver)
211 except Exception, err:
212 raise CmdException, str(err)
213
214 s.set_debuglevel(0)
215 try:
216 if smtpuser and smtppassword:
217 s.ehlo()
218 if smtpusetls:
219 if not hasattr(socket, 'ssl'):
220 raise CmdException, "cannot use TLS - no SSL support in Python"
221 s.starttls()
222 s.ehlo()
223 s.login(smtpuser, smtppassword)
224
225 result = s.sendmail(from_addr, to_addr_list, msg)
226 if len(result):
227 print "mail server refused delivery for the following recipients: %s" % result
228 except Exception, err:
229 raise CmdException, str(err)
230
231 s.quit()
232
233 def __send_message_git(msg, options):
234 """Send the message using git send-email
235 """
236 from subprocess import call
237 from tempfile import mkstemp
238
239 cmd = ["git", "send-email", "--from=%s" % msg['From']]
240 cmd.append("--quiet")
241 cmd.append("--suppress-cc=self")
242 if not options.auto:
243 cmd.append("--suppress-cc=body")
244 if options.in_reply_to:
245 cmd.extend(["--in-reply-to", options.in_reply_to])
246 if options.no_thread:
247 cmd.append("--no-thread")
248
249 # We only support To/Cc/Bcc in git send-email for now.
250 for x in ['to', 'cc', 'bcc']:
251 if getattr(options, x):
252 cmd.extend('--%s=%s' % (x, a) for a in getattr(options, x))
253
254 (fd, path) = mkstemp()
255 os.write(fd, msg.as_string(options.mbox))
256 os.close(fd)
257
258 try:
259 try:
260 cmd.append(path)
261 call(cmd)
262 except Exception, err:
263 raise CmdException, str(err)
264 finally:
265 os.unlink(path)
266
267 def __send_message(type, tmpl, options, *args):
268 """Message sending dispatcher.
269 """
270 (build, outstr) = {'cover': (__build_cover, 'the cover message'),
271 'patch': (__build_message, 'patch "%s"' % args[0])}[type]
272 if type == 'patch':
273 (patch_nr, total_nr) = (args[1], args[2])
274
275 msg_id = email.Utils.make_msgid('stgit')
276 msg = build(tmpl, msg_id, options, *args)
277
278 msg_str = msg.as_string(options.mbox)
279 if options.mbox:
280 out.stdout_raw(msg_str + '\n')
281 return msg_id
282
283 if not options.git:
284 from_addr, to_addrs = __parse_addresses(msg)
285 out.start('Sending ' + outstr)
286
287 smtpserver = options.smtp_server or config.get('stgit.smtpserver')
288 if options.git:
289 __send_message_git(msg, options)
290 elif smtpserver.startswith('/'):
291 # Use the sendmail tool
292 __send_message_sendmail(smtpserver, msg_str)
293 else:
294 # Use the SMTP server (we have host and port information)
295 __send_message_smtp(smtpserver, from_addr, to_addrs, msg_str, options)
296
297 # give recipients a chance of receiving related patches in correct order
298 if type == 'cover' or (type == 'patch' and patch_nr < total_nr):
299 sleep = options.sleep or config.getint('stgit.smtpdelay')
300 time.sleep(sleep)
301 if not options.git:
302 out.done()
303 return msg_id
304
305 def __update_header(msg, header, addr = '', ignore = ()):
306 def __addr_pairs(msg, header, extra):
307 pairs = email.Utils.getaddresses(msg.get_all(header, []) + extra)
308 # remove pairs without an address and resolve the aliases
309 return [address_or_alias(p) for p in pairs if p[1]]
310
311 addr_pairs = __addr_pairs(msg, header, [addr])
312 del msg[header]
313 # remove the duplicates and filter the addresses
314 addr_dict = dict((addr, email.Utils.formataddr((name, addr)))
315 for name, addr in addr_pairs if addr not in ignore)
316 if addr_dict:
317 msg[header] = ', '.join(addr_dict.itervalues())
318 return set(addr_dict.iterkeys())
319
320 def __build_address_headers(msg, options, extra_cc = []):
321 """Build the address headers and check existing headers in the
322 template.
323 """
324 to_addr = ''
325 cc_addr = ''
326 extra_cc_addr = ''
327 bcc_addr = ''
328
329 autobcc = config.get('stgit.autobcc') or ''
330
331 if options.to:
332 to_addr = ', '.join(options.to)
333 if options.cc:
334 cc_addr = ', '.join(options.cc)
335 if extra_cc:
336 extra_cc_addr = ', '.join(extra_cc)
337 if options.bcc:
338 bcc_addr = ', '.join(options.bcc + [autobcc])
339 elif autobcc:
340 bcc_addr = autobcc
341
342 # if an address is on a header, ignore it from the rest
343 to_set = __update_header(msg, 'To', to_addr)
344 cc_set = __update_header(msg, 'Cc', cc_addr, to_set)
345 bcc_set = __update_header(msg, 'Bcc', bcc_addr, to_set.union(cc_set))
346
347 # --auto generated addresses, don't include the sender
348 from_set = __update_header(msg, 'From')
349 __update_header(msg, 'Cc', extra_cc_addr,
350 to_set.union(bcc_set).union(from_set))
351
352 def __get_signers_list(msg):
353 """Return the address list generated from signed-off-by and
354 acked-by lines in the message.
355 """
356 addr_list = []
357 tags = '%s|%s|%s|%s|%s|%s|%s' % (
358 'signed-off-by',
359 'acked-by',
360 'cc',
361 'reviewed-by',
362 'reported-by',
363 'tested-by',
364 'reported-and-tested-by')
365 regex = '^(%s):\s+(.+)$' % tags
366
367 r = re.compile(regex, re.I)
368 for line in msg.split('\n'):
369 m = r.match(line)
370 if m:
371 addr_list.append(m.expand('\g<2>'))
372
373 return addr_list
374
375 def __build_extra_headers(msg, msg_id, ref_id = None):
376 """Build extra email headers and encoding
377 """
378 del msg['Date']
379 msg['Date'] = email.Utils.formatdate(localtime = True)
380 msg['Message-ID'] = msg_id
381 if ref_id:
382 # make sure the ref id has the angle brackets
383 ref_id = '<%s>' % ref_id.strip(' \t\n<>')
384 msg['In-Reply-To'] = ref_id
385 msg['References'] = ref_id
386 msg['User-Agent'] = 'StGit/%s' % version.version
387
388 # update other address headers
389 __update_header(msg, 'Reply-To')
390 __update_header(msg, 'Mail-Reply-To')
391 __update_header(msg, 'Mail-Followup-To')
392
393
394 def __encode_message(msg):
395 # 7 or 8 bit encoding
396 charset = email.Charset.Charset('utf-8')
397 charset.body_encoding = None
398
399 # encode headers
400 for header, value in msg.items():
401 words = []
402 for word in value.split(' '):
403 try:
404 uword = unicode(word, 'utf-8')
405 except UnicodeDecodeError:
406 # maybe we should try a different encoding or report
407 # the error. At the moment, we just ignore it
408 pass
409 words.append(email.Header.Header(uword).encode())
410 new_val = ' '.join(words)
411 msg.replace_header(header, new_val)
412
413 # encode the body and set the MIME and encoding headers
414 if msg.is_multipart():
415 for p in msg.get_payload():
416 p.set_charset(charset)
417 else:
418 msg.set_charset(charset)
419
420 def __edit_message(msg):
421 fname = '.stgitmail.txt'
422
423 # create the initial file
424 f = file(fname, 'w')
425 f.write(msg)
426 f.close()
427
428 call_editor(fname)
429
430 # read the message back
431 f = file(fname)
432 msg = f.read()
433 f.close()
434
435 return msg
436
437 def __build_cover(tmpl, msg_id, options, patches):
438 """Build the cover message (series description) to be sent via SMTP
439 """
440 sender = __get_sender()
441
442 if options.version:
443 version_str = ' %s' % options.version
444 else:
445 version_str = ''
446
447 if options.prefix:
448 prefix_str = options.prefix + ' '
449 else:
450 confprefix = config.get('stgit.mail.prefix')
451 if confprefix:
452 prefix_str = confprefix + ' '
453 else:
454 prefix_str = ''
455
456 total_nr_str = str(len(patches))
457 patch_nr_str = '0'.zfill(len(total_nr_str))
458 if len(patches) > 1:
459 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
460 else:
461 number_str = ''
462
463 tmpl_dict = {'sender': sender,
464 # for backward template compatibility
465 'maintainer': sender,
466 # for backward template compatibility
467 'endofheaders': '',
468 # for backward template compatibility
469 'date': '',
470 'version': version_str,
471 'prefix': prefix_str,
472 'patchnr': patch_nr_str,
473 'totalnr': total_nr_str,
474 'number': number_str,
475 'shortlog': stack.shortlog(crt_series.get_patch(p)
476 for p in reversed(patches)),
477 'diffstat': gitlib.diffstat(git.diff(
478 rev1 = git_id(crt_series, '%s^' % patches[0]),
479 rev2 = git_id(crt_series, '%s' % patches[-1]),
480 diff_flags = options.diff_flags))}
481
482 try:
483 msg_string = tmpl % tmpl_dict
484 except KeyError, err:
485 raise CmdException, 'Unknown patch template variable: %s' \
486 % err
487 except TypeError:
488 raise CmdException, 'Only "%(name)s" variables are ' \
489 'supported in the patch template'
490
491 if options.edit_cover:
492 msg_string = __edit_message(msg_string)
493
494 # The Python email message
495 try:
496 msg = email.message_from_string(msg_string)
497 except Exception, ex:
498 raise CmdException, 'template parsing error: %s' % str(ex)
499
500 if not options.git:
501 __build_address_headers(msg, options)
502 __build_extra_headers(msg, msg_id, options.in_reply_to)
503 __encode_message(msg)
504
505 return msg
506
507 def __build_message(tmpl, msg_id, options, patch, patch_nr, total_nr, ref_id):
508 """Build the message to be sent via SMTP
509 """
510 p = crt_series.get_patch(patch)
511
512 if p.get_description():
513 descr = p.get_description().strip()
514 else:
515 # provide a place holder and force the edit message option on
516 descr = '<empty message>'
517 options.edit_patches = True
518
519 descr_lines = descr.split('\n')
520 short_descr = descr_lines[0].strip()
521 long_descr = '\n'.join(l.rstrip() for l in descr_lines[1:]).lstrip('\n')
522
523 authname = p.get_authname();
524 authemail = p.get_authemail();
525 commname = p.get_commname();
526 commemail = p.get_commemail();
527
528 sender = __get_sender()
529
530 fromauth = '%s <%s>' % (authname, authemail)
531 if fromauth != sender:
532 fromauth = 'From: %s\n\n' % fromauth
533 else:
534 fromauth = ''
535
536 if options.version:
537 version_str = ' %s' % options.version
538 else:
539 version_str = ''
540
541 if options.prefix:
542 prefix_str = options.prefix + ' '
543 else:
544 confprefix = config.get('stgit.mail.prefix')
545 if confprefix:
546 prefix_str = confprefix + ' '
547 else:
548 prefix_str = ''
549
550 total_nr_str = str(total_nr)
551 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
552 if not options.unrelated and total_nr > 1:
553 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
554 else:
555 number_str = ''
556
557 diff = git.diff(rev1 = git_id(crt_series, '%s^' % patch),
558 rev2 = git_id(crt_series, '%s' % patch),
559 diff_flags = options.diff_flags)
560 tmpl_dict = {'patch': patch,
561 'sender': sender,
562 # for backward template compatibility
563 'maintainer': sender,
564 'shortdescr': short_descr,
565 'longdescr': long_descr,
566 # for backward template compatibility
567 'endofheaders': '',
568 'diff': diff,
569 'diffstat': gitlib.diffstat(diff),
570 # for backward template compatibility
571 'date': '',
572 'version': version_str,
573 'prefix': prefix_str,
574 'patchnr': patch_nr_str,
575 'totalnr': total_nr_str,
576 'number': number_str,
577 'fromauth': fromauth,
578 'authname': authname,
579 'authemail': authemail,
580 'authdate': p.get_authdate(),
581 'commname': commname,
582 'commemail': commemail}
583 # change None to ''
584 for key in tmpl_dict:
585 if not tmpl_dict[key]:
586 tmpl_dict[key] = ''
587
588 try:
589 msg_string = tmpl % tmpl_dict
590 except KeyError, err:
591 raise CmdException, 'Unknown patch template variable: %s' \
592 % err
593 except TypeError:
594 raise CmdException, 'Only "%(name)s" variables are ' \
595 'supported in the patch template'
596
597 if options.edit_patches:
598 msg_string = __edit_message(msg_string)
599
600 # The Python email message
601 try:
602 msg = email.message_from_string(msg_string)
603 except Exception, ex:
604 raise CmdException, 'template parsing error: %s' % str(ex)
605
606 if options.auto:
607 extra_cc = __get_signers_list(descr)
608 else:
609 extra_cc = []
610
611 if not options.git:
612 __build_address_headers(msg, options, extra_cc)
613 __build_extra_headers(msg, msg_id, ref_id)
614 __encode_message(msg)
615
616 return msg
617
618 def func(parser, options, args):
619 """Send the patches by e-mail using the patchmail.tmpl file as
620 a template
621 """
622 applied = crt_series.get_applied()
623
624 if options.all:
625 patches = applied
626 elif len(args) >= 1:
627 unapplied = crt_series.get_unapplied()
628 patches = parse_patches(args, applied + unapplied, len(applied))
629 else:
630 raise CmdException, 'Incorrect options. Unknown patches to send'
631
632 # early test for sender identity
633 __get_sender()
634
635 out.start('Checking the validity of the patches')
636 for p in patches:
637 if crt_series.empty_patch(p):
638 raise CmdException, 'Cannot send empty patch "%s"' % p
639 out.done()
640
641 total_nr = len(patches)
642 if total_nr == 0:
643 raise CmdException, 'No patches to send'
644
645 if options.in_reply_to:
646 if options.no_thread or options.unrelated:
647 raise CmdException, \
648 '--in-reply-to option not allowed with --no-thread or --unrelated'
649 ref_id = options.in_reply_to
650 else:
651 ref_id = None
652
653
654 # send the cover message (if any)
655 if options.cover or options.edit_cover:
656 if options.unrelated:
657 raise CmdException, 'cover sending not allowed with --unrelated'
658
659 # find the template file
660 if options.cover:
661 tmpl = file(options.cover).read()
662 else:
663 tmpl = templates.get_template('covermail.tmpl')
664 if not tmpl:
665 raise CmdException, 'No cover message template file found'
666
667 msg_id = __send_message('cover', tmpl, options, patches)
668
669 # subsequent e-mails are seen as replies to the first one
670 if not options.no_thread:
671 ref_id = msg_id
672
673 # send the patches
674 if options.template:
675 tmpl = file(options.template).read()
676 else:
677 if options.attach:
678 tmpl = templates.get_template('mailattch.tmpl')
679 else:
680 tmpl = templates.get_template('patchmail.tmpl')
681 if not tmpl:
682 raise CmdException, 'No e-mail template file found'
683
684 for (p, n) in zip(patches, range(1, total_nr + 1)):
685 msg_id = __send_message('patch', tmpl, options, p, n, total_nr, ref_id)
686
687 # subsequent e-mails are seen as replies to the first one
688 if not options.no_thread and not options.unrelated and not ref_id:
689 ref_id = msg_id