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