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