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