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