2 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
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.
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.
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
18 import sys, os, re, time, datetime, socket, smtplib, getpass
19 import email, email.Utils, email.Header
20 from optparse import OptionParser, make_option
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
29 help = 'send a patch or series of patches by e-mail'
30 usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
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').
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.
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').
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.
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.
61 The following variables are accepted by both the preamble and the
62 patch e-mail templates:
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)
71 In addition to the common variables, the preamble e-mail template
72 accepts the following:
74 %(shortlog)s - first line of each patch description, listed by author
76 In addition to the common variables, the patch e-mail template accepts
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"""
91 directory = DirectoryHasRepository()
92 options = [make_option('-a', '--all',
93 help = 'e-mail all the applied patches',
94 action = 'store_true'),
96 help = 'add TO to the To: list',
99 help = 'add CC to the Cc: list',
102 help = 'add BCC to the Bcc: list',
104 make_option('--auto',
105 help = 'automatically cc the patch signers',
106 action = 'store_true'),
107 make_option('--noreply',
108 help = 'do not send subsequent messages as replies',
109 action = 'store_true'),
110 make_option('--unrelated',
111 help = 'send patches without sequence numbering',
112 action = 'store_true'),
113 make_option('-v', '--version', metavar = 'VERSION',
114 help = 'add VERSION to the [PATCH ...] prefix'),
115 make_option('--prefix', metavar = 'PREFIX',
116 help = 'add PREFIX to the [... PATCH ...] prefix'),
117 make_option('-t', '--template', metavar = 'FILE',
118 help = 'use FILE as the message template'),
119 make_option('-c', '--cover', metavar = 'FILE',
120 help = 'send FILE as the cover message'),
121 make_option('-e', '--edit-cover',
122 help = 'edit the cover message before sending',
123 action = 'store_true'),
124 make_option('-E', '--edit-patches',
125 help = 'edit each patch before sending',
126 action = 'store_true'),
127 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
128 help = 'sleep for SECONDS between e-mails sending'),
129 make_option('--refid',
130 help = 'use REFID as the reference id'),
131 make_option('--smtp-server', metavar = 'HOST[:PORT]',
132 help = 'SMTP server to use for sending mail'),
133 make_option('-u', '--smtp-user', metavar = 'USER',
134 help = 'username for SMTP authentication'),
135 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
136 help = 'username for SMTP authentication'),
137 make_option('-T', '--smtp-tls',
138 help = 'use SMTP with TLS encryption',
139 action = 'store_true'),
140 make_option('-b', '--branch',
141 help = 'use BRANCH instead of the default one'),
142 make_option('-O', '--diff-opts',
143 help = 'options to pass to git-diff'),
144 make_option('-m', '--mbox',
145 help = 'generate an mbox file instead of sending',
146 action = 'store_true')]
150 """Return the 'authname <authemail>' string as read from the
153 sender=config.get('stgit.sender')
156 sender = str(git.user())
157 except git.GitException:
158 sender = str(git.author())
161 raise CmdException, 'unknown sender details'
163 return address_or_alias(sender)
165 def __parse_addresses(msg):
166 """Return a two elements tuple: (from, [to])
168 def __addr_list(msg, header):
169 return [name_addr[1] for name_addr in
170 email.Utils.getaddresses(msg.get_all(header, []))]
172 from_addr_list = __addr_list(msg, 'From')
173 if len(from_addr_list) == 0:
174 raise CmdException, 'No "From" address'
176 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
177 + __addr_list(msg, 'Bcc')
178 if len(to_addr_list) == 0:
179 raise CmdException, 'No "To/Cc/Bcc" addresses'
181 return (from_addr_list[0], to_addr_list)
183 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
184 smtpuser, smtppassword, use_tls):
185 """Send the message using the given SMTP server
188 s = smtplib.SMTP(smtpserver)
189 except Exception, err:
190 raise CmdException, str(err)
194 if smtpuser and smtppassword:
197 if not hasattr(socket, 'ssl'):
198 raise CmdException, "cannot use TLS - no SSL support in Python"
201 s.login(smtpuser, smtppassword)
203 result = s.sendmail(from_addr, to_addr_list, msg)
205 print "mail server refused delivery for the following recipients: %s" % result
206 # give recipients a chance of receiving patches in the correct order
208 except Exception, err:
209 raise CmdException, str(err)
213 def __build_address_headers(msg, options, extra_cc = []):
214 """Build the address headers and check existing headers in the
217 def __replace_header(header, addr):
219 crt_addr = msg[header]
223 msg[header] = address_or_alias(', '.join([crt_addr, addr]))
225 msg[header] = address_or_alias(addr)
231 autobcc = config.get('stgit.autobcc') or ''
234 to_addr = ', '.join(options.to)
236 cc_addr = ', '.join(options.cc + extra_cc)
238 cc_addr = ', '.join(extra_cc)
240 bcc_addr = ', '.join(options.bcc + [autobcc])
244 __replace_header('To', to_addr)
245 __replace_header('Cc', cc_addr)
246 __replace_header('Bcc', bcc_addr)
248 def __get_signers_list(msg):
249 """Return the address list generated from signed-off-by and
250 acked-by lines in the message.
254 r = re.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re.I)
255 for line in msg.split('\n'):
258 addr_list.append(m.expand('\g<2>'))
262 def __build_extra_headers(msg, msg_id, ref_id = None):
263 """Build extra email headers and encoding
266 msg['Date'] = email.Utils.formatdate(localtime = True)
267 msg['Message-ID'] = msg_id
269 msg['In-Reply-To'] = ref_id
270 msg['References'] = ref_id
271 msg['User-Agent'] = 'StGIT/%s' % version.version
273 def __encode_message(msg):
274 # 7 or 8 bit encoding
275 charset = email.Charset.Charset('utf-8')
276 charset.body_encoding = None
279 for header, value in msg.items():
281 for word in value.split(' '):
283 uword = unicode(word, 'utf-8')
284 except UnicodeDecodeError:
285 # maybe we should try a different encoding or report
286 # the error. At the moment, we just ignore it
288 words.append(email.Header.Header(uword).encode())
289 new_val = ' '.join(words)
290 msg.replace_header(header, new_val)
292 # encode the body and set the MIME and encoding headers
293 msg.set_charset(charset)
295 def __edit_message(msg):
296 fname = '.stgitmail.txt'
298 # create the initial file
305 # read the message back
312 def __build_cover(tmpl, patches, msg_id, options):
313 """Build the cover message (series description) to be sent via SMTP
315 sender = __get_sender()
318 version_str = ' %s' % options.version
323 prefix_str = options.prefix + ' '
325 confprefix = config.get('stgit.mail.prefix')
327 prefix_str = confprefix + ' '
331 total_nr_str = str(len(patches))
332 patch_nr_str = '0'.zfill(len(total_nr_str))
334 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
338 tmpl_dict = {'sender': sender,
339 # for backward template compatibility
340 'maintainer': sender,
341 # for backward template compatibility
343 # for backward template compatibility
345 'version': version_str,
346 'prefix': prefix_str,
347 'patchnr': patch_nr_str,
348 'totalnr': total_nr_str,
349 'number': number_str,
350 'shortlog': stack.shortlog(crt_series.get_patch(p)
352 'diffstat': git.diffstat(
353 rev1 = git_id('%s//bottom' % patches[0]),
354 rev2 = git_id('%s//top' % patches[-1]))}
357 msg_string = tmpl % tmpl_dict
358 except KeyError, err:
359 raise CmdException, 'Unknown patch template variable: %s' \
362 raise CmdException, 'Only "%(name)s" variables are ' \
363 'supported in the patch template'
365 if options.edit_cover:
366 msg_string = __edit_message(msg_string)
368 # The Python email message
370 msg = email.message_from_string(msg_string)
371 except Exception, ex:
372 raise CmdException, 'template parsing error: %s' % str(ex)
374 __build_address_headers(msg, options)
375 __build_extra_headers(msg, msg_id, options.refid)
376 __encode_message(msg)
380 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
381 """Build the message to be sent via SMTP
383 p = crt_series.get_patch(patch)
385 descr = p.get_description().strip()
386 descr_lines = descr.split('\n')
388 short_descr = descr_lines[0].rstrip()
389 long_descr = '\n'.join(descr_lines[1:]).lstrip()
391 authname = p.get_authname();
392 authemail = p.get_authemail();
393 commname = p.get_commname();
394 commemail = p.get_commemail();
396 sender = __get_sender()
398 fromauth = '%s <%s>' % (authname, authemail)
399 if fromauth != sender:
400 fromauth = 'From: %s\n\n' % fromauth
405 version_str = ' %s' % options.version
410 prefix_str = options.prefix + ' '
412 confprefix = config.get('stgit.mail.prefix')
414 prefix_str = confprefix + ' '
418 if options.diff_opts:
419 diff_flags = options.diff_opts.split()
423 total_nr_str = str(total_nr)
424 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
425 if not options.unrelated and total_nr > 1:
426 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
430 tmpl_dict = {'patch': patch,
432 # for backward template compatibility
433 'maintainer': sender,
434 'shortdescr': short_descr,
435 'longdescr': long_descr,
436 # for backward template compatibility
438 'diff': git.diff(rev1 = git_id('%s//bottom' % patch),
439 rev2 = git_id('%s//top' % patch),
440 diff_flags = diff_flags ),
441 'diffstat': git.diffstat(rev1 = git_id('%s//bottom'%patch),
442 rev2 = git_id('%s//top' % patch)),
443 # for backward template compatibility
445 'version': version_str,
446 'prefix': prefix_str,
447 'patchnr': patch_nr_str,
448 'totalnr': total_nr_str,
449 'number': number_str,
450 'fromauth': fromauth,
451 'authname': authname,
452 'authemail': authemail,
453 'authdate': p.get_authdate(),
454 'commname': commname,
455 'commemail': commemail}
457 for key in tmpl_dict:
458 if not tmpl_dict[key]:
462 msg_string = tmpl % tmpl_dict
463 except KeyError, err:
464 raise CmdException, 'Unknown patch template variable: %s' \
467 raise CmdException, 'Only "%(name)s" variables are ' \
468 'supported in the patch template'
470 if options.edit_patches:
471 msg_string = __edit_message(msg_string)
473 # The Python email message
475 msg = email.message_from_string(msg_string)
476 except Exception, ex:
477 raise CmdException, 'template parsing error: %s' % str(ex)
480 extra_cc = __get_signers_list(descr)
484 __build_address_headers(msg, options, extra_cc)
485 __build_extra_headers(msg, msg_id, ref_id)
486 __encode_message(msg)
490 def func(parser, options, args):
491 """Send the patches by e-mail using the patchmail.tmpl file as
494 smtpserver = options.smtp_server or config.get('stgit.smtpserver')
496 applied = crt_series.get_applied()
501 unapplied = crt_series.get_unapplied()
502 patches = parse_patches(args, applied + unapplied, len(applied))
504 raise CmdException, 'Incorrect options. Unknown patches to send'
506 smtppassword = options.smtp_password or config.get('stgit.smtppassword')
507 smtpuser = options.smtp_user or config.get('stgit.smtpuser')
508 smtpusetls = options.smtp_tls or config.get('stgit.smtptls') == 'yes'
510 if (smtppassword and not smtpuser):
511 raise CmdException, 'SMTP password supplied, username needed'
512 if (smtpusetls and not smtpuser):
513 raise CmdException, 'SMTP over TLS requested, username needed'
514 if (smtpuser and not smtppassword):
515 smtppassword = getpass.getpass("Please enter SMTP password: ")
517 total_nr = len(patches)
519 raise CmdException, 'No patches to send'
522 if options.noreply or options.unrelated:
523 raise CmdException, \
524 '--refid option not allowed with --noreply or --unrelated'
525 ref_id = options.refid
529 sleep = options.sleep or config.getint('stgit.smtpdelay')
531 # send the cover message (if any)
532 if options.cover or options.edit_cover:
533 if options.unrelated:
534 raise CmdException, 'cover sending not allowed with --unrelated'
536 # find the template file
538 tmpl = file(options.cover).read()
540 tmpl = templates.get_template('covermail.tmpl')
542 raise CmdException, 'No cover message template file found'
544 msg_id = email.Utils.make_msgid('stgit')
545 msg = __build_cover(tmpl, patches, msg_id, options)
546 from_addr, to_addr_list = __parse_addresses(msg)
548 msg_string = msg.as_string(options.mbox)
550 # subsequent e-mails are seen as replies to the first one
551 if not options.noreply:
555 out.stdout_raw(msg_string + '\n')
557 out.start('Sending the cover message')
558 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
559 sleep, smtpuser, smtppassword, smtpusetls)
564 tmpl = file(options.template).read()
566 tmpl = templates.get_template('patchmail.tmpl')
568 raise CmdException, 'No e-mail template file found'
570 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
571 msg_id = email.Utils.make_msgid('stgit')
572 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
574 from_addr, to_addr_list = __parse_addresses(msg)
576 msg_string = msg.as_string(options.mbox)
578 # subsequent e-mails are seen as replies to the first one
579 if not options.noreply and not options.unrelated and not ref_id:
583 out.stdout_raw(msg_string + '\n')
585 out.start('Sending patch "%s"' % p)
586 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
587 sleep, smtpuser, smtppassword, smtpusetls)