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