Ask git for author and committer name
[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
61eed152
CM
18import sys, os, re, time, datetime, smtplib
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 *
1f3bb017 24from stgit import stack, git, version, templates
b4bddc06
CM
25from stgit.config import config
26
27
28help = 'send a patch or series of patches by e-mail'
6b1e0111 29usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
26aab5b0 30
6b1e0111
CM
31Send a patch or a range of patches by e-mail using the 'smtpserver'
32configuration option. The From address and the e-mail format are
33generated from the template file passed as argument to '--template'
34(defaulting to '.git/patchmail.tmpl' or
35'~/.stgit/templates/patchmail.tmpl' or or
94d18868 36'/usr/share/stgit/templates/patchmail.tmpl'). The To/Cc/Bcc addresses
2bb96902
CM
37can either be added to the template file or passed via the
38corresponding command line options.
39
0ba13ee9
KH
40A 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
42be used as a template. The latter option will invoke the editor on the
43specified file (defaulting to '.git/covermail.tmpl' or
94d18868
YD
44'~/.stgit/templates/covermail.tmpl' or
45'/usr/share/stgit/templates/covermail.tmpl').
e3e05587
CM
46
47All 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
49replies to a different e-mail by using the '--refid' option.
26aab5b0
CM
50
51SMTP authentication is also possible with '--smtp-user' and
52'--smtp-password' options, also available as configuration settings:
53'smtpuser' and 'smtppassword'.
54
e5bdb1fe 55The patch e-mail template accepts the following variables:
26aab5b0
CM
56
57 %(patch)s - patch name
901288c2 58 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
26aab5b0
CM
59 %(shortdescr)s - the first line of the patch description
60 %(longdescr)s - the rest of the patch description, after the first line
26aab5b0
CM
61 %(diff)s - unified diff of the patch
62 %(diffstat)s - diff statistics
d0d139a3 63 %(version)s - ' version' string passed on the command line (or empty)
d323b5da 64 %(prefix)s - 'prefix ' string passed on the command line
26aab5b0
CM
65 %(patchnr)s - patch number
66 %(totalnr)s - total number of patches to be sent
b8d258e5 67 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
901288c2 68 %(fromauth)s - 'From: author\\n\\n' if different from sender
26aab5b0
CM
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
901288c2
CM
75For the preamble e-mail template, only the %(sender)s, %(version)s,
76%(patchnr)s, %(totalnr)s and %(number)s variables are supported."""
b4bddc06 77
9a316368
CM
78options = [make_option('-a', '--all',
79 help = 'e-mail all the applied patches',
80 action = 'store_true'),
2bb96902 81 make_option('--to',
e83b3149
PO
82 help = 'add TO to the To: list',
83 action = 'append'),
2bb96902 84 make_option('--cc',
e83b3149
PO
85 help = 'add CC to the Cc: list',
86 action = 'append'),
2bb96902 87 make_option('--bcc',
e83b3149
PO
88 help = 'add BCC to the Bcc: list',
89 action = 'append'),
f8d1cf65
CM
90 make_option('--auto',
91 help = 'automatically cc the patch signers',
92 action = 'store_true'),
d1ed3a12
CM
93 make_option('--noreply',
94 help = 'do not send subsequent messages as replies',
95 action = 'store_true'),
d0d139a3
CM
96 make_option('-v', '--version', metavar = 'VERSION',
97 help = 'add VERSION to the [PATCH ...] prefix'),
d323b5da
RR
98 make_option('--prefix', metavar = 'PREFIX',
99 help = 'add PREFIX to the [... PATCH ...] prefix'),
9a316368
CM
100 make_option('-t', '--template', metavar = 'FILE',
101 help = 'use FILE as the message template'),
e3e05587
CM
102 make_option('-c', '--cover', metavar = 'FILE',
103 help = 'send FILE as the cover message'),
0ba13ee9 104 make_option('-e', '--edit-cover',
e3e05587
CM
105 help = 'edit the cover message before sending',
106 action = 'store_true'),
0ba13ee9
KH
107 make_option('-E', '--edit-patches',
108 help = 'edit each patch before sending',
109 action = 'store_true'),
b4bddc06
CM
110 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
111 help = 'sleep for SECONDS between e-mails sending'),
112 make_option('--refid',
d0d139a3 113 help = 'use REFID as the reference id'),
eb026d93
B
114 make_option('-u', '--smtp-user', metavar = 'USER',
115 help = 'username for SMTP authentication'),
116 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
2f7c8b0b
CM
117 help = 'username for SMTP authentication'),
118 make_option('-b', '--branch',
29f00589
CM
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')]
b4bddc06
CM
123
124
901288c2 125def __get_sender():
dae0f0be
CM
126 """Return the 'authname <authemail>' string as read from the
127 configuration file
128 """
901288c2 129 if config.has_option('stgit', 'sender'):
9e3f506f 130 sender = config.get('stgit', 'sender')
dae0f0be 131 else:
9e3f506f
KH
132 try:
133 sender = str(git.user())
134 except git.GitException:
135 sender = str(git.author())
136
137 if not sender:
901288c2 138 raise CmdException, 'unknown sender details'
dae0f0be 139
9e3f506f
KH
140 return sender
141
7cc615f3 142def __parse_addresses(addresses):
b4bddc06
CM
143 """Return a two elements tuple: (from, [to])
144 """
7cc615f3
CL
145 def __addr_list(addrs):
146 m = re.search('[^@\s<,]+@[^>\s,]+', addrs);
d60cd083
CM
147 if (m == None):
148 return []
7cc615f3 149 return [ m.group() ] + __addr_list(addrs[m.end():])
b4bddc06
CM
150
151 from_addr_list = []
152 to_addr_list = []
7cc615f3 153 for line in addresses.split('\n'):
b4bddc06
CM
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
24aadb3f 159 if len(from_addr_list) == 0:
b4bddc06
CM
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
eb026d93
B
166def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
167 smtpuser, smtppassword):
b4bddc06
CM
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:
eb026d93
B
177 if smtpuser and smtppassword:
178 s.ehlo()
179 s.login(smtpuser, smtppassword)
180
b4bddc06
CM
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
61eed152 189def __build_address_headers(msg, options, extra_cc = []):
f8d1cf65
CM
190 """Build the address headers and check existing headers in the
191 template.
192 """
61eed152
CM
193 def __replace_header(header, addr):
194 if addr:
195 crt_addr = msg[header]
196 del msg[header]
f8d1cf65 197
61eed152
CM
198 if crt_addr:
199 msg[header] = ', '.join([crt_addr, addr])
200 else:
201 msg[header] = addr
f8d1cf65 202
f8d1cf65
CM
203 to_addr = ''
204 cc_addr = ''
205 bcc_addr = ''
206
d884c4d8
CM
207 if config.has_option('stgit', 'autobcc'):
208 autobcc = config.get('stgit', 'autobcc')
209 else:
210 autobcc = ''
211
e83b3149 212 if options.to:
61eed152 213 to_addr = ', '.join(options.to)
e83b3149 214 if options.cc:
61eed152 215 cc_addr = ', '.join(options.cc + extra_cc)
f8d1cf65 216 elif extra_cc:
61eed152 217 cc_addr = ', '.join(extra_cc)
e83b3149 218 if options.bcc:
61eed152 219 bcc_addr = ', '.join(options.bcc + [autobcc])
d884c4d8
CM
220 elif autobcc:
221 bcc_addr = autobcc
f8d1cf65 222
61eed152
CM
223 __replace_header('To', to_addr)
224 __replace_header('Cc', cc_addr)
225 __replace_header('Bcc', bcc_addr)
f8d1cf65
CM
226
227def __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
e83b3149 240
61eed152
CM
241def __build_extra_headers(msg, msg_id, ref_id = None):
242 """Build extra email headers and encoding
19a56fa1 243 """
61eed152
CM
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
252def __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)
19a56fa1 273
58c61f10 274def __edit_message(msg):
0ba13ee9
KH
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
e3e05587
CM
302def __build_cover(tmpl, total_nr, msg_id, options):
303 """Build the cover message (series description) to be sent via SMTP
b4bddc06 304 """
901288c2 305 sender = __get_sender()
dae0f0be 306
d0d139a3
CM
307 if options.version:
308 version_str = ' %s' % options.version
ed5de0cc
CM
309 else:
310 version_str = ''
d0d139a3 311
d323b5da
RR
312 if options.prefix:
313 prefix_str = options.prefix + ' '
314 else:
315 prefix_str = ''
316
b4bddc06 317 total_nr_str = str(total_nr)
b8d258e5
CM
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 = ''
b4bddc06 323
901288c2
CM
324 tmpl_dict = {'sender': sender,
325 # for backward template compatibility
326 'maintainer': sender,
61eed152
CM
327 # for backward template compatibility
328 'endofheaders': '',
329 # for backward template compatibility
330 'date': '',
d0d139a3 331 'version': version_str,
d323b5da 332 'prefix': prefix_str,
b8d258e5
CM
333 'patchnr': patch_nr_str,
334 'totalnr': total_nr_str,
335 'number': number_str}
b4bddc06
CM
336
337 try:
61eed152 338 msg_string = tmpl % tmpl_dict
b4bddc06
CM
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
58c61f10
CM
346 if options.edit_cover:
347 msg_string = __edit_message(msg_string)
348
61eed152
CM
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
61eed152 361 return msg_string.strip('\n')
b4bddc06 362
2bb96902 363def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
b4bddc06
CM
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()
61eed152 372 long_descr = '\n'.join(descr_lines[1:]).lstrip()
b4bddc06 373
1d1485c3
CM
374 authname = p.get_authname();
375 authemail = p.get_authemail();
376 commname = p.get_commname();
377 commemail = p.get_commemail();
378
901288c2 379 sender = __get_sender()
1d1485c3
CM
380
381 fromauth = '%s <%s>' % (authname, authemail)
901288c2 382 if fromauth != sender:
1d1485c3
CM
383 fromauth = 'From: %s\n\n' % fromauth
384 else:
385 fromauth = ''
dae0f0be 386
d0d139a3
CM
387 if options.version:
388 version_str = ' %s' % options.version
ed5de0cc
CM
389 else:
390 version_str = ''
d0d139a3 391
d323b5da
RR
392 if options.prefix:
393 prefix_str = options.prefix + ' '
394 else:
395 prefix_str = ''
396
b4bddc06
CM
397 total_nr_str = str(total_nr)
398 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
b8d258e5
CM
399 if total_nr > 1:
400 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
401 else:
402 number_str = ''
b4bddc06
CM
403
404 tmpl_dict = {'patch': patch,
901288c2
CM
405 'sender': sender,
406 # for backward template compatibility
407 'maintainer': sender,
b4bddc06
CM
408 'shortdescr': short_descr,
409 'longdescr': long_descr,
61eed152
CM
410 # for backward template compatibility
411 'endofheaders': '',