Add diffstat of whole patch series to cover mail
[stgit] / stgit / commands / mail.py
CommitLineData
b4bddc06
CM
1__copyright__ = """
2Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
3
4This program is free software; you can redistribute it and/or modify
5it under the terms of the GNU General Public License version 2 as
6published by the Free Software Foundation.
7
8This program is distributed in the hope that it will be useful,
9but WITHOUT ANY WARRANTY; without even the implied warranty of
10MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11GNU General Public License for more details.
12
13You should have received a copy of the GNU General Public License
14along with this program; if not, write to the Free Software
15Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16"""
17
6cf5ec9b 18import sys, os, re, time, datetime, socket, smtplib, getpass
61eed152 19import email, email.Utils, email.Header
b4bddc06 20from optparse import OptionParser, make_option
b4bddc06
CM
21
22from stgit.commands.common import *
23from stgit.utils import *
5e888f30 24from stgit.out import *
1f3bb017 25from stgit import stack, git, version, templates
b4bddc06
CM
26from stgit.config import config
27
28
29help = 'send a patch or series of patches by e-mail'
6b1e0111 30usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
26aab5b0 31
cec913c4
KH
32Send a patch or a range of patches by e-mail using the SMTP server
33specified by the 'stgit.smtpserver' configuration option, or the
34'--smtp-server' command line option. The From address and the e-mail
35format are generated from the template file passed as argument to
36'--template' (defaulting to '.git/patchmail.tmpl' or
79df2f0d
CM
37'~/.stgit/templates/patchmail.tmpl' or
38'/usr/share/stgit/templates/patchmail.tmpl').
39
40The To/Cc/Bcc addresses can either be added to the template file or
41passed via the corresponding command line options. They can be e-mail
42addresses or aliases which are automatically expanded to the values
43stored in the [mail "alias"] section of GIT configuration files.
2bb96902 44
0ba13ee9
KH
45A 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
47be used as a template. The latter option will invoke the editor on the
48specified file (defaulting to '.git/covermail.tmpl' or
94d18868
YD
49'~/.stgit/templates/covermail.tmpl' or
50'/usr/share/stgit/templates/covermail.tmpl').
e3e05587
CM
51
52All 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
54replies to a different e-mail by using the '--refid' option.
26aab5b0
CM
55
56SMTP authentication is also possible with '--smtp-user' and
57'--smtp-password' options, also available as configuration settings:
fc44c2ca
PR
58'smtpuser' and 'smtppassword'. TLS encryption can be enabled by
59'--smtp-tls' option and 'smtptls' setting.
26aab5b0 60
e5bdb1fe 61The patch e-mail template accepts the following variables:
26aab5b0
CM
62
63 %(patch)s - patch name
901288c2 64 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
26aab5b0
CM
65 %(shortdescr)s - the first line of the patch description
66 %(longdescr)s - the rest of the patch description, after the first line
26aab5b0
CM
67 %(diff)s - unified diff of the patch
68 %(diffstat)s - diff statistics
d0d139a3 69 %(version)s - ' version' string passed on the command line (or empty)
d323b5da 70 %(prefix)s - 'prefix ' string passed on the command line
26aab5b0
CM
71 %(patchnr)s - patch number
72 %(totalnr)s - total number of patches to be sent
b8d258e5 73 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
901288c2 74 %(fromauth)s - 'From: author\\n\\n' if different from sender
26aab5b0
CM
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
99c4a4c5
KH
81For the preamble e-mail template, only the %(diffstat)s, %(sender)s,
82%(version)s, %(patchnr)s, %(totalnr)s and %(number)s variables are supported."""
b4bddc06 83
9a316368
CM
84options = [make_option('-a', '--all',
85 help = 'e-mail all the applied patches',
86 action = 'store_true'),
2bb96902 87 make_option('--to',
e83b3149
PO
88 help = 'add TO to the To: list',
89 action = 'append'),
2bb96902 90 make_option('--cc',
e83b3149
PO
91 help = 'add CC to the Cc: list',
92 action = 'append'),
2bb96902 93 make_option('--bcc',
e83b3149
PO
94 help = 'add BCC to the Bcc: list',
95 action = 'append'),
f8d1cf65
CM
96 make_option('--auto',
97 help = 'automatically cc the patch signers',
98 action = 'store_true'),
d1ed3a12
CM
99 make_option('--noreply',
100 help = 'do not send subsequent messages as replies',
101 action = 'store_true'),
c2a8af1d
CM
102 make_option('--unrelated',
103 help = 'send patches without sequence numbering',
104 action = 'store_true'),
d0d139a3
CM
105 make_option('-v', '--version', metavar = 'VERSION',
106 help = 'add VERSION to the [PATCH ...] prefix'),
d323b5da
RR
107 make_option('--prefix', metavar = 'PREFIX',
108 help = 'add PREFIX to the [... PATCH ...] prefix'),
9a316368
CM
109 make_option('-t', '--template', metavar = 'FILE',
110 help = 'use FILE as the message template'),
e3e05587
CM
111 make_option('-c', '--cover', metavar = 'FILE',
112 help = 'send FILE as the cover message'),
0ba13ee9 113 make_option('-e', '--edit-cover',
e3e05587
CM
114 help = 'edit the cover message before sending',
115 action = 'store_true'),
0ba13ee9
KH
116 make_option('-E', '--edit-patches',
117 help = 'edit each patch before sending',
118 action = 'store_true'),
b4bddc06
CM
119 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
120 help = 'sleep for SECONDS between e-mails sending'),
121 make_option('--refid',
d0d139a3 122 help = 'use REFID as the reference id'),
cec913c4
KH
123 make_option('--smtp-server', metavar = 'HOST[:PORT]',
124 help = 'SMTP server to use for sending mail'),
eb026d93
B
125 make_option('-u', '--smtp-user', metavar = 'USER',
126 help = 'username for SMTP authentication'),
127 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
2f7c8b0b 128 help = 'username for SMTP authentication'),
fc44c2ca
PR
129 make_option('-T', '--smtp-tls',
130 help = 'use SMTP with TLS encryption',
131 action = 'store_true'),
2f7c8b0b 132 make_option('-b', '--branch',
29f00589 133 help = 'use BRANCH instead of the default one'),
2ace36ab
YD
134 make_option('-O', '--diff-opts',
135 help = 'options to pass to git-diff'),
29f00589
CM
136 make_option('-m', '--mbox',
137 help = 'generate an mbox file instead of sending',
138 action = 'store_true')]
b4bddc06
CM
139
140
901288c2 141def __get_sender():
dae0f0be
CM
142 """Return the 'authname <authemail>' string as read from the
143 configuration file
144 """
c73e63b7
YD
145 sender=config.get('stgit.sender')
146 if not sender:
9e3f506f
KH
147 try:
148 sender = str(git.user())
149 except git.GitException:
150 sender = str(git.author())
151
152 if not sender:
901288c2 153 raise CmdException, 'unknown sender details'
dae0f0be 154
79df2f0d 155 return address_or_alias(sender)
9e3f506f 156
d650d6ed 157def __parse_addresses(msg):
b4bddc06
CM
158 """Return a two elements tuple: (from, [to])
159 """
d650d6ed
CM
160 def __addr_list(msg, header):
161 return [name_addr[1] for name_addr in
162 email.Utils.getaddresses(msg.get_all(header, []))]
b4bddc06 163
d650d6ed 164 from_addr_list = __addr_list(msg, 'From')
24aadb3f 165 if len(from_addr_list) == 0:
b4bddc06 166 raise CmdException, 'No "From" address'
d650d6ed
CM
167
168 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
169 + __addr_list(msg, 'Bcc')
b4bddc06
CM
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
eb026d93 175def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
fc44c2ca 176 smtpuser, smtppassword, use_tls):
b4bddc06
CM
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:
eb026d93
B
186 if smtpuser and smtppassword:
187 s.ehlo()
fc44c2ca
PR
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()
eb026d93
B
193 s.login(smtpuser, smtppassword)
194
0bc1343c
YD
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
b4bddc06
CM
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
61eed152 205def __build_address_headers(msg, options, extra_cc = []):
f8d1cf65
CM
206 """Build the address headers and check existing headers in the
207 template.
208 """
61eed152
CM
209 def __replace_header(header, addr):
210 if addr:
211 crt_addr = msg[header]
212 del msg[header]
f8d1cf65 213
61eed152 214 if crt_addr:
79df2f0d 215 msg[header] = address_or_alias(', '.join([crt_addr, addr]))
61eed152 216 else:
79df2f0d 217 msg[header] = address_or_alias(addr)
f8d1cf65 218
f8d1cf65
CM
219 to_addr = ''
220 cc_addr = ''
221 bcc_addr = ''
222
c73e63b7 223 autobcc = config.get('stgit.autobcc') or ''
d884c4d8 224
e83b3149 225 if options.to:
61eed152 226 to_addr = ', '.join(options.to)
e83b3149 227 if options.cc:
61eed152 228 cc_addr = ', '.join(options.cc + extra_cc)
f8d1cf65 229 elif extra_cc:
61eed152 230 cc_addr = ', '.join(extra_cc)
e83b3149 231 if options.bcc:
61eed152 232 bcc_addr = ', '.join(options.bcc + [autobcc])
d884c4d8
CM
233 elif autobcc:
234 bcc_addr = autobcc
f8d1cf65 235
61eed152
CM
236 __replace_header('To', to_addr)
237 __replace_header('Cc', cc_addr)
238 __replace_header('Bcc', bcc_addr)
f8d1cf65
CM
239
240def __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
769cd397 246 r = re.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re.I)
f8d1cf65
CM
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
e83b3149 253
61eed152
CM
254def __build_extra_headers(msg, msg_id, ref_id = None):
255 """Build extra email headers and encoding
19a56fa1 256 """
61eed152
CM
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
265def __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)
19a56fa1 286
58c61f10 287def __edit_message(msg):
0ba13ee9
KH
288 fname = '.stgitmail.txt'
289
290 # create the initial file
291 f = file(fname, 'w')
292 f.write(msg)
293 f.close()
294
83bb4e4c 295 call_editor(fname)
0ba13ee9
KH
296
297 # read the message back
298 f = file(fname)
299 msg = f.read()
300 f.close()
301
302 return msg
303
99c4a4c5 304def __build_cover(tmpl, patches, msg_id, options):
e3e05587 305 """Build the cover message (series description) to be sent via SMTP
b4bddc06 306 """
901288c2 307 sender = __get_sender()
dae0f0be 308
d0d139a3
CM
309 if options.version:
310 version_str = ' %s' % options.version
ed5de0cc
CM
311 else:
312 version_str = ''
d0d139a3 313
d323b5da
RR
314 if options.prefix:
315 prefix_str = options.prefix + ' '
316 else:
a7e0d4ee
YD
317 confprefix = config.get('stgit.mail.prefix')
318 if confprefix:
319 prefix_str = confprefix + ' '
320 else:
321 prefix_str = ''
d323b5da 322
99c4a4c5 323 total_nr_str = str(len(patches))
b8d258e5 324 patch_nr_str = '0'.zfill(len(total_nr_str))
99c4a4c5 325 if len(patches) > 1:
b8d258e5
CM
326 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
327 else:
328 number_str = ''
b4bddc06 329
901288c2
CM
330 tmpl_dict = {'sender': sender,
331 # for backward template compatibility
332 'maintainer': sender,
61eed152
CM
333 # for backward template compatibility
334 'endofheaders': '',
335 # for backward template compatibility
336 'date': '',
d0d139a3 337 'version': version_str,
d323b5da 338 'prefix': prefix_str,
b8d258e5
CM
339 'patchnr': patch_nr_str,
340 'totalnr': total_nr_str,
99c4a4c5
KH
341 'number': number_str,
342 'diffstat': git.diffstat(
343 rev1 = git_id('%s//bottom' % patches[0]),
344 rev2 = git_id('%s//top' % patches[-1]))}
b4bddc06
CM
345
346 try:
61eed152 347 msg_string = tmpl % tmpl_dict
b4bddc06
CM
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
58c61f10
CM
355 if options.edit_cover:
356 msg_string = __edit_message(msg_string)
357
61eed152
CM
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
d650d6ed 368 return msg
b4bddc06 369
2bb96902 370def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
b4bddc06
CM
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()
61eed152 379 long_descr = '\n'.join(descr_lines[1:]).lstrip()
b4bddc06 380
1d1485c3
CM
381 authname = p.get_authname();
382 authemail = p.get_authemail();
383 commname = p.get_commname();
384 commemail = p.get_commemail();
385
901288c2 386 sender = __get_sender()
1d1485c3
CM
387
388 fromauth = '%s <%s>' % (authname, authemail)
901288c2 389 if fromauth != sender:
1d1485c3
CM
390 fromauth = 'From: %s\n\n' % fromauth
391 else:
392 fromauth = ''
dae0f0be 393
d0d139a3
CM
394 if options.version:
395 version_str = ' %s' % options.version
ed5de0cc
CM
396 else:
397 version_str = ''
d0d139a3 398
d323b5da
RR
399 if options.prefix:
400 prefix_str = options.prefix + ' '
401 else:
a7e0d4ee
YD
402 confprefix = config.get('stgit.mail.prefix')
403 if confprefix:
404 prefix_str = confprefix + ' '
405 else:
406 prefix_str = ''
d323b5da 407
2ace36ab
YD
408 if options.diff_opts:
409 diff_flags = options.diff_opts.split()
0d219030
YD
410 else:
411 diff_flags = []
412
b4bddc06
CM
413 total_nr_str = str(total_nr)
414 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
c2a8af1d 415 if not options.unrelated and total_nr > 1:
b8d258e5
CM
416 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
417 else:
418 number_str = ''
b4bddc06
CM
419
420 tmpl_dict = {'patch': patch,
901288c2
CM
421 'sender': sender,
422 # for backward template compatibility
423 'maintainer': sender,
b4bddc06
CM
424 'shortdescr': short_descr,
425 'longdescr': long_descr,
61eed152
CM
426 # for backward template compatibility
427 'endofheaders': '',