chiark / gitweb /
Use the ".." syntax for patch ranges
[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 '--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 '~/.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   %(patchnr)s      - patch number
69   %(totalnr)s      - total number of patches to be sent
70   %(number)s       - empty if only one patch is sent or ' patchnr/totalnr'
71   %(authname)s     - author's name
72   %(authemail)s    - author's email
73   %(authdate)s     - patch creation date
74   %(commname)s     - committer's name
75   %(commemail)s    - committer's e-mail
76
77 For the preamble e-mail template, only the %(maintainer)s, %(date)s,
78 %(endofheaders)s, %(version)s, %(patchnr)s, %(totalnr)s and %(number)s
79 variables are supported."""
80
81 options = [make_option('-a', '--all',
82                        help = 'e-mail all the applied patches',
83                        action = 'store_true'),
84            make_option('--to',
85                        help = 'add TO to the To: list',
86                        action = 'append'),
87            make_option('--cc',
88                        help = 'add CC to the Cc: list',
89                        action = 'append'),
90            make_option('--bcc',
91                        help = 'add BCC to the Bcc: list',
92                        action = 'append'),
93            make_option('-v', '--version', metavar = 'VERSION',
94                        help = 'add VERSION to the [PATCH ...] prefix'),
95            make_option('-t', '--template', metavar = 'FILE',
96                        help = 'use FILE as the message template'),
97            make_option('-c', '--cover', metavar = 'FILE',
98                        help = 'send FILE as the cover message'),
99            make_option('-e', '--edit',
100                        help = 'edit the cover message before sending',
101                        action = 'store_true'),
102            make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
103                        help = 'sleep for SECONDS between e-mails sending'),
104            make_option('--refid',
105                        help = 'use REFID as the reference id'),
106            make_option('-u', '--smtp-user', metavar = 'USER',
107                        help = 'username for SMTP authentication'),
108            make_option('-p', '--smtp-password', metavar = 'PASSWORD',
109                        help = 'username for SMTP authentication'),
110            make_option('-b', '--branch',
111                        help = 'use BRANCH instead of the default one'),
112            make_option('-m', '--mbox',
113                        help = 'generate an mbox file instead of sending',
114                        action = 'store_true')]
115
116
117 def __get_maintainer():
118     """Return the 'authname <authemail>' string as read from the
119     configuration file
120     """
121     if config.has_option('stgit', 'authname') \
122            and config.has_option('stgit', 'authemail'):
123         return '%s <%s>' % (config.get('stgit', 'authname'),
124                             config.get('stgit', 'authemail'))
125     else:
126         return None
127
128 def __parse_addresses(addresses):
129     """Return a two elements tuple: (from, [to])
130     """
131     def __addr_list(addrs):
132         m = re.search('[^@\s<,]+@[^>\s,]+', addrs);
133         if (m == None):
134             return []
135         return [ m.group() ] + __addr_list(addrs[m.end():])
136
137     from_addr_list = []
138     to_addr_list = []
139     for line in addresses.split('\n'):
140         if re.match('from:\s+', line, re.I):
141             from_addr_list += __addr_list(line)
142         elif re.match('(to|cc|bcc):\s+', line, re.I):
143             to_addr_list += __addr_list(line)
144
145     if len(from_addr_list) == 0:
146         raise CmdException, 'No "From" address'
147     if len(to_addr_list) == 0:
148         raise CmdException, 'No "To/Cc/Bcc" addresses'
149
150     return (from_addr_list[0], to_addr_list)
151
152 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
153                    smtpuser, smtppassword):
154     """Send the message using the given SMTP server
155     """
156     try:
157         s = smtplib.SMTP(smtpserver)
158     except Exception, err:
159         raise CmdException, str(err)
160
161     s.set_debuglevel(0)
162     try:
163         if smtpuser and smtppassword:
164             s.ehlo()
165             s.login(smtpuser, smtppassword)
166
167         s.sendmail(from_addr, to_addr_list, msg)
168         # give recipients a chance of receiving patches in the correct order
169         time.sleep(sleep)
170     except Exception, err:
171         raise CmdException, str(err)
172
173     s.quit()
174
175 def __write_mbox(from_addr, msg):
176     """Write an mbox like file to the standard output
177     """
178     r = re.compile('^From ', re.M)
179     msg = r.sub('>\g<0>', msg)
180
181     print 'From %s %s' % (from_addr, datetime.datetime.today().ctime())
182     print msg
183     print
184
185 def __build_address_headers(options):
186     headers_end = ''
187     if options.to:
188         headers_end += 'To: '
189         for to in options.to:
190             headers_end += '%s, ' % to
191         headers_end = headers_end[:-2] + '\n'
192     if options.cc:
193         headers_end += 'Cc: '
194         for cc in options.cc:
195             headers_end += '%s, ' % cc
196         headers_end = headers_end[:-2] + '\n'
197     if options.bcc:
198         headers_end += 'Bcc: '
199         for bcc in options.bcc:
200             headers_end += '%s, ' % bcc
201         headers_end = headers_end[:-2] + '\n'
202     return headers_end
203
204 def __build_extra_headers():
205     """Build extra headers like content-type etc.
206     """
207     headers  = 'Content-Type: text/plain; charset=utf-8; format=fixed\n'
208     headers += 'Content-Transfer-Encoding: 8bit\n'
209     headers += 'User-Agent: StGIT/%s\n' % version.version
210
211     return headers
212
213 def __build_cover(tmpl, total_nr, msg_id, options):
214     """Build the cover message (series description) to be sent via SMTP
215     """
216     maintainer = __get_maintainer()
217     if not maintainer:
218         maintainer = ''
219
220     headers_end = __build_address_headers(options)
221     headers_end += 'Message-Id: %s\n' % msg_id
222     if options.refid:
223         headers_end += "In-Reply-To: %s\n" % options.refid
224         headers_end += "References: %s\n" % options.refid
225     headers_end += __build_extra_headers()
226
227     if options.version:
228         version_str = ' %s' % options.version
229     else:
230         version_str = ''
231
232     total_nr_str = str(total_nr)
233     patch_nr_str = '0'.zfill(len(total_nr_str))
234     if total_nr > 1:
235         number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
236     else:
237         number_str = ''
238
239     tmpl_dict = {'maintainer':   maintainer,
240                  'endofheaders': headers_end,
241                  'date':         email.Utils.formatdate(localtime = True),
242                  'version':      version_str,
243                  'patchnr':      patch_nr_str,
244                  'totalnr':      total_nr_str,
245                  'number':       number_str}
246
247     try:
248         msg = tmpl % tmpl_dict
249     except KeyError, err:
250         raise CmdException, 'Unknown patch template variable: %s' \
251               % err
252     except TypeError:
253         raise CmdException, 'Only "%(name)s" variables are ' \
254               'supported in the patch template'
255
256     if options.edit:
257         fname = '.stgitmail.txt'
258
259         # create the initial file
260         f = file(fname, 'w+')
261         f.write(msg)
262         f.close()
263
264         # the editor
265         if config.has_option('stgit', 'editor'):
266             editor = config.get('stgit', 'editor')
267         elif 'EDITOR' in os.environ:
268             editor = os.environ['EDITOR']
269         else:
270             editor = 'vi'
271         editor += ' %s' % fname
272
273         print 'Invoking the editor: "%s"...' % editor,
274         sys.stdout.flush()
275         print 'done (exit code: %d)' % os.system(editor)
276
277         # read the message back
278         f = file(fname)
279         msg = f.read()
280         f.close()
281
282     return msg.strip('\n')
283
284 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
285     """Build the message to be sent via SMTP
286     """
287     p = crt_series.get_patch(patch)
288
289     descr = p.get_description().strip()
290     descr_lines = descr.split('\n')
291
292     short_descr = descr_lines[0].rstrip()
293     long_descr = reduce(lambda x, y: x + '\n' + y,
294                         descr_lines[1:], '').lstrip()
295
296     maintainer = __get_maintainer()
297     if not maintainer:
298         maintainer = '%s <%s>' % (p.get_commname(), p.get_commemail())
299
300     headers_end = __build_address_headers(options)
301     headers_end += 'Message-Id: %s\n' % msg_id
302     if ref_id:
303         headers_end += "In-Reply-To: %s\n" % ref_id
304         headers_end += "References: %s\n" % ref_id
305     headers_end += __build_extra_headers()
306
307     if options.version:
308         version_str = ' %s' % options.version
309     else:
310         version_str = ''
311
312     total_nr_str = str(total_nr)
313     patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
314     if total_nr > 1:
315         number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
316     else:
317         number_str = ''
318
319     tmpl_dict = {'patch':        patch,
320                  'maintainer':   maintainer,
321                  'shortdescr':   short_descr,
322                  'longdescr':    long_descr,
323                  'endofheaders': headers_end,
324                  'diff':         git.diff(rev1 = git_id('%s//bottom' % patch),
325                                           rev2 = git_id('%s//top' % patch)),
326                  'diffstat':     git.diffstat(rev1 = git_id('%s//bottom'%patch),
327                                               rev2 = git_id('%s//top' % patch)),
328                  'date':         email.Utils.formatdate(localtime = True),
329                  'version':      version_str,
330                  'patchnr':      patch_nr_str,
331                  'totalnr':      total_nr_str,
332                  'number':       number_str,
333                  'authname':     p.get_authname(),
334                  'authemail':    p.get_authemail(),
335                  'authdate':     p.get_authdate(),
336                  'commname':     p.get_commname(),
337                  'commemail':    p.get_commemail()}
338     for key in tmpl_dict:
339         if not tmpl_dict[key]:
340             tmpl_dict[key] = ''
341
342     try:
343         msg = tmpl % tmpl_dict
344     except KeyError, err:
345         raise CmdException, 'Unknown patch template variable: %s' \
346               % err
347     except TypeError:
348         raise CmdException, 'Only "%(name)s" variables are ' \
349               'supported in the patch template'
350
351     return msg.strip('\n')
352
353 def func(parser, options, args):
354     """Send the patches by e-mail using the patchmail.tmpl file as
355     a template
356     """
357     smtpserver = config.get('stgit', 'smtpserver')
358
359     smtpuser = None
360     smtppassword = None
361     if config.has_option('stgit', 'smtpuser'):
362         smtpuser = config.get('stgit', 'smtpuser')
363     if config.has_option('stgit', 'smtppassword'):
364         smtppassword = config.get('stgit', 'smtppassword')
365
366     applied = crt_series.get_applied()
367
368     if options.all:
369         patches = applied
370     elif len(args) >= 1:
371         patches = parse_patches(args, applied)
372     else:
373         raise CmdException, 'Incorrect options. Unknown patches to send'
374
375     if options.smtp_password:
376         smtppassword = options.smtp_password
377
378     if options.smtp_user:
379         smtpuser = options.smtp_user
380
381     if (smtppassword and not smtpuser):
382         raise CmdException, 'SMTP password supplied, username needed'
383     if (smtpuser and not smtppassword):
384         raise CmdException, 'SMTP username supplied, password needed'
385
386     total_nr = len(patches)
387     if total_nr == 0:
388         raise CmdException, 'No patches to send'
389
390     ref_id = options.refid
391
392     if options.sleep != None:
393         sleep = options.sleep
394     else:
395         sleep = config.getint('stgit', 'smtpdelay')
396
397     # send the cover message (if any)
398     if options.cover or options.edit:
399         # find the template file
400         if options.cover:
401             tmpl = file(options.template).read()
402         else:
403             tmpl = templates.get_template('covermail.tmpl')
404             if not tmpl:
405                 raise CmdException, 'No cover message template file found'
406
407         msg_id = email.Utils.make_msgid('stgit')
408         msg = __build_cover(tmpl, total_nr, msg_id, options)
409         from_addr, to_addr_list = __parse_addresses(msg)
410
411         # subsequent e-mails are seen as replies to the first one
412         ref_id = msg_id
413
414         if options.mbox:
415             __write_mbox(from_addr, msg)
416         else:
417             print 'Sending the cover message...',
418             sys.stdout.flush()
419             __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
420                            smtpuser, smtppassword)
421             print 'done'
422
423     # send the patches
424     if options.template:
425         tmpl = file(options.template).read()
426     else:
427         tmpl = templates.get_template('patchmail.tmpl')
428         if not tmpl:
429             raise CmdException, 'No e-mail template file found'
430
431     for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
432         msg_id = email.Utils.make_msgid('stgit')
433         msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
434                               options)
435         from_addr, to_addr_list = __parse_addresses(msg)
436
437         # subsequent e-mails are seen as replies to the first one
438         if not ref_id:
439             ref_id = msg_id
440
441         if options.mbox:
442             __write_mbox(from_addr, msg)
443         else:
444             print 'Sending patch "%s"...' % p,
445             sys.stdout.flush()
446             __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
447                            smtpuser, smtppassword)
448             print 'done'