chiark / gitweb /
d758b9c810bad171a90faad49ad958ffbc3b7792
[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>]
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 '--first' option. All the
40 subsequent e-mails appear as replies to the first e-mail sent (either
41 the preamble or the first patch). E-mails can be seen as replies to a
42 different e-mail by using the '--refid' option.
43
44 SMTP authentication is also possible with '--smtp-user' and
45 '--smtp-password' options, also available as configuration settings:
46 'smtpuser' and 'smtppassword'.
47
48 The template e-mail headers and body must be separated by
49 '%(endofheaders)s' variable, which is replaced by StGIT with
50 additional headers and a blank line. The patch e-mail template accepts
51 the following variables:
52
53   %(patch)s        - patch name
54   %(maintainer)s   - 'authname <authemail>' as read from the config file
55   %(shortdescr)s   - the first line of the patch description
56   %(longdescr)s    - the rest of the patch description, after the first line
57   %(endofheaders)s - delimiter between e-mail headers and body
58   %(diff)s         - unified diff of the patch
59   %(diffstat)s     - diff statistics
60   %(date)s         - current date/time
61   %(patchnr)s      - patch number
62   %(totalnr)s      - total number of patches to be sent
63   %(number)s       - empty if only one patch is sent or ' patchnr/totalnr'
64   %(authname)s     - author's name
65   %(authemail)s    - author's email
66   %(authdate)s     - patch creation date
67   %(commname)s     - committer's name
68   %(commemail)s    - committer's e-mail
69
70 For the preamble e-mail template, only the %(maintainer)s, %(date)s,
71 %(endofheaders)s, %(patchnr)s, %(totalnr)s and %(number)s variables
72 are supported."""
73
74 options = [make_option('-a', '--all',
75                        help = 'e-mail all the applied patches',
76                        action = 'store_true'),
77            make_option('-r', '--range',
78                        metavar = '[PATCH1][:[PATCH2]]',
79                        help = 'e-mail patches between PATCH1 and PATCH2'),
80            make_option('--to',
81                        help = 'Add TO to the To: list'),
82            make_option('--cc',
83                        help = 'Add CC to the Cc: list'),
84            make_option('--bcc',
85                        help = 'Add BCC to the Bcc: list'),
86            make_option('-t', '--template', metavar = 'FILE',
87                        help = 'use FILE as the message template'),
88            make_option('-f', '--first', metavar = 'FILE',
89                        help = 'send FILE as the first message'),
90            make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
91                        help = 'sleep for SECONDS between e-mails sending'),
92            make_option('--refid',
93                        help = 'Use REFID as the reference id'),
94            make_option('-u', '--smtp-user', metavar = 'USER',
95                        help = 'username for SMTP authentication'),
96            make_option('-p', '--smtp-password', metavar = 'PASSWORD',
97                        help = 'username for SMTP authentication')]
98
99
100 def __get_maintainer():
101     """Return the 'authname <authemail>' string as read from the
102     configuration file
103     """
104     if config.has_option('stgit', 'authname') \
105            and config.has_option('stgit', 'authemail'):
106         return '%s <%s>' % (config.get('stgit', 'authname'),
107                             config.get('stgit', 'authemail'))
108     else:
109         return None
110
111 def __parse_addresses(string):
112     """Return a two elements tuple: (from, [to])
113     """
114     def __addr_list(string):
115         return re.split('.*?([\w\.]+@[\w\.]+)', string)[1:-1:2]
116
117     from_addr_list = []
118     to_addr_list = []
119     for line in string.split('\n'):
120         if re.match('from:\s+', line, re.I):
121             from_addr_list += __addr_list(line)
122         elif re.match('(to|cc|bcc):\s+', line, re.I):
123             to_addr_list += __addr_list(line)
124
125     if len(from_addr_list) != 1:
126         raise CmdException, 'No "From" address'
127     if len(to_addr_list) == 0:
128         raise CmdException, 'No "To/Cc/Bcc" addresses'
129
130     return (from_addr_list[0], to_addr_list)
131
132 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
133                    smtpuser, smtppassword):
134     """Send the message using the given SMTP server
135     """
136     try:
137         s = smtplib.SMTP(smtpserver)
138     except Exception, err:
139         raise CmdException, str(err)
140
141     s.set_debuglevel(0)
142     try:
143         if smtpuser and smtppassword:
144             s.ehlo()
145             s.login(smtpuser, smtppassword)
146
147         s.sendmail(from_addr, to_addr_list, msg)
148         # give recipients a chance of receiving patches in the correct order
149         time.sleep(sleep)
150     except Exception, err:
151         raise CmdException, str(err)
152
153     s.quit()
154
155 def __build_first(tmpl, total_nr, msg_id, options):
156     """Build the first message (series description) to be sent via SMTP
157     """
158     maintainer = __get_maintainer()
159     if not maintainer:
160         maintainer = ''
161
162     headers_end = ''
163     if options.to:
164         headers_end += 'To: %s\n' % options.to
165     if options.cc:
166         headers_end += 'Cc: %s\n' % options.cc
167     if options.bcc:
168         headers_end += 'Bcc: %s\n' % options.bcc
169     headers_end += 'Message-Id: %s\n' % msg_id
170
171     total_nr_str = str(total_nr)
172     patch_nr_str = '0'.zfill(len(total_nr_str))
173     if total_nr > 1:
174         number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
175     else:
176         number_str = ''
177
178     tmpl_dict = {'maintainer':   maintainer,
179                  'endofheaders': headers_end,
180                  'date':         email.Utils.formatdate(localtime = True),
181                  'patchnr':      patch_nr_str,
182                  'totalnr':      total_nr_str,
183                  'number':       number_str}
184
185     try:
186         msg = tmpl % tmpl_dict
187     except KeyError, err:
188         raise CmdException, 'Unknown patch template variable: %s' \
189               % err
190     except TypeError:
191         raise CmdException, 'Only "%(name)s" variables are ' \
192               'supported in the patch template'
193
194     return msg
195
196 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
197     """Build the message to be sent via SMTP
198     """
199     p = crt_series.get_patch(patch)
200
201     descr = p.get_description().strip()
202     descr_lines = descr.split('\n')
203
204     short_descr = descr_lines[0].rstrip()
205     long_descr = reduce(lambda x, y: x + '\n' + y,
206                         descr_lines[1:], '').lstrip()
207
208     maintainer = __get_maintainer()
209     if not maintainer:
210         maintainer = '%s <%s>' % (p.get_commname(), p.get_commemail())
211
212     headers_end = ''
213     if options.to:
214         headers_end += 'To: %s\n' % options.to
215     if options.cc:
216         headers_end += 'Cc: %s\n' % options.cc
217     if options.bcc:
218         headers_end += 'Bcc: %s\n' % options.bcc
219     headers_end += 'Message-Id: %s\n' % msg_id
220     if ref_id:
221         headers_end += "In-Reply-To: %s\n" % ref_id
222         headers_end += "References: %s\n" % ref_id
223
224     total_nr_str = str(total_nr)
225     patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
226     if total_nr > 1:
227         number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
228     else:
229         number_str = ''
230
231     tmpl_dict = {'patch':        patch,
232                  'maintainer':   maintainer,
233                  'shortdescr':   short_descr,
234                  'longdescr':    long_descr,
235                  'endofheaders': headers_end,
236                  'diff':         git.diff(rev1 = git_id('%s/bottom' % patch),
237                                           rev2 = git_id('%s/top' % patch)),
238                  'diffstat':     git.diffstat(rev1 = git_id('%s/bottom'%patch),
239                                               rev2 = git_id('%s/top' % patch)),
240                  'date':         email.Utils.formatdate(localtime = True),
241                  'patchnr':      patch_nr_str,
242                  'totalnr':      total_nr_str,
243                  'number':       number_str,
244                  'authname':     p.get_authname(),
245                  'authemail':    p.get_authemail(),
246                  'authdate':     p.get_authdate(),
247                  'commname':     p.get_commname(),
248                  'commemail':    p.get_commemail()}
249     for key in tmpl_dict:
250         if not tmpl_dict[key]:
251             tmpl_dict[key] = ''
252
253     try:
254         msg = tmpl % tmpl_dict
255     except KeyError, err:
256         raise CmdException, 'Unknown patch template variable: %s' \
257               % err
258     except TypeError:
259         raise CmdException, 'Only "%(name)s" variables are ' \
260               'supported in the patch template'
261
262     return msg
263
264 def func(parser, options, args):
265     """Send the patches by e-mail using the patchmail.tmpl file as
266     a template
267     """
268     if len(args) > 1:
269         parser.error('incorrect number of arguments')
270
271     if not config.has_option('stgit', 'smtpserver'):
272         raise CmdException, 'smtpserver not defined'
273     smtpserver = config.get('stgit', 'smtpserver')
274
275     smtpuser = None
276     smtppassword = None
277     if config.has_option('stgit', 'smtpuser'):
278         smtpuser = config.get('stgit', 'smtpuser')
279     if config.has_option('stgit', 'smtppassword'):
280         smtppassword = config.get('stgit', 'smtppassword')
281
282     applied = crt_series.get_applied()
283
284     if len(args) == 1:
285         if args[0] in applied:
286             patches = [args[0]]
287         else:
288             raise CmdException, 'Patch "%s" not applied' % args[0]
289     elif options.all:
290         patches = applied
291     elif options.range:
292         boundaries = options.range.split(':')
293         if len(boundaries) == 1:
294             start = boundaries[0]
295             stop = boundaries[0]
296         elif len(boundaries) == 2:
297             if boundaries[0] == '':
298                 start = applied[0]
299             else:
300                 start = boundaries[0]
301             if boundaries[1] == '':
302                 stop = applied[-1]
303             else:
304                 stop = boundaries[1]
305         else:
306             raise CmdException, 'incorrect parameters to "--range"'
307
308         if start in applied:
309             start_idx = applied.index(start)
310         else:
311             raise CmdException, 'Patch "%s" not applied' % start
312         if stop in applied:
313             stop_idx = applied.index(stop) + 1
314         else:
315             raise CmdException, 'Patch "%s" not applied' % stop
316
317         if start_idx >= stop_idx:
318             raise CmdException, 'Incorrect patch range order'
319
320         patches = applied[start_idx:stop_idx]
321     else:
322         raise CmdException, 'Incorrect options. Unknown patches to send'
323
324     if options.smtp_password:
325         smtppassword = options.smtp_password
326
327     if options.smtp_user:
328         smtpuser = options.smtp_user
329
330     if (smtppassword and not smtpuser):
331         raise CmdException, 'SMTP password supplied, username needed'
332     if (smtpuser and not smtppassword):
333         raise CmdException, 'SMTP username supplied, password needed'
334
335     total_nr = len(patches)
336     if total_nr == 0:
337         raise CmdException, 'No patches to send'
338
339     ref_id = options.refid
340
341     if options.sleep != None:
342         sleep = options.sleep
343     else:
344         sleep = 2
345
346     # send the first message (if any)
347     if options.first:
348         tmpl = file(options.first).read()
349
350         msg_id = email.Utils.make_msgid('stgit')
351         msg = __build_first(tmpl, total_nr, msg_id, options)
352         from_addr, to_addr_list = __parse_addresses(msg)
353
354         # subsequent e-mails are seen as replies to the first one
355         ref_id = msg_id
356
357         print 'Sending file "%s"...' % options.first,
358         sys.stdout.flush()
359
360         __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
361                        smtpuser, smtppassword)
362
363         print 'done'
364
365     # send the patches
366     if options.template:
367         tfile_list = [options.template]
368     else:
369         tfile_list = []
370
371     tfile_list += [os.path.join(git.base_dir, 'patchmail.tmpl'),
372                    os.path.join(sys.prefix,
373                                 'share/stgit/templates/patchmail.tmpl')]
374     tmpl = None
375     for tfile in tfile_list:
376         if os.path.isfile(tfile):
377             tmpl = file(tfile).read()
378             break
379     if not tmpl:
380         raise CmdException, 'No e-mail template file: %s or %s' \
381               % (tfile_list[-1], tfile_list[-2])
382
383     for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
384         msg_id = email.Utils.make_msgid('stgit')
385         msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
386                               options)
387         from_addr, to_addr_list = __parse_addresses(msg)
388
389         # subsequent e-mails are seen as replies to the first one
390         if not ref_id:
391             ref_id = msg_id
392
393         print 'Sending patch "%s"...' % p,
394         sys.stdout.flush()
395
396         __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
397                        smtpuser, smtppassword)
398
399         print 'done'