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