chiark / gitweb /
2b28564f0469f3dbfe4790fd636581d5bf200f8d
[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, email.Utils
19 from optparse import OptionParser, make_option
20
21 from stgit.commands.common import *
22 from stgit.utils import *
23 from stgit import stack, git, version, templates
24 from stgit.config import config
25
26
27 help = 'send a patch or series of patches by e-mail'
28 usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
29
30 Send a patch or a range of patches by e-mail using the 'smtpserver'
31 configuration option. The From address and the e-mail format are
32 generated from the template file passed as argument to '--template'
33 (defaulting to '.git/patchmail.tmpl' or
34 '~/.stgit/templates/patchmail.tmpl' or or
35 '/usr/share/stgit/templates/patchmail.tmpl'). The To/Cc/Bcc addresses
36 can either be added to the template file or passed via the
37 corresponding command line options.
38
39 A preamble e-mail can be sent using the '--cover' and/or
40 '--edit-cover' options. The first allows the user to specify a file to
41 be used as a template. The latter option will invoke the editor on the
42 specified file (defaulting to '.git/covermail.tmpl' or
43 '~/.stgit/templates/covermail.tmpl' or
44 '/usr/share/stgit/templates/covermail.tmpl').
45
46 All the subsequent e-mails appear as replies to the first e-mail sent
47 (either the preamble or the first patch). E-mails can be seen as
48 replies to a different e-mail by using the '--refid' option.
49
50 SMTP authentication is also possible with '--smtp-user' and
51 '--smtp-password' options, also available as configuration settings:
52 'smtpuser' and 'smtppassword'.
53
54 The template e-mail headers and body must be separated by
55 '%(endofheaders)s' variable, which is replaced by StGIT with
56 additional headers and a blank line. The patch e-mail template accepts
57 the following variables:
58
59   %(patch)s        - patch name
60   %(maintainer)s   - 'authname <authemail>' as read from the config file
61   %(shortdescr)s   - the first line of the patch description
62   %(longdescr)s    - the rest of the patch description, after the first line
63   %(endofheaders)s - delimiter between e-mail headers and body
64   %(diff)s         - unified diff of the patch
65   %(diffstat)s     - diff statistics
66   %(date)s         - current date/time
67   %(version)s      - ' version' string passed on the command line (or empty)
68   %(prefix)s       - 'prefix ' string passed on the command line
69   %(patchnr)s      - patch number
70   %(totalnr)s      - total number of patches to be sent
71   %(number)s       - empty if only one patch is sent or ' patchnr/totalnr'
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 %(maintainer)s, %(date)s,
79 %(endofheaders)s, %(version)s, %(patchnr)s, %(totalnr)s and %(number)s
80 variables are supported."""
81
82 options = [make_option('-a', '--all',
83                        help = 'e-mail all the applied patches',
84                        action = 'store_true'),
85            make_option('--to',
86                        help = 'add TO to the To: list',
87                        action = 'append'),
88            make_option('--cc',
89                        help = 'add CC to the Cc: list',
90                        action = 'append'),
91            make_option('--bcc',
92                        help = 'add BCC to the Bcc: list',
93                        action = 'append'),
94            make_option('--auto',
95                        help = 'automatically cc the patch signers',
96                        action = 'store_true'),
97            make_option('--noreply',
98                        help = 'do not send subsequent messages as replies',
99                        action = 'store_true'),
100            make_option('-v', '--version', metavar = 'VERSION',
101                        help = 'add VERSION to the [PATCH ...] prefix'),
102            make_option('--prefix', metavar = 'PREFIX',
103                        help = 'add PREFIX to the [... PATCH ...] prefix'),
104            make_option('-t', '--template', metavar = 'FILE',
105                        help = 'use FILE as the message template'),
106            make_option('-c', '--cover', metavar = 'FILE',
107                        help = 'send FILE as the cover message'),
108            make_option('-e', '--edit-cover',
109                        help = 'edit the cover message before sending',
110                        action = 'store_true'),
111            make_option('-E', '--edit-patches',
112                        help = 'edit each patch before sending',
113                        action = 'store_true'),
114            make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
115                        help = 'sleep for SECONDS between e-mails sending'),
116            make_option('--refid',
117                        help = 'use REFID as the reference id'),
118            make_option('-u', '--smtp-user', metavar = 'USER',
119                        help = 'username for SMTP authentication'),
120            make_option('-p', '--smtp-password', metavar = 'PASSWORD',
121                        help = 'username for SMTP authentication'),
122            make_option('-b', '--branch',
123                        help = 'use BRANCH instead of the default one'),
124            make_option('-m', '--mbox',
125                        help = 'generate an mbox file instead of sending',
126                        action = 'store_true')]
127
128
129 def __get_maintainer():
130     """Return the 'authname <authemail>' string as read from the
131     configuration file
132     """
133     if config.has_option('stgit', 'authname') \
134            and config.has_option('stgit', 'authemail'):
135         return '%s <%s>' % (config.get('stgit', 'authname'),
136                             config.get('stgit', 'authemail'))
137     else:
138         return None
139
140 def __parse_addresses(addresses):
141     """Return a two elements tuple: (from, [to])
142     """
143     def __addr_list(addrs):
144         m = re.search('[^@\s<,]+@[^>\s,]+', addrs);
145         if (m == None):
146             return []
147         return [ m.group() ] + __addr_list(addrs[m.end():])
148
149     from_addr_list = []
150     to_addr_list = []
151     for line in addresses.split('\n'):
152         if re.match('from:\s+', line, re.I):
153             from_addr_list += __addr_list(line)
154         elif re.match('(to|cc|bcc):\s+', line, re.I):
155             to_addr_list += __addr_list(line)
156
157     if len(from_addr_list) == 0:
158         raise CmdException, 'No "From" address'
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 __write_mbox(from_addr, msg):
188     """Write an mbox like file to the standard output
189     """
190     r = re.compile('^From ', re.M)
191     msg = r.sub('>\g<0>', msg)
192
193     print 'From %s %s' % (from_addr, datetime.datetime.today().ctime())
194     print msg
195     print
196
197 def __build_address_headers(tmpl, options, extra_cc = []):
198     """Build the address headers and check existing headers in the
199     template.
200     """
201     def csv(lst):
202         s = ''
203         for i in lst:
204             if not i:
205                 continue
206             if s:
207                 s += ', ' + i
208             else:
209                 s = i
210         return s
211
212     def replace_header(header, addr, tmpl):
213         r = re.compile('^' + header + ':\s+.+$', re.I | re.M)
214         if r.search(tmpl):
215             tmpl = r.sub('\g<0>, ' + addr, tmpl, 1)
216             h = ''
217         else:
218             h = header + ': ' + addr
219
220         return tmpl, h
221
222     headers = ''
223     to_addr = ''
224     cc_addr = ''
225     bcc_addr = ''
226
227     if config.has_option('stgit', 'autobcc'):
228         autobcc = config.get('stgit', 'autobcc')
229     else:
230         autobcc = ''
231
232     if options.to:
233         to_addr = csv(options.to)
234     if options.cc:
235         cc_addr = csv(options.cc + extra_cc)
236     elif extra_cc:
237         cc_addr = csv(extra_cc)
238     if options.bcc:
239         bcc_addr = csv(options.bcc + [autobcc])
240     elif autobcc:
241         bcc_addr = autobcc
242
243     # replace existing headers
244     if to_addr:
245         tmpl, h = replace_header('To', to_addr, tmpl)
246         if h:
247             headers += h + '\n'
248     if cc_addr:
249         tmpl, h = replace_header('Cc', cc_addr, tmpl)
250         if h:
251             headers += h + '\n'
252     if bcc_addr:
253         tmpl, h = replace_header('Bcc', bcc_addr, tmpl)
254         if h:
255             headers += h + '\n'
256
257     return tmpl, headers
258
259 def __get_signers_list(msg):
260     """Return the address list generated from signed-off-by and
261     acked-by lines in the message.
262     """
263     addr_list = []
264
265     r = re.compile('^(signed-off-by|acked-by):\s+(.+)$', re.I)
266     for line in msg.split('\n'):
267         m = r.match(line)
268         if m:
269             addr_list.append(m.expand('\g<2>'))
270
271     return addr_list
272
273 def __build_extra_headers():
274     """Build extra headers like content-type etc.
275     """
276     headers  = 'Content-Type: text/plain; charset=utf-8; format=fixed\n'
277     headers += 'Content-Transfer-Encoding: 8bit\n'
278     headers += 'User-Agent: StGIT/%s\n' % version.version
279
280     return headers
281
282 def edit_message(msg):
283     fname = '.stgitmail.txt'
284
285     # create the initial file
286     f = file(fname, 'w')
287     f.write(msg)
288     f.close()
289
290     # the editor
291     if config.has_option('stgit', 'editor'):
292         editor = config.get('stgit', 'editor')
293     elif 'EDITOR' in os.environ:
294         editor = os.environ['EDITOR']
295     else:
296         editor = 'vi'
297     editor += ' %s' % fname
298
299     print 'Invoking the editor: "%s"...' % editor,
300     sys.stdout.flush()
301     print 'done (exit code: %d)' % os.system(editor)
302
303     # read the message back
304     f = file(fname)
305     msg = f.read()
306     f.close()
307
308     return msg
309
310 def __build_cover(tmpl, total_nr, msg_id, options):
311     """Build the cover message (series description) to be sent via SMTP
312     """
313     maintainer = __get_maintainer()
314     if not maintainer:
315         maintainer = ''
316
317     tmpl, headers_end = __build_address_headers(tmpl, options)
318     headers_end += 'Message-Id: %s\n' % msg_id
319     if options.refid:
320         headers_end += "In-Reply-To: %s\n" % options.refid
321         headers_end += "References: %s\n" % options.refid
322     headers_end += __build_extra_headers()
323
324     if options.version:
325         version_str = ' %s' % options.version
326     else:
327         version_str = ''
328
329     if options.prefix:
330         prefix_str = options.prefix + ' '
331     else:
332         prefix_str = ''
333         
334     total_nr_str = str(total_nr)
335     patch_nr_str = '0'.zfill(len(total_nr_str))
336     if total_nr > 1:
337         number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
338     else:
339         number_str = ''
340
341     tmpl_dict = {'maintainer':   maintainer,
342                  'endofheaders': headers_end,
343                  'date':         email.Utils.formatdate(localtime = True),
344                  'version':      version_str,
345                  'prefix':       prefix_str,
346                  'patchnr':      patch_nr_str,
347                  'totalnr':      total_nr_str,
348                  'number':       number_str}
349
350     try:
351         msg = tmpl % tmpl_dict
352     except KeyError, err:
353         raise CmdException, 'Unknown patch template variable: %s' \
354               % err
355     except TypeError:
356         raise CmdException, 'Only "%(name)s" variables are ' \
357               'supported in the patch template'
358
359     if options.edit_cover:
360         msg = edit_message(msg)
361
362     return msg.strip('\n')
363
364 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
365     """Build the message to be sent via SMTP
366     """
367     p = crt_series.get_patch(patch)
368
369     descr = p.get_description().strip()
370     descr_lines = descr.split('\n')
371
372     short_descr = descr_lines[0].rstrip()
373     long_descr = reduce(lambda x, y: x + '\n' + y,
374                         descr_lines[1:], '').lstrip()
375
376     maintainer = __get_maintainer()
377     if not maintainer:
378         maintainer = '%s <%s>' % (p.get_commname(), p.get_commemail())
379
380     if options.auto:
381         extra_cc = __get_signers_list(descr)
382     else:
383         extra_cc = []
384
385     tmpl, headers_end = __build_address_headers(tmpl, options, extra_cc)
386     headers_end += 'Message-Id: %s\n' % msg_id
387     if ref_id:
388         headers_end += "In-Reply-To: %s\n" % ref_id
389         headers_end += "References: %s\n" % ref_id
390     headers_end += __build_extra_headers()
391
392     if options.version:
393         version_str = ' %s' % options.version
394     else:
395         version_str = ''
396
397     if options.prefix:
398         prefix_str = options.prefix + ' '
399     else:
400         prefix_str = ''
401         
402     total_nr_str = str(total_nr)
403     patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
404     if total_nr > 1:
405         number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
406     else:
407         number_str = ''
408
409     tmpl_dict = {'patch':        patch,
410                  'maintainer':   maintainer,
411                  'shortdescr':   short_descr,
412                  'longdescr':    long_descr,
413                  'endofheaders': headers_end,
414                  'diff':         git.diff(rev1 = git_id('%s//bottom' % patch),
415                                           rev2 = git_id('%s//top' % patch)),
416                  'diffstat':     git.diffstat(rev1 = git_id('%s//bottom'%patch),
417                                               rev2 = git_id('%s//top' % patch)),
418                  'date':         email.Utils.formatdate(localtime = True),
419                  'version':      version_str,
420                  'prefix':       prefix_str,
421                  'patchnr':      patch_nr_str,
422                  'totalnr':      total_nr_str,
423                  'number':       number_str,
424                  'authname':     p.get_authname(),
425                  'authemail':    p.get_authemail(),
426                  'authdate':     p.get_authdate(),
427                  'commname':     p.get_commname(),
428                  'commemail':    p.get_commemail()}
429     for key in tmpl_dict:
430         if not tmpl_dict[key]:
431             tmpl_dict[key] = ''
432
433     try:
434         msg = tmpl % tmpl_dict
435     except KeyError, err:
436         raise CmdException, 'Unknown patch template variable: %s' \
437               % err
438     except TypeError:
439         raise CmdException, 'Only "%(name)s" variables are ' \
440               'supported in the patch template'
441
442     if options.edit_patches:
443         msg = edit_message(msg)
444
445     return msg.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             __write_mbox(from_addr, msg)
514         else:
515             print 'Sending the cover message...',
516             sys.stdout.flush()
517             __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
518                            smtpuser, smtppassword)
519             print 'done'
520
521     # send the patches
522     if options.template:
523         tmpl = file(options.template).read()
524     else:
525         tmpl = templates.get_template('patchmail.tmpl')
526         if not tmpl:
527             raise CmdException, 'No e-mail template file found'
528
529     for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
530         msg_id = email.Utils.make_msgid('stgit')
531         msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
532                               options)
533         from_addr, to_addr_list = __parse_addresses(msg)
534
535         # subsequent e-mails are seen as replies to the first one
536         if not options.noreply and not ref_id:
537             ref_id = msg_id
538
539         if options.mbox:
540             __write_mbox(from_addr, msg)
541         else:
542             print 'Sending patch "%s"...' % p,
543             sys.stdout.flush()
544             __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
545                            smtpuser, smtppassword)
546             print 'done'