'sync' code comments clean-up after commit 6b79a09c
[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
79df2f0d
CM
35'~/.stgit/templates/patchmail.tmpl' or
36'/usr/share/stgit/templates/patchmail.tmpl').
37
38The To/Cc/Bcc addresses can either be added to the template file or
39passed via the corresponding command line options. They can be e-mail
40addresses or aliases which are automatically expanded to the values
41stored in the [mail "alias"] section of GIT configuration files.
2bb96902 42
0ba13ee9
KH
43A preamble e-mail can be sent using the '--cover' and/or
44'--edit-cover' options. The first allows the user to specify a file to
45be used as a template. The latter option will invoke the editor on the
46specified file (defaulting to '.git/covermail.tmpl' or
94d18868
YD
47'~/.stgit/templates/covermail.tmpl' or
48'/usr/share/stgit/templates/covermail.tmpl').
e3e05587
CM
49
50All the subsequent e-mails appear as replies to the first e-mail sent
51(either the preamble or the first patch). E-mails can be seen as
52replies to a different e-mail by using the '--refid' option.
26aab5b0
CM
53
54SMTP authentication is also possible with '--smtp-user' and
55'--smtp-password' options, also available as configuration settings:
56'smtpuser' and 'smtppassword'.
57
e5bdb1fe 58The patch e-mail template accepts the following variables:
26aab5b0
CM
59
60 %(patch)s - patch name
901288c2 61 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
26aab5b0
CM
62 %(shortdescr)s - the first line of the patch description
63 %(longdescr)s - the rest of the patch description, after the first line
26aab5b0
CM
64 %(diff)s - unified diff of the patch
65 %(diffstat)s - diff statistics
d0d139a3 66 %(version)s - ' version' string passed on the command line (or empty)
d323b5da 67 %(prefix)s - 'prefix ' string passed on the command line
26aab5b0
CM
68 %(patchnr)s - patch number
69 %(totalnr)s - total number of patches to be sent
b8d258e5 70 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
901288c2 71 %(fromauth)s - 'From: author\\n\\n' if different from sender
26aab5b0
CM
72 %(authname)s - author's name
73 %(authemail)s - author's email
74 %(authdate)s - patch creation date
75 %(commname)s - committer's name
76 %(commemail)s - committer's e-mail
77
901288c2
CM
78For the preamble e-mail template, only the %(sender)s, %(version)s,
79%(patchnr)s, %(totalnr)s and %(number)s variables are supported."""
b4bddc06 80
9a316368
CM
81options = [make_option('-a', '--all',
82 help = 'e-mail all the applied patches',
83 action = 'store_true'),
2bb96902 84 make_option('--to',
e83b3149
PO
85 help = 'add TO to the To: list',
86 action = 'append'),
2bb96902 87 make_option('--cc',
e83b3149
PO
88 help = 'add CC to the Cc: list',
89 action = 'append'),
2bb96902 90 make_option('--bcc',
e83b3149
PO
91 help = 'add BCC to the Bcc: list',
92 action = 'append'),
f8d1cf65
CM
93 make_option('--auto',
94 help = 'automatically cc the patch signers',
95 action = 'store_true'),
d1ed3a12
CM
96 make_option('--noreply',
97 help = 'do not send subsequent messages as replies',
98 action = 'store_true'),
d0d139a3
CM
99 make_option('-v', '--version', metavar = 'VERSION',
100 help = 'add VERSION to the [PATCH ...] prefix'),
d323b5da
RR
101 make_option('--prefix', metavar = 'PREFIX',
102 help = 'add PREFIX to the [... PATCH ...] prefix'),
9a316368
CM
103 make_option('-t', '--template', metavar = 'FILE',
104 help = 'use FILE as the message template'),
e3e05587
CM
105 make_option('-c', '--cover', metavar = 'FILE',
106 help = 'send FILE as the cover message'),
0ba13ee9 107 make_option('-e', '--edit-cover',
e3e05587
CM
108 help = 'edit the cover message before sending',
109 action = 'store_true'),
0ba13ee9
KH
110 make_option('-E', '--edit-patches',
111 help = 'edit each patch before sending',
112 action = 'store_true'),
b4bddc06
CM
113 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
114 help = 'sleep for SECONDS between e-mails sending'),
115 make_option('--refid',
d0d139a3 116 help = 'use REFID as the reference id'),
eb026d93
B
117 make_option('-u', '--smtp-user', metavar = 'USER',
118 help = 'username for SMTP authentication'),
119 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
2f7c8b0b
CM
120 help = 'username for SMTP authentication'),
121 make_option('-b', '--branch',
29f00589 122 help = 'use BRANCH instead of the default one'),
2ace36ab
YD
123 make_option('-O', '--diff-opts',
124 help = 'options to pass to git-diff'),
29f00589
CM
125 make_option('-m', '--mbox',
126 help = 'generate an mbox file instead of sending',
127 action = 'store_true')]
b4bddc06
CM
128
129
901288c2 130def __get_sender():
dae0f0be
CM
131 """Return the 'authname <authemail>' string as read from the
132 configuration file
133 """
c73e63b7
YD
134 sender=config.get('stgit.sender')
135 if not sender:
9e3f506f
KH
136 try:
137 sender = str(git.user())
138 except git.GitException:
139 sender = str(git.author())
140
141 if not sender:
901288c2 142 raise CmdException, 'unknown sender details'
dae0f0be 143
79df2f0d 144 return address_or_alias(sender)
9e3f506f 145
d650d6ed 146def __parse_addresses(msg):
b4bddc06
CM
147 """Return a two elements tuple: (from, [to])
148 """
d650d6ed
CM
149 def __addr_list(msg, header):
150 return [name_addr[1] for name_addr in
151 email.Utils.getaddresses(msg.get_all(header, []))]
b4bddc06 152
d650d6ed 153 from_addr_list = __addr_list(msg, 'From')
24aadb3f 154 if len(from_addr_list) == 0:
b4bddc06 155 raise CmdException, 'No "From" address'
d650d6ed
CM
156
157 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
158 + __addr_list(msg, 'Bcc')
b4bddc06
CM
159 if len(to_addr_list) == 0:
160 raise CmdException, 'No "To/Cc/Bcc" addresses'
161
162 return (from_addr_list[0], to_addr_list)
163
eb026d93
B
164def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
165 smtpuser, smtppassword):
b4bddc06
CM
166 """Send the message using the given SMTP server
167 """
168 try:
169 s = smtplib.SMTP(smtpserver)
170 except Exception, err:
171 raise CmdException, str(err)
172
173 s.set_debuglevel(0)
174 try:
eb026d93
B
175 if smtpuser and smtppassword:
176 s.ehlo()
177 s.login(smtpuser, smtppassword)
178
b4bddc06
CM
179 s.sendmail(from_addr, to_addr_list, msg)
180 # give recipients a chance of receiving patches in the correct order
181 time.sleep(sleep)
182 except Exception, err:
183 raise CmdException, str(err)
184
185 s.quit()
186
61eed152 187def __build_address_headers(msg, options, extra_cc = []):
f8d1cf65
CM
188 """Build the address headers and check existing headers in the
189 template.
190 """
61eed152
CM
191 def __replace_header(header, addr):
192 if addr:
193 crt_addr = msg[header]
194 del msg[header]
f8d1cf65 195
61eed152 196 if crt_addr:
79df2f0d 197 msg[header] = address_or_alias(', '.join([crt_addr, addr]))
61eed152 198 else:
79df2f0d 199 msg[header] = address_or_alias(addr)
f8d1cf65 200
f8d1cf65
CM
201 to_addr = ''
202 cc_addr = ''
203 bcc_addr = ''
204
c73e63b7 205 autobcc = config.get('stgit.autobcc') or ''
d884c4d8 206
e83b3149 207 if options.to:
61eed152 208 to_addr = ', '.join(options.to)
e83b3149 209 if options.cc:
61eed152 210 cc_addr = ', '.join(options.cc + extra_cc)
f8d1cf65 211 elif extra_cc:
61eed152 212 cc_addr = ', '.join(extra_cc)
e83b3149 213 if options.bcc:
61eed152 214 bcc_addr = ', '.join(options.bcc + [autobcc])
d884c4d8
CM
215 elif autobcc:
216 bcc_addr = autobcc
f8d1cf65 217
61eed152
CM
218 __replace_header('To', to_addr)
219 __replace_header('Cc', cc_addr)
220 __replace_header('Bcc', bcc_addr)
f8d1cf65
CM
221
222def __get_signers_list(msg):
223 """Return the address list generated from signed-off-by and
224 acked-by lines in the message.
225 """
226 addr_list = []
227
769cd397 228 r = re.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re.I)
f8d1cf65
CM
229 for line in msg.split('\n'):
230 m = r.match(line)
231 if m:
232 addr_list.append(m.expand('\g<2>'))
233
234 return addr_list
e83b3149 235
61eed152
CM
236def __build_extra_headers(msg, msg_id, ref_id = None):
237 """Build extra email headers and encoding
19a56fa1 238 """
61eed152
CM
239 del msg['Date']
240 msg['Date'] = email.Utils.formatdate(localtime = True)
241 msg['Message-ID'] = msg_id
242 if ref_id:
243 msg['In-Reply-To'] = ref_id
244 msg['References'] = ref_id
245 msg['User-Agent'] = 'StGIT/%s' % version.version
246
247def __encode_message(msg):
248 # 7 or 8 bit encoding
249 charset = email.Charset.Charset('utf-8')
250 charset.body_encoding = None
251
252 # encode headers
253 for header, value in msg.items():
254 words = []
255 for word in value.split(' '):
256 try:
257 uword = unicode(word, 'utf-8')
258 except UnicodeDecodeError:
259 # maybe we should try a different encoding or report
260 # the error. At the moment, we just ignore it
261 pass
262 words.append(email.Header.Header(uword).encode())
263 new_val = ' '.join(words)
264 msg.replace_header(header, new_val)
265
266 # encode the body and set the MIME and encoding headers
267 msg.set_charset(charset)
19a56fa1 268
58c61f10 269def __edit_message(msg):
0ba13ee9
KH
270 fname = '.stgitmail.txt'
271
272 # create the initial file
273 f = file(fname, 'w')
274 f.write(msg)
275 f.close()
276
83bb4e4c 277 call_editor(fname)
0ba13ee9
KH
278
279 # read the message back
280 f = file(fname)
281 msg = f.read()
282 f.close()
283
284 return msg
285
e3e05587
CM
286def __build_cover(tmpl, total_nr, msg_id, options):
287 """Build the cover message (series description) to be sent via SMTP
b4bddc06 288 """
901288c2 289 sender = __get_sender()
dae0f0be 290
d0d139a3
CM
291 if options.version:
292 version_str = ' %s' % options.version
ed5de0cc
CM
293 else:
294 version_str = ''
d0d139a3 295
d323b5da
RR
296 if options.prefix:
297 prefix_str = options.prefix + ' '
298 else:
a7e0d4ee
YD
299 confprefix = config.get('stgit.mail.prefix')
300 if confprefix:
301 prefix_str = confprefix + ' '
302 else:
303 prefix_str = ''
d323b5da 304
b4bddc06 305 total_nr_str = str(total_nr)
b8d258e5
CM
306 patch_nr_str = '0'.zfill(len(total_nr_str))
307 if total_nr > 1:
308 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
309 else:
310 number_str = ''
b4bddc06 311
901288c2
CM
312 tmpl_dict = {'sender': sender,
313 # for backward template compatibility
314 'maintainer': sender,
61eed152
CM
315 # for backward template compatibility
316 'endofheaders': '',
317 # for backward template compatibility
318 'date': '',
d0d139a3 319 'version': version_str,
d323b5da 320 'prefix': prefix_str,
b8d258e5
CM
321 'patchnr': patch_nr_str,
322 'totalnr': total_nr_str,
323 'number': number_str}
b4bddc06
CM
324
325 try:
61eed152 326 msg_string = tmpl % tmpl_dict
b4bddc06
CM
327 except KeyError, err:
328 raise CmdException, 'Unknown patch template variable: %s' \
329 % err
330 except TypeError:
331 raise CmdException, 'Only "%(name)s" variables are ' \
332 'supported in the patch template'
333
58c61f10
CM
334 if options.edit_cover:
335 msg_string = __edit_message(msg_string)
336
61eed152
CM
337 # The Python email message
338 try:
339 msg = email.message_from_string(msg_string)
340 except Exception, ex:
341 raise CmdException, 'template parsing error: %s' % str(ex)
342
343 __build_address_headers(msg, options)
344 __build_extra_headers(msg, msg_id, options.refid)
345 __encode_message(msg)
346
d650d6ed 347 return msg
b4bddc06 348
2bb96902 349def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
b4bddc06
CM
350 """Build the message to be sent via SMTP
351 """
352 p = crt_series.get_patch(patch)
353
354 descr = p.get_description().strip()
355 descr_lines = descr.split('\n')
356
357 short_descr = descr_lines[0].rstrip()
61eed152 358 long_descr = '\n'.join(descr_lines[1:]).lstrip()
b4bddc06 359
1d1485c3
CM
360 authname = p.get_authname();
361 authemail = p.get_authemail();
362 commname = p.get_commname();
363 commemail = p.get_commemail();
364
901288c2 365 sender = __get_sender()
1d1485c3
CM
366
367 fromauth = '%s <%s>' % (authname, authemail)
901288c2 368 if fromauth != sender:
1d1485c3
CM
369 fromauth = 'From: %s\n\n' % fromauth
370 else:
371 fromauth = ''
dae0f0be 372
d0d139a3
CM
373 if options.version:
374 version_str = ' %s' % options.version
ed5de0cc
CM
375 else:
376 version_str = ''
d0d139a3 377
d323b5da
RR
378 if options.prefix:
379 prefix_str = options.prefix + ' '
380 else:
a7e0d4ee
YD
381 confprefix = config.get('stgit.mail.prefix')
382 if confprefix:
383 prefix_str = confprefix + ' '
384 else:
385 prefix_str = ''
d323b5da 386
2ace36ab
YD
387 if options.diff_opts:
388 diff_flags = options.diff_opts.split()
0d219030
YD
389 else:
390 diff_flags = []
391
b4bddc06
CM
392 total_nr_str = str(total_nr)
393 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
b8d258e5
CM
394 if total_nr > 1:
395 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
396 else:
397 number_str = ''
b4bddc06
CM
398
399 tmpl_dict = {'patch': patch,
901288c2
CM
400 'sender': sender,
401 # for backward template compatibility
402 'maintainer': sender,
b4bddc06
CM
403 'shortdescr': short_descr,
404 'longdescr': long_descr,
61eed152
CM
405 # for backward template compatibility
406 'endofheaders': '',