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