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