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