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