Edit the cover or patch message before e-mail encoding
[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
dae0f0be 58 %(maintainer)s - 'authname <authemail>' as read from 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'
26aab5b0
CM
68 %(authname)s - author's name
69 %(authemail)s - author's email
70 %(authdate)s - patch creation date
71 %(commname)s - committer's name
72 %(commemail)s - committer's e-mail
73
e5bdb1fe
KH
74For the preamble e-mail template, only the %(maintainer)s,
75%(version)s, %(patchnr)s, %(totalnr)s and %(number)s variables are
76supported."""
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
dae0f0be
CM
125def __get_maintainer():
126 """Return the 'authname <authemail>' string as read from the
127 configuration file
128 """
129 if config.has_option('stgit', 'authname') \
130 and config.has_option('stgit', 'authemail'):
131 return '%s <%s>' % (config.get('stgit', 'authname'),
132 config.get('stgit', 'authemail'))
133 else:
134 return None
135
7cc615f3 136def __parse_addresses(addresses):
b4bddc06
CM
137 """Return a two elements tuple: (from, [to])
138 """
7cc615f3
CL
139 def __addr_list(addrs):
140 m = re.search('[^@\s<,]+@[^>\s,]+', addrs);
d60cd083
CM
141 if (m == None):
142 return []
7cc615f3 143 return [ m.group() ] + __addr_list(addrs[m.end():])
b4bddc06
CM
144
145 from_addr_list = []
146 to_addr_list = []
7cc615f3 147 for line in addresses.split('\n'):
b4bddc06
CM
148 if re.match('from:\s+', line, re.I):
149 from_addr_list += __addr_list(line)
150 elif re.match('(to|cc|bcc):\s+', line, re.I):
151 to_addr_list += __addr_list(line)
152
24aadb3f 153 if len(from_addr_list) == 0:
b4bddc06
CM
154 raise CmdException, 'No "From" address'
155 if len(to_addr_list) == 0:
156 raise CmdException, 'No "To/Cc/Bcc" addresses'
157
158 return (from_addr_list[0], to_addr_list)
159
eb026d93
B
160def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
161 smtpuser, smtppassword):
b4bddc06
CM
162 """Send the message using the given SMTP server
163 """
164 try:
165 s = smtplib.SMTP(smtpserver)
166 except Exception, err:
167 raise CmdException, str(err)
168
169 s.set_debuglevel(0)
170 try:
eb026d93
B
171 if smtpuser and smtppassword:
172 s.ehlo()
173 s.login(smtpuser, smtppassword)
174
b4bddc06
CM
175 s.sendmail(from_addr, to_addr_list, msg)
176 # give recipients a chance of receiving patches in the correct order
177 time.sleep(sleep)
178 except Exception, err:
179 raise CmdException, str(err)
180
181 s.quit()
182
61eed152 183def __build_address_headers(msg, options, extra_cc = []):
f8d1cf65
CM
184 """Build the address headers and check existing headers in the
185 template.
186 """
61eed152
CM
187 def __replace_header(header, addr):
188 if addr:
189 crt_addr = msg[header]
190 del msg[header]
f8d1cf65 191
61eed152
CM
192 if crt_addr:
193 msg[header] = ', '.join([crt_addr, addr])
194 else:
195 msg[header] = addr
f8d1cf65 196
f8d1cf65
CM
197 to_addr = ''
198 cc_addr = ''
199 bcc_addr = ''
200
d884c4d8
CM
201 if config.has_option('stgit', 'autobcc'):
202 autobcc = config.get('stgit', 'autobcc')
203 else:
204 autobcc = ''
205
e83b3149 206 if options.to:
61eed152 207 to_addr = ', '.join(options.to)
e83b3149 208 if options.cc:
61eed152 209 cc_addr = ', '.join(options.cc + extra_cc)
f8d1cf65 210 elif extra_cc:
61eed152 211 cc_addr = ', '.join(extra_cc)
e83b3149 212 if options.bcc:
61eed152 213 bcc_addr = ', '.join(options.bcc + [autobcc])
d884c4d8
CM
214 elif autobcc:
215 bcc_addr = autobcc
f8d1cf65 216
61eed152
CM
217 __replace_header('To', to_addr)
218 __replace_header('Cc', cc_addr)
219 __replace_header('Bcc', bcc_addr)
f8d1cf65
CM
220
221def __get_signers_list(msg):
222 """Return the address list generated from signed-off-by and
223 acked-by lines in the message.
224 """
225 addr_list = []
226
227 r = re.compile('^(signed-off-by|acked-by):\s+(.+)$', re.I)
228 for line in msg.split('\n'):
229 m = r.match(line)
230 if m:
231 addr_list.append(m.expand('\g<2>'))
232
233 return addr_list
e83b3149 234
61eed152
CM
235def __build_extra_headers(msg, msg_id, ref_id = None):
236 """Build extra email headers and encoding
19a56fa1 237 """
61eed152
CM
238 del msg['Date']
239 msg['Date'] = email.Utils.formatdate(localtime = True)
240 msg['Message-ID'] = msg_id
241 if ref_id:
242 msg['In-Reply-To'] = ref_id
243 msg['References'] = ref_id
244 msg['User-Agent'] = 'StGIT/%s' % version.version
245
246def __encode_message(msg):
247 # 7 or 8 bit encoding
248 charset = email.Charset.Charset('utf-8')
249 charset.body_encoding = None
250
251 # encode headers
252 for header, value in msg.items():
253 words = []
254 for word in value.split(' '):
255 try:
256 uword = unicode(word, 'utf-8')
257 except UnicodeDecodeError:
258 # maybe we should try a different encoding or report
259 # the error. At the moment, we just ignore it
260 pass
261 words.append(email.Header.Header(uword).encode())
262 new_val = ' '.join(words)
263 msg.replace_header(header, new_val)
264
265 # encode the body and set the MIME and encoding headers
266 msg.set_charset(charset)
19a56fa1 267
58c61f10 268def __edit_message(msg):
0ba13ee9
KH
269 fname = '.stgitmail.txt'
270
271 # create the initial file
272 f = file(fname, 'w')
273 f.write(msg)
274 f.close()
275
276 # the editor
277 if config.has_option('stgit', 'editor'):
278 editor = config.get('stgit', 'editor')
279 elif 'EDITOR' in os.environ:
280 editor = os.environ['EDITOR']
281 else:
282 editor = 'vi'
283 editor += ' %s' % fname
284
285 print 'Invoking the editor: "%s"...' % editor,
286 sys.stdout.flush()
287 print 'done (exit code: %d)' % os.system(editor)
288
289 # read the message back
290 f = file(fname)
291 msg = f.read()
292 f.close()
293
294 return msg
295
e3e05587
CM
296def __build_cover(tmpl, total_nr, msg_id, options):
297 """Build the cover message (series description) to be sent via SMTP
b4bddc06 298 """
dae0f0be
CM
299 maintainer = __get_maintainer()
300 if not maintainer:
301 maintainer = ''
302
d0d139a3
CM
303 if options.version:
304 version_str = ' %s' % options.version
ed5de0cc
CM
305 else:
306 version_str = ''
d0d139a3 307
d323b5da
RR
308 if options.prefix:
309 prefix_str = options.prefix + ' '
310 else:
311 prefix_str = ''
312
b4bddc06 313 total_nr_str = str(total_nr)
b8d258e5
CM
314 patch_nr_str = '0'.zfill(len(total_nr_str))
315 if total_nr > 1:
316 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
317 else:
318 number_str = ''
b4bddc06 319
dae0f0be 320 tmpl_dict = {'maintainer': maintainer,
61eed152
CM
321 # for backward template compatibility
322 'endofheaders': '',
323 # for backward template compatibility
324 'date': '',
d0d139a3 325 'version': version_str,
d323b5da 326 'prefix': prefix_str,
b8d258e5
CM
327 'patchnr': patch_nr_str,
328 'totalnr': total_nr_str,
329 'number': number_str}
b4bddc06
CM
330
331 try:
61eed152 332 msg_string = tmpl % tmpl_dict
b4bddc06
CM
333 except KeyError, err:
334 raise CmdException, 'Unknown patch template variable: %s' \
335 % err
336 except TypeError:
337 raise CmdException, 'Only "%(name)s" variables are ' \
338 'supported in the patch template'
339
58c61f10
CM
340 if options.edit_cover:
341 msg_string = __edit_message(msg_string)
342
61eed152
CM
343 # The Python email message
344 try:
345 msg = email.message_from_string(msg_string)
346 except Exception, ex:
347 raise CmdException, 'template parsing error: %s' % str(ex)
348
349 __build_address_headers(msg, options)
350 __build_extra_headers(msg, msg_id, options.refid)
351 __encode_message(msg)
352
353 msg_string = msg.as_string(options.mbox)
354
61eed152 355 return msg_string.strip('\n')
b4bddc06 356
2bb96902 357def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
b4bddc06
CM
358 """Build the message to be sent via SMTP
359 """
360 p = crt_series.get_patch(patch)
361
362 descr = p.get_description().strip()
363 descr_lines = descr.split('\n')
364
365 short_descr = descr_lines[0].rstrip()
61eed152 366 long_descr = '\n'.join(descr_lines[1:]).lstrip()
b4bddc06 367
dae0f0be
CM
368 maintainer = __get_maintainer()
369 if not maintainer:
370 maintainer = '%s <%s>' % (p.get_commname(), p.get_commemail())
371
d0d139a3
CM
372 if options.version:
373 version_str = ' %s' % options.version
ed5de0cc
CM
374 else:
375 version_str = ''
d0d139a3 376
d323b5da
RR
377 if options.prefix:
378 prefix_str = options.prefix + ' '
379 else:
380 prefix_str = ''
381
b4bddc06
CM
382 total_nr_str = str(total_nr)
383 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
b8d258e5
CM
384 if total_nr > 1:
385 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
386 else:
387 number_str = ''
b4bddc06
CM
388
389 tmpl_dict = {'patch': patch,
dae0f0be 390 'maintainer': maintainer,
b4bddc06
CM
391 'shortdescr': short_descr,
392 'longdescr': long_descr,
61eed152
CM
393 # for backward template compatibility
394 'endofheaders': '',