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