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