chiark / gitweb /
975f8c92c9b54520ea126b8e1a541d0774d9de48
[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, smtplib, email.Utils
19 from optparse import OptionParser, make_option
20 from time import gmtime, strftime
21
22 from stgit.commands.common import *
23 from stgit.utils import *
24 from stgit import stack, git
25 from stgit.config import config
26
27
28 help = 'send a patch or series of patches by e-mail'
29 usage = """%prog [options] [<patch> [<patch2...]]
30
31 Send a patch or a range of patches (defaulting to the applied patches)
32 by e-mail using the 'smtpserver' configuration option. The From
33 address and the e-mail format are generated from the template file
34 passed as argument to '--template' (defaulting to .git/patchmail.tmpl
35 or /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 '--edit'
40 options. The first allows the user to specify a file to be used as a
41 template. The latter option will invoke the editor on the specified
42 file (defaulting to .git/covermail.tmpl or
43 /usr/share/stgit/templates/covermail.tmpl).
44
45 All the subsequent e-mails appear as replies to the first e-mail sent
46 (either the preamble or the first patch). E-mails can be seen as
47 replies to a different e-mail by using the '--refid' option.
48
49 SMTP authentication is also possible with '--smtp-user' and
50 '--smtp-password' options, also available as configuration settings:
51 'smtpuser' and 'smtppassword'.
52
53 The template e-mail headers and body must be separated by
54 '%(endofheaders)s' variable, which is replaced by StGIT with
55 additional headers and a blank line. The patch e-mail template accepts
56 the following variables:
57
58   %(patch)s        - patch name
59   %(maintainer)s   - 'authname <authemail>' as read from the config file
60   %(shortdescr)s   - the first line of the patch description
61   %(longdescr)s    - the rest of the patch description, after the first line
62   %(endofheaders)s - delimiter between e-mail headers and body
63   %(diff)s         - unified diff of the patch
64   %(diffstat)s     - diff statistics
65   %(date)s         - current date/time
66   %(version)s      - ' version' string passed on the command line (or empty)
67   %(patchnr)s      - patch number
68   %(totalnr)s      - total number of patches to be sent
69   %(number)s       - empty if only one patch is sent or ' patchnr/totalnr'
70   %(authname)s     - author's name
71   %(authemail)s    - author's email
72   %(authdate)s     - patch creation date
73   %(commname)s     - committer's name
74   %(commemail)s    - committer's e-mail
75
76 For the preamble e-mail template, only the %(maintainer)s, %(date)s,
77 %(endofheaders)s, %(version)s, %(patchnr)s, %(totalnr)s and %(number)s
78 variables are supported."""
79
80 options = [make_option('-a', '--all',
81                        help = 'e-mail all the applied patches',
82                        action = 'store_true'),
83            make_option('-r', '--range',
84                        metavar = '[PATCH1][:[PATCH2]]',
85                        help = 'e-mail patches between PATCH1 and PATCH2'),
86            make_option('--to',
87                        help = 'add TO to the To: list',
88                        action = 'append'),
89            make_option('--cc',
90                        help = 'add CC to the Cc: list',
91                        action = 'append'),
92            make_option('--bcc',
93                        help = 'add BCC to the Bcc: list',
94                        action = 'append'),
95            make_option('-v', '--version', metavar = 'VERSION',
96                        help = 'add VERSION to the [PATCH ...] prefix'),
97            make_option('-t', '--template', metavar = 'FILE',
98                        help = 'use FILE as the message template'),
99            make_option('-c', '--cover', metavar = 'FILE',
100                        help = 'send FILE as the cover message'),
101            make_option('-e', '--edit',
102                        help = 'edit the cover message before sending',
103                        action = 'store_true'),
104            make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
105                        help = 'sleep for SECONDS between e-mails sending'),
106            make_option('--refid',
107                        help = 'use REFID as the reference id'),
108            make_option('-u', '--smtp-user', metavar = 'USER',
109                        help = 'username for SMTP authentication'),
110            make_option('-p', '--smtp-password', metavar = 'PASSWORD',
111                        help = 'username for SMTP authentication'),
112            make_option('-b', '--branch',
113                        help = 'use BRANCH instead of the default one')]
114
115
116 def __get_maintainer():
117     """Return the 'authname <authemail>' string as read from the
118     configuration file
119     """
120     if config.has_option('stgit', 'authname') \
121            and config.has_option('stgit', 'authemail'):
122         return '%s <%s>' % (config.get('stgit', 'authname'),
123                             config.get('stgit', 'authemail'))
124     else:
125         return None
126
127 def __parse_addresses(addresses):
128     """Return a two elements tuple: (from, [to])
129     """
130     def __addr_list(addrs):
131         m = re.search('[^@\s<,]+@[^>\s,]+', addrs);
132         if (m == None):
133             return []
134         return [ m.group() ] + __addr_list(addrs[m.end():])
135
136     from_addr_list = []
137     to_addr_list = []
138     for line in addresses.split('\n'):
139         if re.match('from:\s+', line, re.I):
140             from_addr_list += __addr_list(line)
141         elif re.match('(to|cc|bcc):\s+', line, re.I):
142             to_addr_list += __addr_list(line)
143
144     if len(from_addr_list) == 0:
145         raise CmdException, 'No "From" address'
146     if len(to_addr_list) == 0:
147         raise CmdException, 'No "To/Cc/Bcc" addresses'
148
149     return (from_addr_list[0], to_addr_list)
150
151 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
152                    smtpuser, smtppassword):
153     """Send the message using the given SMTP server
154     """
155     try:
156         s = smtplib.SMTP(smtpserver)
157     except Exception, err:
158         raise CmdException, str(err)
159
160     s.set_debuglevel(0)
161     try:
162         if smtpuser and smtppassword:
163             s.ehlo()
164             s.login(smtpuser, smtppassword)
165
166         s.sendmail(from_addr, to_addr_list, msg)
167         # give recipients a chance of receiving patches in the correct order
168         time.sleep(sleep)
169     except Exception, err:
170         raise CmdException, str(err)
171
172     s.quit()
173
174 def __build_address_headers(options):
175     headers_end = ''
176     if options.to:
177         headers_end += 'To: '
178         for to in options.to:
179             headers_end += '%s, ' % to
180         headers_end = headers_end[:-2] + '\n'
181     if options.cc:
182         headers_end += 'Cc: '
183         for cc in options.cc:
184             headers_end += '%s, ' % cc
185         headers_end = headers_end[:-2] + '\n'
186     if options.bcc:
187         headers_end += 'Bcc: '
188         for bcc in options.bcc:
189             headers_end += '%s, ' % bcc
190         headers_end = headers_end[:-2] + '\n'
191     return headers_end
192
193 def __build_cover(tmpl, total_nr, msg_id, options):
194     """Build the cover message (series description) to be sent via SMTP
195     """
196     maintainer = __get_maintainer()
197     if not maintainer:
198         maintainer = ''
199
200     headers_end = __build_address_headers(options)
201     headers_end += 'Message-Id: %s\n' % msg_id
202     if options.refid:
203         headers_end += "In-Reply-To: %s\n" % options.refid
204         headers_end += "References: %s\n" % options.refid
205
206     if options.version:
207         version_str = ' %s' % options.version
208     else:
209         version_str = ''
210
211     total_nr_str = str(total_nr)
212     patch_nr_str = '0'.zfill(len(total_nr_str))
213     if total_nr > 1:
214         number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
215     else:
216         number_str = ''
217
218     tmpl_dict = {'maintainer':   maintainer,
219                  'endofheaders': headers_end,
220                  'date':         email.Utils.formatdate(localtime = True),
221                  'version':      version_str,
222                  'patchnr':      patch_nr_str,
223                  'totalnr':      total_nr_str,
224                  'number':       number_str}
225
226     try:
227         msg = tmpl % tmpl_dict
228     except KeyError, err:
229         raise CmdException, 'Unknown patch template variable: %s' \
230               % err
231     except TypeError:
232         raise CmdException, 'Only "%(name)s" variables are ' \
233               'supported in the patch template'
234
235     if options.edit:
236         fname = '.stgitmail.txt'
237
238         # create the initial file
239         f = file(fname, 'w+')
240         f.write(msg)
241         f.close()
242
243         # the editor
244         if config.has_option('stgit', 'editor'):
245             editor = config.get('stgit', 'editor')
246         elif 'EDITOR' in os.environ:
247             editor = os.environ['EDITOR']
248         else:
249             editor = 'vi'
250         editor += ' %s' % fname
251
252         print 'Invoking the editor: "%s"...' % editor,
253         sys.stdout.flush()
254         print 'done (exit code: %d)' % os.system(editor)
255
256         # read the message back
257         f = file(fname)
258         msg = f.read()
259         f.close()
260
261     return msg
262
263 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
264     """Build the message to be sent via SMTP
265     """
266     p = crt_series.get_patch(patch)
267
268     descr = p.get_description().strip()
269     descr_lines = descr.split('\n')
270
271     short_descr = descr_lines[0].rstrip()
272     long_descr = reduce(lambda x, y: x + '\n' + y,
273                         descr_lines[1:], '').lstrip()
274
275     maintainer = __get_maintainer()
276     if not maintainer:
277         maintainer = '%s <%s>' % (p.get_commname(), p.get_commemail())
278
279     headers_end = __build_address_headers(options)
280     headers_end += 'Message-Id: %s\n' % msg_id
281     if ref_id:
282         headers_end += "In-Reply-To: %s\n" % ref_id
283         headers_end += "References: %s\n" % ref_id
284
285     if options.version:
286         version_str = ' %s' % options.version
287     else:
288         version_str = ''
289
290     total_nr_str = str(total_nr)
291     patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
292     if total_nr > 1:
293         number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
294     else:
295         number_str = ''
296
297     tmpl_dict = {'patch':        patch,
298                  'maintainer':   maintainer,
299                  'shortdescr':   short_descr,
300                  'longdescr':    long_descr,
301                  'endofheaders': headers_end,
302                  'diff':         git.diff(rev1 = git_id('%s/bottom' % patch),
303                                           rev2 = git_id('%s/top' % patch)),
304                  'diffstat':     git.diffstat(rev1 = git_id('%s/bottom'%patch),
305                                               rev2 = git_id('%s/top' % patch)),
306                  'date':         email.Utils.formatdate(localtime = True),
307                  'version':      version_str,
308                  'patchnr':      patch_nr_str,
309                  'totalnr':      total_nr_str,
310                  'number':       number_str,
311                  'authname':     p.get_authname(),
312                  'authemail':    p.get_authemail(),
313                  'authdate':     p.get_authdate(),
314                  'commname':     p.get_commname(),
315                  'commemail':    p.get_commemail()}
316     for key in tmpl_dict:
317         if not tmpl_dict[key]:
318             tmpl_dict[key] = ''
319
320     try:
321         msg = tmpl % tmpl_dict
322     except KeyError, err:
323         raise CmdException, 'Unknown patch template variable: %s' \
324               % err
325     except TypeError:
326         raise CmdException, 'Only "%(name)s" variables are ' \
327               'supported in the patch template'
328
329     return msg
330
331 def func(parser, options, args):
332     """Send the patches by e-mail using the patchmail.tmpl file as
333     a template
334     """
335     if not config.has_option('stgit', 'smtpserver'):
336         raise CmdException, 'smtpserver not defined'
337     smtpserver = config.get('stgit', 'smtpserver')
338
339     smtpuser = None
340     smtppassword = None
341     if config.has_option('stgit', 'smtpuser'):
342         smtpuser = config.get('stgit', 'smtpuser')
343     if config.has_option('stgit', 'smtppassword'):
344         smtppassword = config.get('stgit', 'smtppassword')
345
346     applied = crt_series.get_applied()
347     unapplied = crt_series.get_unapplied()
348
349     if len(args) >= 1:
350         for patch in args:
351             if patch in unapplied:
352                 raise CmdException, 'Patch "%s" not applied' % patch
353             if not patch in applied:
354                 raise CmdException, 'Patch "%s" does not exist' % patch
355         patches = args
356     elif options.all:
357         patches = applied
358     elif options.range:
359         boundaries = options.range.split(':')
360         if len(boundaries) == 1:
361             start = boundaries[0]
362             stop = boundaries[0]
363         elif len(boundaries) == 2:
364             if boundaries[0] == '':
365                 start = applied[0]
366             else:
367                 start = boundaries[0]
368             if boundaries[1] == '':
369                 stop = applied[-1]
370             else:
371                 stop = boundaries[1]
372         else:
373             raise CmdException, 'incorrect parameters to "--range"'
374
375         if start in applied:
376             start_idx = applied.index(start)
377         else:
378             if start in unapplied:
379                 raise CmdException, 'Patch "%s" not applied' % start
380             else:
381                 raise CmdException, 'Patch "%s" does not exist' % start
382         if stop in applied:
383             stop_idx = applied.index(stop) + 1
384         else:
385             if stop in unapplied:
386                 raise CmdException, 'Patch "%s" not applied' % stop
387             else:
388                 raise CmdException, 'Patch "%s" does not exist' % stop
389
390         if start_idx >= stop_idx:
391             raise CmdException, 'Incorrect patch range order'
392
393         patches = applied[start_idx:stop_idx]
394     else:
395         raise CmdException, 'Incorrect options. Unknown patches to send'
396
397     if options.smtp_password:
398         smtppassword = options.smtp_password
399
400     if options.smtp_user:
401         smtpuser = options.smtp_user
402
403     if (smtppassword and not smtpuser):
404         raise CmdException, 'SMTP password supplied, username needed'
405     if (smtpuser and not smtppassword):
406         raise CmdException, 'SMTP username supplied, password needed'
407
408     total_nr = len(patches)
409     if total_nr == 0:
410         raise CmdException, 'No patches to send'
411
412     ref_id = options.refid
413
414     if options.sleep != None:
415         sleep = options.sleep
416     else:
417         sleep = 2
418
419     # send the cover message (if any)
420     if options.cover or options.edit:
421         # find the template file
422         if options.cover:
423             tfile_list = [options.cover]
424         else:
425             tfile_list = [os.path.join(git.get_base_dir(), 'covermail.tmpl'),
426                           os.path.join(sys.prefix,
427                                        'share/stgit/templates/covermail.tmpl')]
428
429         tmpl = None
430         for tfile in tfile_list:
431             if os.path.isfile(tfile):
432                 tmpl = file(tfile).read()
433                 break
434         if not tmpl:
435             raise CmdException, 'No cover message template file found'
436
437         msg_id = email.Utils.make_msgid('stgit')
438         msg = __build_cover(tmpl, total_nr, msg_id, options)
439         from_addr, to_addr_list = __parse_addresses(msg)
440
441         # subsequent e-mails are seen as replies to the first one
442         ref_id = msg_id
443
444         print 'Sending the cover message...',
445         sys.stdout.flush()
446
447         __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
448                        smtpuser, smtppassword)
449
450         print 'done'
451
452     # send the patches
453     if options.template:
454         tfile_list = [options.template]
455     else:
456         tfile_list = [os.path.join(git.get_base_dir(), 'patchmail.tmpl'),
457                       os.path.join(sys.prefix,
458                                    'share/stgit/templates/patchmail.tmpl')]
459     tmpl = None
460     for tfile in tfile_list:
461         if os.path.isfile(tfile):
462             tmpl = file(tfile).read()
463             break
464     if not tmpl:
465         raise CmdException, 'No e-mail template file found'
466
467     for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
468         msg_id = email.Utils.make_msgid('stgit')
469         msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
470                               options)
471         from_addr, to_addr_list = __parse_addresses(msg)
472
473         # subsequent e-mails are seen as replies to the first one
474         if not ref_id:
475             ref_id = msg_id
476
477         print 'Sending patch "%s"...' % p,
478         sys.stdout.flush()
479
480         __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
481                        smtpuser, smtppassword)
482
483         print 'done'