Fixed completion function hardcoding .git/.
[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'),
c2a8af1d
CM
99 make_option('--unrelated',
100 help = 'send patches without sequence numbering',
101 action = 'store_true'),
d0d139a3
CM
102 make_option('-v', '--version', metavar = 'VERSION',
103 help = 'add VERSION to the [PATCH ...] prefix'),
d323b5da
RR
104 make_option('--prefix', metavar = 'PREFIX',
105 help = 'add PREFIX to the [... PATCH ...] prefix'),
9a316368
CM
106 make_option('-t', '--template', metavar = 'FILE',
107 help = 'use FILE as the message template'),
e3e05587
CM
108 make_option('-c', '--cover', metavar = 'FILE',
109 help = 'send FILE as the cover message'),
0ba13ee9 110 make_option('-e', '--edit-cover',
e3e05587
CM
111 help = 'edit the cover message before sending',
112 action = 'store_true'),
0ba13ee9
KH
113 make_option('-E', '--edit-patches',
114 help = 'edit each patch before sending',
115 action = 'store_true'),
b4bddc06
CM
116 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
117 help = 'sleep for SECONDS between e-mails sending'),
118 make_option('--refid',
d0d139a3 119 help = 'use REFID as the reference id'),
eb026d93
B
120 make_option('-u', '--smtp-user', metavar = 'USER',
121 help = 'username for SMTP authentication'),
122 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
2f7c8b0b
CM
123 help = 'username for SMTP authentication'),
124 make_option('-b', '--branch',
29f00589 125 help = 'use BRANCH instead of the default one'),
2ace36ab
YD
126 make_option('-O', '--diff-opts',
127 help = 'options to pass to git-diff'),
29f00589
CM
128 make_option('-m', '--mbox',
129 help = 'generate an mbox file instead of sending',
130 action = 'store_true')]
b4bddc06
CM
131
132
901288c2 133def __get_sender():
dae0f0be
CM
134 """Return the 'authname <authemail>' string as read from the
135 configuration file
136 """
c73e63b7
YD
137 sender=config.get('stgit.sender')
138 if not sender:
9e3f506f
KH
139 try:
140 sender = str(git.user())
141 except git.GitException:
142 sender = str(git.author())
143
144 if not sender:
901288c2 145 raise CmdException, 'unknown sender details'
dae0f0be 146
79df2f0d 147 return address_or_alias(sender)
9e3f506f 148
d650d6ed 149def __parse_addresses(msg):
b4bddc06
CM
150 """Return a two elements tuple: (from, [to])
151 """
d650d6ed
CM
152 def __addr_list(msg, header):
153 return [name_addr[1] for name_addr in
154 email.Utils.getaddresses(msg.get_all(header, []))]
b4bddc06 155
d650d6ed 156 from_addr_list = __addr_list(msg, 'From')
24aadb3f 157 if len(from_addr_list) == 0:
b4bddc06 158 raise CmdException, 'No "From" address'
d650d6ed
CM
159
160 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
161 + __addr_list(msg, 'Bcc')
b4bddc06
CM
162 if len(to_addr_list) == 0:
163 raise CmdException, 'No "To/Cc/Bcc" addresses'
164
165 return (from_addr_list[0], to_addr_list)
166
eb026d93
B
167def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
168 smtpuser, smtppassword):
b4bddc06
CM
169 """Send the message using the given SMTP server
170 """
171 try:
172 s = smtplib.SMTP(smtpserver)
173 except Exception, err:
174 raise CmdException, str(err)
175
176 s.set_debuglevel(0)
177 try:
eb026d93
B
178 if smtpuser and smtppassword:
179 s.ehlo()
180 s.login(smtpuser, smtppassword)
181
0bc1343c
YD
182 result = s.sendmail(from_addr, to_addr_list, msg)
183 if len(result):
184 print "mail server refused delivery for the following recipients: %s" % result
b4bddc06
CM
185 # give recipients a chance of receiving patches in the correct order
186 time.sleep(sleep)
187 except Exception, err:
188 raise CmdException, str(err)
189
190 s.quit()
191
61eed152 192def __build_address_headers(msg, options, extra_cc = []):
f8d1cf65
CM
193 """Build the address headers and check existing headers in the
194 template.
195 """
61eed152
CM
196 def __replace_header(header, addr):
197 if addr:
198 crt_addr = msg[header]
199 del msg[header]
f8d1cf65 200
61eed152 201 if crt_addr:
79df2f0d 202 msg[header] = address_or_alias(', '.join([crt_addr, addr]))
61eed152 203 else:
79df2f0d 204 msg[header] = address_or_alias(addr)
f8d1cf65 205
f8d1cf65
CM
206 to_addr = ''
207 cc_addr = ''
208 bcc_addr = ''
209
c73e63b7 210 autobcc = config.get('stgit.autobcc') or ''
d884c4d8 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
769cd397 233 r = re.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re.I)
f8d1cf65
CM
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
83bb4e4c 282 call_editor(fname)
0ba13ee9
KH
283
284 # read the message back
285 f = file(fname)
286 msg = f.read()
287 f.close()
288
289 return msg
290
e3e05587
CM
291def __build_cover(tmpl, total_nr, msg_id, options):
292 """Build the cover message (series description) to be sent via SMTP
b4bddc06 293 """
901288c2 294 sender = __get_sender()
dae0f0be 295
d0d139a3
CM
296 if options.version:
297 version_str = ' %s' % options.version
ed5de0cc
CM
298 else:
299 version_str = ''
d0d139a3 300
d323b5da
RR
301 if options.prefix:
302 prefix_str = options.prefix + ' '
303 else:
a7e0d4ee
YD
304 confprefix = config.get('stgit.mail.prefix')
305 if confprefix:
306 prefix_str = confprefix + ' '
307 else:
308 prefix_str = ''
d323b5da 309
b4bddc06 310 total_nr_str = str(total_nr)
b8d258e5
CM
311 patch_nr_str = '0'.zfill(len(total_nr_str))
312 if total_nr > 1:
313 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
314 else:
315 number_str = ''
b4bddc06 316
901288c2
CM
317 tmpl_dict = {'sender': sender,
318 # for backward template compatibility
319 'maintainer': sender,
61eed152
CM
320 # for backward template compatibility
321 'endofheaders': '',
322 # for backward template compatibility
323 'date': '',
d0d139a3 324 'version': version_str,
d323b5da 325 'prefix': prefix_str,
b8d258e5
CM
326 'patchnr': patch_nr_str,
327 'totalnr': total_nr_str,
328 'number': number_str}
b4bddc06
CM
329
330 try:
61eed152 331 msg_string = tmpl % tmpl_dict
b4bddc06
CM
332 except KeyError, err:
333 raise CmdException, 'Unknown patch template variable: %s' \
334 % err
335 except TypeError:
336 raise CmdException, 'Only "%(name)s" variables are ' \
337 'supported in the patch template'
338
58c61f10
CM
339 if options.edit_cover:
340 msg_string = __edit_message(msg_string)
341
61eed152
CM
342 # The Python email message
343 try:
344 msg = email.message_from_string(msg_string)
345 except Exception, ex:
346 raise CmdException, 'template parsing error: %s' % str(ex)
347
348 __build_address_headers(msg, options)
349 __build_extra_headers(msg, msg_id, options.refid)
350 __encode_message(msg)
351
d650d6ed 352 return msg
b4bddc06 353
2bb96902 354def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
b4bddc06
CM
355 """Build the message to be sent via SMTP
356 """
357 p = crt_series.get_patch(patch)
358
359 descr = p.get_description().strip()
360 descr_lines = descr.split('\n')
361
362 short_descr = descr_lines[0].rstrip()
61eed152 363 long_descr = '\n'.join(descr_lines[1:]).lstrip()
b4bddc06 364
1d1485c3
CM
365 authname = p.get_authname();
366 authemail = p.get_authemail();
367 commname = p.get_commname();
368 commemail = p.get_commemail();
369
901288c2 370 sender = __get_sender()
1d1485c3
CM
371
372 fromauth = '%s <%s>' % (authname, authemail)
901288c2 373 if fromauth != sender:
1d1485c3
CM
374 fromauth = 'From: %s\n\n' % fromauth
375 else:
376 fromauth = ''
dae0f0be 377
d0d139a3
CM
378 if options.version:
379 version_str = ' %s' % options.version
ed5de0cc
CM
380 else:
381 version_str = ''
d0d139a3 382
d323b5da
RR
383 if options.prefix:
384 prefix_str = options.prefix + ' '
385 else:
a7e0d4ee
YD
386 confprefix = config.get('stgit.mail.prefix')
387 if confprefix:
388 prefix_str = confprefix + ' '
389 else:
390 prefix_str = ''
d323b5da 391
2ace36ab
YD
392 if options.diff_opts:
393 diff_flags = options.diff_opts.split()
0d219030
YD
394 else:
395 diff_flags = []
396
b4bddc06
CM
397 total_nr_str = str(total_nr)
398 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
c2a8af1d 399 if not options.unrelated and total_nr > 1:
b8d258e5
CM
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': '',