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