5d1dc9b333b56ae32bc105943ed90b72a2118d00
[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 '--refid' 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('--noreply', 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('--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 ] + argparse.diff_opts_option()
145
146 directory = DirectoryHasRepository(log = False)
147
148 def __get_sender():
149 """Return the 'authname <authemail>' string as read from the
150 configuration file
151 """
152 sender=config.get('stgit.sender')
153 if not sender:
154 try:
155 sender = str(git.user())
156 except git.GitException:
157 try:
158 sender = str(git.author())
159 except git.GitException:
160 pass
161 if not sender:
162 raise CmdException, ('Unknown sender name and e-mail; you should'
163 ' for example set git config user.name and'
164 ' user.email')
165 sender = email.Utils.parseaddr(sender)
166
167 return email.Utils.formataddr(address_or_alias(sender))
168
169 def __addr_list(msg, header):
170 return [addr for name, addr in
171 email.Utils.getaddresses(msg.get_all(header, []))]
172
173 def __parse_addresses(msg):
174 """Return a two elements tuple: (from, [to])
175 """
176 from_addr_list = __addr_list(msg, 'From')
177 if len(from_addr_list) == 0:
178 raise CmdException, 'No "From" address'
179
180 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
181 + __addr_list(msg, 'Bcc')
182 if len(to_addr_list) == 0:
183 raise CmdException, 'No "To/Cc/Bcc" addresses'
184
185 return (from_addr_list[0], set(to_addr_list))
186
187 def __send_message_sendmail(sendmail, msg):
188 """Send the message using the sendmail command.
189 """
190 cmd = sendmail.split()
191 Run(*cmd).raw_input(msg).discard_output()
192
193 def __send_message_smtp(smtpserver, from_addr, to_addr_list, msg, options):
194 """Send the message using the given SMTP server
195 """
196 smtppassword = options.smtp_password or config.get('stgit.smtppassword')
197 smtpuser = options.smtp_user or config.get('stgit.smtpuser')
198 smtpusetls = options.smtp_tls or config.get('stgit.smtptls') == 'yes'
199
200 if (smtppassword and not smtpuser):
201 raise CmdException('SMTP password supplied, username needed')
202 if (smtpusetls and not smtpuser):
203 raise CmdException('SMTP over TLS requested, username needed')
204 if (smtpuser and not smtppassword):
205 smtppassword = getpass.getpass("Please enter SMTP password: ")
206
207 try:
208 s = smtplib.SMTP(smtpserver)
209 except Exception, err:
210 raise CmdException, str(err)
211
212 s.set_debuglevel(0)
213 try:
214 if smtpuser and smtppassword:
215 s.ehlo()
216 if smtpusetls:
217 if not hasattr(socket, 'ssl'):
218 raise CmdException, "cannot use TLS - no SSL support in Python"
219 s.starttls()
220 s.ehlo()
221 s.login(smtpuser, smtppassword)
222
223 result = s.sendmail(from_addr, to_addr_list, msg)
224 if len(result):
225 print "mail server refused delivery for the following recipients: %s" % result
226 except Exception, err:
227 raise CmdException, str(err)
228
229 s.quit()
230
231 def __send_message(type, tmpl, options, *args):
232 """Message sending dispatcher.
233 """
234 (build, outstr) = {'cover': (__build_cover, 'the cover message'),
235 'patch': (__build_message, 'patch "%s"' % args[0])}[type]
236 if type == 'patch':
237 (patch_nr, total_nr) = (args[1], args[2])
238
239 msg_id = email.Utils.make_msgid('stgit')
240 msg = build(tmpl, msg_id, options, *args)
241
242 from_addr, to_addrs = __parse_addresses(msg)
243 msg_str = msg.as_string(options.mbox)
244 if options.mbox:
245 out.stdout_raw(msg_str + '\n')
246 return msg_id
247
248 out.start('Sending ' + outstr)
249
250 smtpserver = options.smtp_server or config.get('stgit.smtpserver')
251 if smtpserver.startswith('/'):
252 # Use the sendmail tool
253 __send_message_sendmail(smtpserver, msg_str)
254 else:
255 # Use the SMTP server (we have host and port information)
256 __send_message_smtp(smtpserver, from_addr, to_addrs, msg_str, options)
257
258 # give recipients a chance of receiving related patches in correct order
259 if type == 'cover' or (type == 'patch' and patch_nr < total_nr):
260 sleep = options.sleep or config.getint('stgit.smtpdelay')
261 time.sleep(sleep)
262 out.done()
263 return msg_id
264
265 def __build_address_headers(msg, options, extra_cc = []):
266 """Build the address headers and check existing headers in the
267 template.
268 """
269 def __addr_pairs(msg, header, extra):
270 pairs = email.Utils.getaddresses(msg.get_all(header, []) + extra)
271 # remove pairs without an address and resolve the aliases
272 return [address_or_alias(p) for p in pairs if p[1]]
273
274 def __update_header(header, addr = '', ignore = ()):
275 addr_pairs = __addr_pairs(msg, header, [addr])
276 del msg[header]
277 # remove the duplicates and filter the addresses
278 addr_dict = dict((addr, email.Utils.formataddr((name, addr)))
279 for name, addr in addr_pairs if addr not in ignore)
280 if addr_dict:
281 msg[header] = ', '.join(addr_dict.itervalues())
282 return set(addr_dict.iterkeys())
283
284 to_addr = ''
285 cc_addr = ''
286 extra_cc_addr = ''
287 bcc_addr = ''
288
289 autobcc = config.get('stgit.autobcc') or ''
290
291 if options.to:
292 to_addr = ', '.join(options.to)
293 if options.cc:
294 cc_addr = ', '.join(options.cc)
295 if extra_cc:
296 extra_cc_addr = ', '.join(extra_cc)
297 if options.bcc:
298 bcc_addr = ', '.join(options.bcc + [autobcc])
299 elif autobcc:
300 bcc_addr = autobcc
301
302 # if an address is on a header, ignore it from the rest
303 to_set = __update_header('To', to_addr)
304 cc_set = __update_header('Cc', cc_addr, to_set)
305 bcc_set = __update_header('Bcc', bcc_addr, to_set.union(cc_set))
306
307 # --auto generated addresses, don't include the sender
308 from_set = __update_header('From')
309 __update_header('Cc', extra_cc_addr, to_set.union(bcc_set).union(from_set))
310
311 # update other address headers
312 __update_header('Reply-To')
313 __update_header('Mail-Reply-To')
314 __update_header('Mail-Followup-To')
315
316 def __get_signers_list(msg):
317 """Return the address list generated from signed-off-by and
318 acked-by lines in the message.
319 """
320 addr_list = []
321 tags = '%s|%s|%s|%s|%s|%s|%s' % (
322 'signed-off-by',
323 'acked-by',
324 'cc',
325 'reviewed-by',
326 'reported-by',
327 'tested-by',
328 'reported-and-tested-by')
329 regex = '^(%s):\s+(.+)$' % tags
330
331 r = re.compile(regex, re.I)
332 for line in msg.split('\n'):
333 m = r.match(line)
334 if m:
335 addr_list.append(m.expand('\g<2>'))
336
337 return addr_list
338
339 def __build_extra_headers(msg, msg_id, ref_id = None):
340 """Build extra email headers and encoding
341 """
342 del msg['Date']
343 msg['Date'] = email.Utils.formatdate(localtime = True)
344 msg['Message-ID'] = msg_id
345 if ref_id:
346 # make sure the ref id has the angle brackets
347 ref_id = '<%s>' % ref_id.strip(' \t\n<>')
348 msg['In-Reply-To'] = ref_id
349 msg['References'] = ref_id
350 msg['User-Agent'] = 'StGit/%s' % version.version
351
352 def __encode_message(msg):
353 # 7 or 8 bit encoding
354 charset = email.Charset.Charset('utf-8')
355 charset.body_encoding = None
356
357 # encode headers
358 for header, value in msg.items():
359 words = []
360 for word in value.split(' '):
361 try:
362 uword = unicode(word, 'utf-8')
363 except UnicodeDecodeError:
364 # maybe we should try a different encoding or report
365 # the error. At the moment, we just ignore it
366 pass
367 words.append(email.Header.Header(uword).encode())
368 new_val = ' '.join(words)
369 msg.replace_header(header, new_val)
370
371 # encode the body and set the MIME and encoding headers
372 if msg.is_multipart():
373 for p in msg.get_payload():
374 p.set_charset(charset)
375 else:
376 msg.set_charset(charset)
377
378 def __edit_message(msg):
379 fname = '.stgitmail.txt'
380
381 # create the initial file
382 f = file(fname, 'w')
383 f.write(msg)
384 f.close()
385
386 call_editor(fname)
387
388 # read the message back
389 f = file(fname)
390 msg = f.read()
391 f.close()
392
393 return msg
394
395 def __build_cover(tmpl, msg_id, options, patches):
396 """Build the cover message (series description) to be sent via SMTP
397 """
398 sender = __get_sender()
399
400 if options.version:
401 version_str = ' %s' % options.version
402 else:
403 version_str = ''
404
405 if options.prefix:
406 prefix_str = options.prefix + ' '
407 else:
408 confprefix = config.get('stgit.mail.prefix')
409 if confprefix:
410 prefix_str = confprefix + ' '
411 else:
412 prefix_str = ''
413
414 total_nr_str = str(len(patches))
415 patch_nr_str = '0'.zfill(len(total_nr_str))
416 if len(patches) > 1:
417 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
418 else:
419 number_str = ''
420
421 tmpl_dict = {'sender': sender,
422 # for backward template compatibility
423 'maintainer': sender,
424 # for backward template compatibility
425 'endofheaders': '',
426 # for backward template compatibility
427 'date': '',
428 'version': version_str,
429 'prefix': prefix_str,
430 'patchnr': patch_nr_str,
431 'totalnr': total_nr_str,
432 'number': number_str,
433 'shortlog': stack.shortlog(crt_series.get_patch(p)
434 for p in reversed(patches)),
435 'diffstat': gitlib.diffstat(git.diff(
436 rev1 = git_id(crt_series, '%s^' % patches[0]),
437 rev2 = git_id(crt_series, '%s' % patches[-1]),
438 diff_flags = options.diff_flags))}
439
440 try:
441 msg_string = tmpl % tmpl_dict
442 except KeyError, err:
443 raise CmdException, 'Unknown patch template variable: %s' \
444 % err
445 except TypeError:
446 raise CmdException, 'Only "%(name)s" variables are ' \
447 'supported in the patch template'
448
449 if options.edit_cover:
450 msg_string = __edit_message(msg_string)
451
452 # The Python email message
453 try:
454 msg = email.message_from_string(msg_string)
455 except Exception, ex:
456 raise CmdException, 'template parsing error: %s' % str(ex)
457
458 __build_address_headers(msg, options)
459 __build_extra_headers(msg, msg_id, options.refid)
460 __encode_message(msg)
461
462 return msg
463
464 def __build_message(tmpl, msg_id, options, patch, patch_nr, total_nr, ref_id):
465 """Build the message to be sent via SMTP
466 """
467 p = crt_series.get_patch(patch)
468
469 if p.get_description():
470 descr = p.get_description().strip()
471 else:
472 # provide a place holder and force the edit message option on
473 descr = '<empty message>'
474 options.edit_patches = True
475
476 descr_lines = descr.split('\n')
477 short_descr = descr_lines[0].strip()
478 long_descr = '\n'.join(l.rstrip() for l in descr_lines[1:]).lstrip('\n')
479
480 authname = p.get_authname();
481 authemail = p.get_authemail();
482 commname = p.get_commname();
483 commemail = p.get_commemail();
484
485 sender = __get_sender()
486
487 fromauth = '%s <%s>' % (authname, authemail)
488 if fromauth != sender:
489 fromauth = 'From: %s\n\n' % fromauth
490 else:
491 fromauth = ''
492
493 if options.version:
494 version_str = ' %s' % options.version
495 else:
496 version_str = ''
497
498 if options.prefix:
499 prefix_str = options.prefix + ' '
500 else:
501 confprefix = config.get('stgit.mail.prefix')
502 if confprefix:
503 prefix_str = confprefix + ' '
504 else:
505 prefix_str = ''
506
507 total_nr_str = str(total_nr)
508 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
509 if not options.unrelated and total_nr > 1:
510 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
511 else:
512 number_str = ''
513
514 diff = git.diff(rev1 = git_id(crt_series, '%s^' % patch),
515 rev2 = git_id(crt_series, '%s' % patch),
516 diff_flags = options.diff_flags)
517 tmpl_dict = {'patch': patch,
518 'sender': sender,
519 # for backward template compatibility
520 'maintainer': sender,
521 'shortdescr': short_descr,
522 'longdescr': long_descr,
523 # for backward template compatibility
524 'endofheaders': '',
525 'diff': diff,
526 'diffstat': gitlib.diffstat(diff),
527 # for backward template compatibility
528 'date': '',
529 'version': version_str,
530 'prefix': prefix_str,
531 'patchnr': patch_nr_str,
532 'totalnr': total_nr_str,
533 'number': number_str,
534 'fromauth': fromauth,
535 'authname': authname,
536 'authemail': authemail,
537 'authdate': p.get_authdate(),
538 'commname': commname,
539 'commemail': commemail}
540 # change None to ''
541 for key in tmpl_dict:
542 if not tmpl_dict[key]:
543 tmpl_dict[key] = ''
544
545 try:
546 msg_string = tmpl % tmpl_dict
547 except KeyError, err:
548 raise CmdException, 'Unknown patch template variable: %s' \
549 % err
550 except TypeError:
551 raise CmdException, 'Only "%(name)s" variables are ' \
552 'supported in the patch template'
553
554 if options.edit_patches:
555 msg_string = __edit_message(msg_string)
556
557 # The Python email message
558 try:
559 msg = email.message_from_string(msg_string)
560 except Exception, ex:
561 raise CmdException, 'template parsing error: %s' % str(ex)
562
563 if options.auto:
564 extra_cc = __get_signers_list(descr)
565 else:
566 extra_cc = []
567
568 __build_address_headers(msg, options, extra_cc)
569 __build_extra_headers(msg, msg_id, ref_id)
570 __encode_message(msg)
571
572 return msg
573
574 def func(parser, options, args):
575 """Send the patches by e-mail using the patchmail.tmpl file as
576 a template
577 """
578 applied = crt_series.get_applied()
579
580 if options.all:
581 patches = applied
582 elif len(args) >= 1:
583 unapplied = crt_series.get_unapplied()
584 patches = parse_patches(args, applied + unapplied, len(applied))
585 else:
586 raise CmdException, 'Incorrect options. Unknown patches to send'
587
588 # early test for sender identity
589 __get_sender()
590
591 out.start('Checking the validity of the patches')
592 for p in patches:
593 if crt_series.empty_patch(p):
594 raise CmdException, 'Cannot send empty patch "%s"' % p
595 out.done()
596
597 total_nr = len(patches)
598 if total_nr == 0:
599 raise CmdException, 'No patches to send'
600
601 if options.refid:
602 if options.noreply or options.unrelated:
603 raise CmdException, \
604 '--refid option not allowed with --noreply or --unrelated'
605 ref_id = options.refid
606 else:
607 ref_id = None
608
609
610 # send the cover message (if any)
611 if options.cover or options.edit_cover:
612 if options.unrelated:
613 raise CmdException, 'cover sending not allowed with --unrelated'
614
615 # find the template file
616 if options.cover:
617 tmpl = file(options.cover).read()
618 else:
619 tmpl = templates.get_template('covermail.tmpl')
620 if not tmpl:
621 raise CmdException, 'No cover message template file found'
622
623 msg_id = __send_message('cover', tmpl, options, patches)
624
625 # subsequent e-mails are seen as replies to the first one
626 if not options.noreply:
627 ref_id = msg_id
628
629 # send the patches
630 if options.template:
631 tmpl = file(options.template).read()
632 else:
633 if options.attach:
634 tmpl = templates.get_template('mailattch.tmpl')
635 else:
636 tmpl = templates.get_template('patchmail.tmpl')
637 if not tmpl:
638 raise CmdException, 'No e-mail template file found'
639
640 for (p, n) in zip(patches, range(1, total_nr + 1)):
641 msg_id = __send_message('patch', tmpl, options, p, n, total_nr, ref_id)
642
643 # subsequent e-mails are seen as replies to the first one
644 if not options.noreply and not options.unrelated and not ref_id:
645 ref_id = msg_id