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