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