Only create a 'From: author' line if needed
[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
19 import email, email.Utils, email.Header
20 from optparse import OptionParser, make_option
21
22 from stgit.commands.common import *
23 from stgit.utils import *
24 from stgit import stack, git, version, templates
25 from stgit.config import config
26
27
28 help = 'send a patch or series of patches by e-mail'
29 usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
30
31 Send a patch or a range of patches by e-mail using the 'smtpserver'
32 configuration option. The From address and the e-mail format are
33 generated from the template file passed as argument to '--template'
34 (defaulting to '.git/patchmail.tmpl' or
35 '~/.stgit/templates/patchmail.tmpl' or or
36 '/usr/share/stgit/templates/patchmail.tmpl'). The To/Cc/Bcc addresses
37 can either be added to the template file or passed via the
38 corresponding command line options.
39
40 A preamble e-mail can be sent using the '--cover' and/or
41 '--edit-cover' options. The first allows the user to specify a file to
42 be used as a template. The latter option will invoke the editor on the
43 specified file (defaulting to '.git/covermail.tmpl' or
44 '~/.stgit/templates/covermail.tmpl' or
45 '/usr/share/stgit/templates/covermail.tmpl').
46
47 All the subsequent e-mails appear as replies to the first e-mail sent
48 (either the preamble or the first patch). E-mails can be seen as
49 replies to a different e-mail by using the '--refid' option.
50
51 SMTP authentication is also possible with '--smtp-user' and
52 '--smtp-password' options, also available as configuration settings:
53 'smtpuser' and 'smtppassword'.
54
55 The patch e-mail template accepts 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 %(diff)s - unified diff of the patch
62 %(diffstat)s - diff statistics
63 %(version)s - ' version' string passed on the command line (or empty)
64 %(prefix)s - 'prefix ' string passed on the command line
65 %(patchnr)s - patch number
66 %(totalnr)s - total number of patches to be sent
67 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
68 %(fromauth)s - 'From: author\\n\\n' if different from maintainer
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,
76 %(version)s, %(patchnr)s, %(totalnr)s and %(number)s variables are
77 supported."""
78
79 options = [make_option('-a', '--all',
80 help = 'e-mail all the applied patches',
81 action = 'store_true'),
82 make_option('--to',
83 help = 'add TO to the To: list',
84 action = 'append'),
85 make_option('--cc',
86 help = 'add CC to the Cc: list',
87 action = 'append'),
88 make_option('--bcc',
89 help = 'add BCC to the Bcc: list',
90 action = 'append'),
91 make_option('--auto',
92 help = 'automatically cc the patch signers',
93 action = 'store_true'),
94 make_option('--noreply',
95 help = 'do not send subsequent messages as replies',
96 action = 'store_true'),
97 make_option('-v', '--version', metavar = 'VERSION',
98 help = 'add VERSION to the [PATCH ...] prefix'),
99 make_option('--prefix', metavar = 'PREFIX',
100 help = 'add PREFIX 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-cover',
106 help = 'edit the cover message before sending',
107 action = 'store_true'),
108 make_option('-E', '--edit-patches',
109 help = 'edit each patch before sending',
110 action = 'store_true'),
111 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
112 help = 'sleep for SECONDS between e-mails sending'),
113 make_option('--refid',
114 help = 'use REFID as the reference id'),
115 make_option('-u', '--smtp-user', metavar = 'USER',
116 help = 'username for SMTP authentication'),
117 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
118 help = 'username for SMTP authentication'),
119 make_option('-b', '--branch',
120 help = 'use BRANCH instead of the default one'),
121 make_option('-m', '--mbox',
122 help = 'generate an mbox file instead of sending',
123 action = 'store_true')]
124
125
126 def __get_maintainer():
127 """Return the 'authname <authemail>' string as read from the
128 configuration file
129 """
130 if config.has_option('stgit', 'authname') \
131 and config.has_option('stgit', 'authemail'):
132 return '%s <%s>' % (config.get('stgit', 'authname'),
133 config.get('stgit', 'authemail'))
134 else:
135 return None
136
137 def __parse_addresses(addresses):
138 """Return a two elements tuple: (from, [to])
139 """
140 def __addr_list(addrs):
141 m = re.search('[^@\s<,]+@[^>\s,]+', addrs);
142 if (m == None):
143 return []
144 return [ m.group() ] + __addr_list(addrs[m.end():])
145
146 from_addr_list = []
147 to_addr_list = []
148 for line in addresses.split('\n'):
149 if re.match('from:\s+', line, re.I):
150 from_addr_list += __addr_list(line)
151 elif re.match('(to|cc|bcc):\s+', line, re.I):
152 to_addr_list += __addr_list(line)
153
154 if len(from_addr_list) == 0:
155 raise CmdException, 'No "From" address'
156 if len(to_addr_list) == 0:
157 raise CmdException, 'No "To/Cc/Bcc" addresses'
158
159 return (from_addr_list[0], to_addr_list)
160
161 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
162 smtpuser, smtppassword):
163 """Send the message using the given SMTP server
164 """
165 try:
166 s = smtplib.SMTP(smtpserver)
167 except Exception, err:
168 raise CmdException, str(err)
169
170 s.set_debuglevel(0)
171 try:
172 if smtpuser and smtppassword:
173 s.ehlo()
174 s.login(smtpuser, smtppassword)
175
176 s.sendmail(from_addr, to_addr_list, msg)
177 # give recipients a chance of receiving patches in the correct order
178 time.sleep(sleep)
179 except Exception, err:
180 raise CmdException, str(err)
181
182 s.quit()
183
184 def __build_address_headers(msg, options, extra_cc = []):
185 """Build the address headers and check existing headers in the
186 template.
187 """
188 def __replace_header(header, addr):
189 if addr:
190 crt_addr = msg[header]
191 del msg[header]
192
193 if crt_addr:
194 msg[header] = ', '.join([crt_addr, addr])
195 else:
196 msg[header] = addr
197
198 to_addr = ''
199 cc_addr = ''
200 bcc_addr = ''
201
202 if config.has_option('stgit', 'autobcc'):
203 autobcc = config.get('stgit', 'autobcc')
204 else:
205 autobcc = ''
206
207 if options.to:
208 to_addr = ', '.join(options.to)
209 if options.cc:
210 cc_addr = ', '.join(options.cc + extra_cc)
211 elif extra_cc:
212 cc_addr = ', '.join(extra_cc)
213 if options.bcc:
214 bcc_addr = ', '.join(options.bcc + [autobcc])
215 elif autobcc:
216 bcc_addr = autobcc
217
218 __replace_header('To', to_addr)
219 __replace_header('Cc', cc_addr)
220 __replace_header('Bcc', bcc_addr)
221
222 def __get_signers_list(msg):
223 """Return the address list generated from signed-off-by and
224 acked-by lines in the message.
225 """
226 addr_list = []
227
228 r = re.compile('^(signed-off-by|acked-by):\s+(.+)$', re.I)
229 for line in msg.split('\n'):
230 m = r.match(line)
231 if m:
232 addr_list.append(m.expand('\g<2>'))
233
234 return addr_list
235
236 def __build_extra_headers(msg, msg_id, ref_id = None):
237 """Build extra email headers and encoding
238 """
239 del msg['Date']
240 msg['Date'] = email.Utils.formatdate(localtime = True)
241 msg['Message-ID'] = msg_id
242 if ref_id:
243 msg['In-Reply-To'] = ref_id
244 msg['References'] = ref_id
245 msg['User-Agent'] = 'StGIT/%s' % version.version
246
247 def __encode_message(msg):
248 # 7 or 8 bit encoding
249 charset = email.Charset.Charset('utf-8')
250 charset.body_encoding = None
251
252 # encode headers
253 for header, value in msg.items():
254 words = []
255 for word in value.split(' '):
256 try:
257 uword = unicode(word, 'utf-8')
258 except UnicodeDecodeError:
259 # maybe we should try a different encoding or report
260 # the error. At the moment, we just ignore it
261 pass
262 words.append(email.Header.Header(uword).encode())
263 new_val = ' '.join(words)
264 msg.replace_header(header, new_val)
265
266 # encode the body and set the MIME and encoding headers
267 msg.set_charset(charset)
268
269 def __edit_message(msg):
270 fname = '.stgitmail.txt'
271
272 # create the initial file
273 f = file(fname, 'w')
274 f.write(msg)
275 f.close()
276
277 # the editor
278 if config.has_option('stgit', 'editor'):
279 editor = config.get('stgit', 'editor')
280 elif 'EDITOR' in os.environ:
281 editor = os.environ['EDITOR']
282 else:
283 editor = 'vi'
284 editor += ' %s' % fname
285
286 print 'Invoking the editor: "%s"...' % editor,
287 sys.stdout.flush()
288 print 'done (exit code: %d)' % os.system(editor)
289
290 # read the message back
291 f = file(fname)
292 msg = f.read()
293 f.close()
294
295 return msg
296
297 def __build_cover(tmpl, total_nr, msg_id, options):
298 """Build the cover message (series description) to be sent via SMTP
299 """
300 maintainer = __get_maintainer()
301 if not maintainer:
302 maintainer = ''
303
304 if options.version:
305 version_str = ' %s' % options.version
306 else:
307 version_str = ''
308
309 if options.prefix:
310 prefix_str = options.prefix + ' '
311 else:
312 prefix_str = ''
313
314 total_nr_str = str(total_nr)
315 patch_nr_str = '0'.zfill(len(total_nr_str))
316 if total_nr > 1:
317 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
318 else:
319 number_str = ''
320
321 tmpl_dict = {'maintainer': maintainer,
322 # for backward template compatibility
323 'endofheaders': '',
324 # for backward template compatibility
325 'date': '',
326 'version': version_str,
327 'prefix': prefix_str,
328 'patchnr': patch_nr_str,
329 'totalnr': total_nr_str,
330 'number': number_str}
331
332 try:
333 msg_string = tmpl % tmpl_dict
334 except KeyError, err:
335 raise CmdException, 'Unknown patch template variable: %s' \
336 % err
337 except TypeError:
338 raise CmdException, 'Only "%(name)s" variables are ' \
339 'supported in the patch template'
340
341 if options.edit_cover:
342 msg_string = __edit_message(msg_string)
343
344 # The Python email message
345 try:
346 msg = email.message_from_string(msg_string)
347 except Exception, ex:
348 raise CmdException, 'template parsing error: %s' % str(ex)
349
350 __build_address_headers(msg, options)
351 __build_extra_headers(msg, msg_id, options.refid)
352 __encode_message(msg)
353
354 msg_string = msg.as_string(options.mbox)
355
356 return msg_string.strip('\n')
357
358 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
359 """Build the message to be sent via SMTP
360 """
361 p = crt_series.get_patch(patch)
362
363 descr = p.get_description().strip()
364 descr_lines = descr.split('\n')
365
366 short_descr = descr_lines[0].rstrip()
367 long_descr = '\n'.join(descr_lines[1:]).lstrip()
368
369 authname = p.get_authname();
370 authemail = p.get_authemail();
371 commname = p.get_commname();
372 commemail = p.get_commemail();
373
374 maintainer = __get_maintainer()
375 if not maintainer:
376 maintainer = '%s <%s>' % (commname, commemail)
377
378 fromauth = '%s <%s>' % (authname, authemail)
379 if fromauth != maintainer:
380 fromauth = 'From: %s\n\n' % fromauth
381 else:
382 fromauth = ''
383
384 if options.version:
385 version_str = ' %s' % options.version
386 else:
387 version_str = ''
388
389 if options.prefix:
390 prefix_str = options.prefix + ' '
391 else:
392 prefix_str = ''
393
394 total_nr_str = str(total_nr)
395 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
396 if total_nr > 1:
397 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
398 else:
399 number_str = ''
400
401 tmpl_dict = {'patch': patch,
402 'maintainer': maintainer,
403 'shortdescr': short_descr,
404 'longdescr': long_descr,
405 # for backward template compatibility
406 'endofheaders': '',
407 'diff': git.diff(rev1 = git_id('%s//bottom' % patch),
408 rev2 = git_id('%s//top' % patch)),
409 'diffstat': git.diffstat(rev1 = git_id('%s//bottom'%patch),
410 rev2 = git_id('%s//top' % patch)),
411 # for backward template compatibility
412 'date': '',
413 'version': version_str,
414 'prefix': prefix_str,
415 'patchnr': patch_nr_str,
416 'totalnr': total_nr_str,
417 'number': number_str,
418 'fromauth': fromauth,
419 'authname': authname,
420 'authemail': authemail,
421 'authdate': p.get_authdate(),
422 'commname': commname,
423 'commemail': commemail}
424 # change None to ''
425 for key in tmpl_dict:
426 if not tmpl_dict[key]:
427 tmpl_dict[key] = ''
428
429 try:
430 msg_string = tmpl % tmpl_dict
431 except KeyError, err:
432 raise CmdException, 'Unknown patch template variable: %s' \
433 % err
434 except TypeError:
435 raise CmdException, 'Only "%(name)s" variables are ' \
436 'supported in the patch template'
437
438 if options.edit_patches:
439 msg_string = __edit_message(msg_string)
440
441 # The Python email message
442 try:
443 msg = email.message_from_string(msg_string)
444 except Exception, ex:
445 raise CmdException, 'template parsing error: %s' % str(ex)
446
447 if options.auto:
448 extra_cc = __get_signers_list(descr)
449 else:
450 extra_cc = []
451
452 __build_address_headers(msg, options, extra_cc)
453 __build_extra_headers(msg, msg_id, ref_id)
454 __encode_message(msg)
455
456 msg_string = msg.as_string(options.mbox)
457
458 return msg_string.strip('\n')
459
460 def func(parser, options, args):
461 """Send the patches by e-mail using the patchmail.tmpl file as
462 a template
463 """
464 smtpserver = config.get('stgit', 'smtpserver')
465
466 smtpuser = None
467 smtppassword = None
468 if config.has_option('stgit', 'smtpuser'):
469 smtpuser = config.get('stgit', 'smtpuser')
470 if config.has_option('stgit', 'smtppassword'):
471 smtppassword = config.get('stgit', 'smtppassword')
472
473 applied = crt_series.get_applied()
474
475 if options.all:
476 patches = applied
477 elif len(args) >= 1:
478 patches = parse_patches(args, applied)
479 else:
480 raise CmdException, 'Incorrect options. Unknown patches to send'
481
482 if options.smtp_password:
483 smtppassword = options.smtp_password
484
485 if options.smtp_user:
486 smtpuser = options.smtp_user
487
488 if (smtppassword and not smtpuser):
489 raise CmdException, 'SMTP password supplied, username needed'
490 if (smtpuser and not smtppassword):
491 raise CmdException, 'SMTP username supplied, password needed'
492
493 total_nr = len(patches)
494 if total_nr == 0:
495 raise CmdException, 'No patches to send'
496
497 if options.noreply:
498 ref_id = None
499 else:
500 ref_id = options.refid
501
502 if options.sleep != None:
503 sleep = options.sleep
504 else:
505 sleep = config.getint('stgit', 'smtpdelay')
506
507 # send the cover message (if any)
508 if options.cover or options.edit_cover:
509 # find the template file
510 if options.cover:
511 tmpl = file(options.cover).read()
512 else:
513 tmpl = templates.get_template('covermail.tmpl')
514 if not tmpl:
515 raise CmdException, 'No cover message template file found'
516
517 msg_id = email.Utils.make_msgid('stgit')
518 msg = __build_cover(tmpl, total_nr, msg_id, options)
519 from_addr, to_addr_list = __parse_addresses(msg)
520
521 # subsequent e-mails are seen as replies to the first one
522 if not options.noreply:
523 ref_id = msg_id
524
525 if options.mbox:
526 print msg
527 print
528 else:
529 print 'Sending the cover message...',
530 sys.stdout.flush()
531 __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
532 smtpuser, smtppassword)
533 print 'done'
534
535 # send the patches
536 if options.template:
537 tmpl = file(options.template).read()
538 else:
539 tmpl = templates.get_template('patchmail.tmpl')
540 if not tmpl:
541 raise CmdException, 'No e-mail template file found'
542
543 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
544 msg_id = email.Utils.make_msgid('stgit')
545 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
546 options)
547 from_addr, to_addr_list = __parse_addresses(msg)
548
549 # subsequent e-mails are seen as replies to the first one
550 if not options.noreply and not ref_id:
551 ref_id = msg_id
552
553 if options.mbox:
554 print msg
555 print
556 else:
557 print 'Sending patch "%s"...' % p,
558 sys.stdout.flush()
559 __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
560 smtpuser, smtppassword)
561 print 'done'