Specify a different base for the imported patch
[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
18import sys, os, re, time, smtplib, email.Utils
19from optparse import OptionParser, make_option
20from time import gmtime, strftime
21
22from stgit.commands.common import *
23from stgit.utils import *
24from stgit import stack, git
25from stgit.config import config
26
27
28help = 'send a patch or series of patches by e-mail'
ddab48a5 29usage = """%prog [options] [<patch> [<patch2...]]
26aab5b0
CM
30
31Send a patch or a range of patches (defaulting to the applied patches)
2bb96902
CM
32by e-mail using the 'smtpserver' configuration option. The From
33address and the e-mail format are generated from the template file
34passed as argument to '--template' (defaulting to .git/patchmail.tmpl
35or /usr/share/stgit/templates/patchmail.tmpl). The To/Cc/Bcc addresses
36can either be added to the template file or passed via the
37corresponding command line options.
38
39A preamble e-mail can be sent using the '--first' option. All the
40subsequent e-mails appear as replies to the first e-mail sent (either
41the preamble or the first patch). E-mails can be seen as replies to a
42different e-mail by using the '--refid' option.
26aab5b0
CM
43
44SMTP authentication is also possible with '--smtp-user' and
45'--smtp-password' options, also available as configuration settings:
46'smtpuser' and 'smtppassword'.
47
48The template e-mail headers and body must be separated by
49'%(endofheaders)s' variable, which is replaced by StGIT with
50additional headers and a blank line. The patch e-mail template accepts
51the following variables:
52
53 %(patch)s - patch name
dae0f0be 54 %(maintainer)s - 'authname <authemail>' as read from the config file
26aab5b0
CM
55 %(shortdescr)s - the first line of the patch description
56 %(longdescr)s - the rest of the patch description, after the first line
57 %(endofheaders)s - delimiter between e-mail headers and body
58 %(diff)s - unified diff of the patch
59 %(diffstat)s - diff statistics
60 %(date)s - current date/time
d0d139a3 61 %(version)s - ' version' string passed on the command line (or empty)
26aab5b0
CM
62 %(patchnr)s - patch number
63 %(totalnr)s - total number of patches to be sent
b8d258e5 64 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
26aab5b0
CM
65 %(authname)s - author's name
66 %(authemail)s - author's email
67 %(authdate)s - patch creation date
68 %(commname)s - committer's name
69 %(commemail)s - committer's e-mail
70
dae0f0be 71For the preamble e-mail template, only the %(maintainer)s, %(date)s,
d0d139a3
CM
72%(endofheaders)s, %(version)s, %(patchnr)s, %(totalnr)s and %(number)s
73variables are supported."""
b4bddc06 74
9a316368
CM
75options = [make_option('-a', '--all',
76 help = 'e-mail all the applied patches',
77 action = 'store_true'),
b4bddc06
CM
78 make_option('-r', '--range',
79 metavar = '[PATCH1][:[PATCH2]]',
80 help = 'e-mail patches between PATCH1 and PATCH2'),
2bb96902 81 make_option('--to',
d0d139a3 82 help = 'add TO to the To: list'),
2bb96902 83 make_option('--cc',
d0d139a3 84 help = 'add CC to the Cc: list'),
2bb96902 85 make_option('--bcc',
d0d139a3
CM
86 help = 'add BCC to the Bcc: list'),
87 make_option('-v', '--version', metavar = 'VERSION',
88 help = 'add VERSION to the [PATCH ...] prefix'),
9a316368
CM
89 make_option('-t', '--template', metavar = 'FILE',
90 help = 'use FILE as the message template'),
b4bddc06
CM
91 make_option('-f', '--first', metavar = 'FILE',
92 help = 'send FILE as the first message'),
93 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
94 help = 'sleep for SECONDS between e-mails sending'),
95 make_option('--refid',
d0d139a3 96 help = 'use REFID as the reference id'),
eb026d93
B
97 make_option('-u', '--smtp-user', metavar = 'USER',
98 help = 'username for SMTP authentication'),
99 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
2f7c8b0b
CM
100 help = 'username for SMTP authentication'),
101 make_option('-b', '--branch',
102 help = 'use BRANCH instead of the default one')]
b4bddc06
CM
103
104
dae0f0be
CM
105def __get_maintainer():
106 """Return the 'authname <authemail>' string as read from the
107 configuration file
108 """
109 if config.has_option('stgit', 'authname') \
110 and config.has_option('stgit', 'authemail'):
111 return '%s <%s>' % (config.get('stgit', 'authname'),
112 config.get('stgit', 'authemail'))
113 else:
114 return None
115
b4bddc06
CM
116def __parse_addresses(string):
117 """Return a two elements tuple: (from, [to])
118 """
119 def __addr_list(string):
e190e1a6 120 return re.split('.*?([-\w\.]+@[-\w\.]+)', string)[1:-1:2]
b4bddc06
CM
121
122 from_addr_list = []
123 to_addr_list = []
124 for line in string.split('\n'):
125 if re.match('from:\s+', line, re.I):
126 from_addr_list += __addr_list(line)
127 elif re.match('(to|cc|bcc):\s+', line, re.I):
128 to_addr_list += __addr_list(line)
129
24aadb3f 130 if len(from_addr_list) == 0:
b4bddc06
CM
131 raise CmdException, 'No "From" address'
132 if len(to_addr_list) == 0:
133 raise CmdException, 'No "To/Cc/Bcc" addresses'
134
135 return (from_addr_list[0], to_addr_list)
136
eb026d93
B
137def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
138 smtpuser, smtppassword):
b4bddc06
CM
139 """Send the message using the given SMTP server
140 """
141 try:
142 s = smtplib.SMTP(smtpserver)
143 except Exception, err:
144 raise CmdException, str(err)
145
146 s.set_debuglevel(0)
147 try:
eb026d93
B
148 if smtpuser and smtppassword:
149 s.ehlo()
150 s.login(smtpuser, smtppassword)
151
b4bddc06
CM
152 s.sendmail(from_addr, to_addr_list, msg)
153 # give recipients a chance of receiving patches in the correct order
154 time.sleep(sleep)
155 except Exception, err:
156 raise CmdException, str(err)
157
158 s.quit()
159
2bb96902 160def __build_first(tmpl, total_nr, msg_id, options):
b4bddc06
CM
161 """Build the first message (series description) to be sent via SMTP
162 """
dae0f0be
CM
163 maintainer = __get_maintainer()
164 if not maintainer:
165 maintainer = ''
166
2bb96902
CM
167 headers_end = ''
168 if options.to:
169 headers_end += 'To: %s\n' % options.to
170 if options.cc:
171 headers_end += 'Cc: %s\n' % options.cc
172 if options.bcc:
173 headers_end += 'Bcc: %s\n' % options.bcc
174 headers_end += 'Message-Id: %s\n' % msg_id
175
d0d139a3
CM
176 if options.version:
177 version_str = ' %s' % options.version
178
b4bddc06 179 total_nr_str = str(total_nr)
b8d258e5
CM
180 patch_nr_str = '0'.zfill(len(total_nr_str))
181 if total_nr > 1:
182 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
183 else:
184 number_str = ''
b4bddc06 185
dae0f0be
CM
186 tmpl_dict = {'maintainer': maintainer,
187 'endofheaders': headers_end,
b4bddc06 188 'date': email.Utils.formatdate(localtime = True),
d0d139a3 189 'version': version_str,
b8d258e5
CM
190 'patchnr': patch_nr_str,
191 'totalnr': total_nr_str,
192 'number': number_str}
b4bddc06
CM
193
194 try:
195 msg = tmpl % tmpl_dict
196 except KeyError, err:
197 raise CmdException, 'Unknown patch template variable: %s' \
198 % err
199 except TypeError:
200 raise CmdException, 'Only "%(name)s" variables are ' \
201 'supported in the patch template'
202
203 return msg
204
2bb96902 205def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
b4bddc06
CM
206 """Build the message to be sent via SMTP
207 """
208 p = crt_series.get_patch(patch)
209
210 descr = p.get_description().strip()
211 descr_lines = descr.split('\n')
212
213 short_descr = descr_lines[0].rstrip()
214 long_descr = reduce(lambda x, y: x + '\n' + y,
215 descr_lines[1:], '').lstrip()
216
dae0f0be
CM
217 maintainer = __get_maintainer()
218 if not maintainer:
219 maintainer = '%s <%s>' % (p.get_commname(), p.get_commemail())
220
2bb96902
CM
221 headers_end = ''
222 if options.to:
223 headers_end += 'To: %s\n' % options.to
224 if options.cc:
225 headers_end += 'Cc: %s\n' % options.cc
226 if options.bcc:
227 headers_end += 'Bcc: %s\n' % options.bcc
228 headers_end += 'Message-Id: %s\n' % msg_id
b4bddc06 229 if ref_id:
2bb96902
CM
230 headers_end += "In-Reply-To: %s\n" % ref_id
231 headers_end += "References: %s\n" % ref_id
b4bddc06 232
d0d139a3
CM
233 if options.version:
234 version_str = ' %s' % options.version
235
b4bddc06
CM
236 total_nr_str = str(total_nr)
237 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
b8d258e5
CM
238 if total_nr > 1:
239 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
240 else:
241 number_str = ''
b4bddc06
CM
242
243 tmpl_dict = {'patch': patch,
dae0f0be 244 'maintainer': maintainer,
b4bddc06
CM
245 'shortdescr': short_descr,
246 'longdescr': long_descr,
247 'endofheaders': headers_end,
248 'diff': git.diff(rev1 = git_id('%s/bottom' % patch),
249 rev2 = git_id('%s/top' % patch)),
250 'diffstat': git.diffstat(rev1 = git_id('%s/bottom'%patch),
251 rev2 = git_id('%s/top' % patch)),
252 'date': email.Utils.formatdate(localtime = True),
d0d139a3 253 'version': version_str,
b4bddc06
CM
254 'patchnr': patch_nr_str,
255 'totalnr': total_nr_str,
b8d258e5 256 'number': number_str,
b4bddc06
CM
257 'authname': p.get_authname(),
258 'authemail': p.get_authemail(),
259 'authdate': p.get_authdate(),
260 'commname': p.get_commname(),
261 'commemail': p.get_commemail()}
262 for key in tmpl_dict:
263 if not tmpl_dict[key]:
264 tmpl_dict[key] = ''
265
266 try:
267 msg = tmpl % tmpl_dict
268 except KeyError, err:
269 raise CmdException, 'Unknown patch template variable: %s' \
270 % err
271 except TypeError:
272 raise CmdException, 'Only "%(name)s" variables are ' \
273 'supported in the patch template'
274
275 return msg
276
b4bddc06
CM
277def func(parser, options, args):
278 """Send the patches by e-mail using the patchmail.tmpl file as
279 a template
280 """
b4bddc06
CM
281 if not config.has_option('stgit', 'smtpserver'):
282 raise CmdException, 'smtpserver not defined'
283 smtpserver = config.get('stgit', 'smtpserver')
284
eb026d93
B
285 smtpuser = None
286 smtppassword = None
287 if config.has_option('stgit', 'smtpuser'):
288 smtpuser = config.get('stgit', 'smtpuser')
289 if config.has_option('stgit', 'smtppassword'):
290 smtppassword = config.get('stgit', 'smtppassword')
291
b4bddc06
CM
292 applied = crt_series.get_applied()
293
ddab48a5
PBG
294 if len(args) >= 1:
295 for patch in args:
296 if not patch in applied:
297 raise CmdException, 'Patch "%s" not applied' % patch
298 patches = args
9a316368
CM
299 elif options.all:
300 patches = applied
301 elif options.range:
b4bddc06
CM
302 boundaries = options.range.split(':')
303 if len(boundaries) == 1:
304 start = boundaries[0]
305 stop = boundaries[0]
306 elif len(boundaries) == 2:
307 if boundaries[0] == '':
308 start = applied[0]
309 else:
310 start = boundaries[0]
311 if boundaries[1] == '':
312 stop = applied[-1]
313 else:
314 stop = boundaries[1]
315 else:
316 raise CmdException, 'incorrect parameters to "--range"'
317
318 if start in applied:
319 start_idx = applied.index(start)
320 else:
321 raise CmdException, 'Patch "%s" not applied' % start
322 if stop in applied:
323 stop_idx = applied.index(stop) + 1
324 else:
325 raise CmdException, 'Patch "%s" not applied' % stop
326
327 if start_idx >= stop_idx:
328 raise CmdException, 'Incorrect patch range order'
9a316368
CM
329
330 patches = applied[start_idx:stop_idx]
b4bddc06 331 else:
9a316368 332 raise CmdException, 'Incorrect options. Unknown patches to send'
b4bddc06 333
eb026d93
B
334 if options.smtp_password:
335 smtppassword = options.smtp_password
336
337 if options.smtp_user:
338 smtpuser = options.smtp_user
339
340 if (smtppassword and not smtpuser):
341 raise CmdException, 'SMTP password supplied, username needed'
342 if (smtpuser and not smtppassword):
343 raise CmdException, 'SMTP username supplied, password needed'
344
b4bddc06 345 total_nr = len(patches)
9a316368
CM
346 if total_nr == 0:
347 raise CmdException, 'No patches to send'
b4bddc06
CM
348
349 ref_id = options.refid
350
351 if options.sleep != None:
352 sleep = options.sleep
353 else:
354 sleep = 2
355
356 # send the first message (if any)
357 if options.first:
358 tmpl = file(options.first).read()
b4bddc06
CM
359
360 msg_id = email.Utils.make_msgid('stgit')
2bb96902
CM
361 msg = __build_first(tmpl, total_nr, msg_id, options)
362 from_addr, to_addr_list = __parse_addresses(msg)
b4bddc06
CM
363
364 # subsequent e-mails are seen as replies to the first one
365 ref_id = msg_id
366
367 print 'Sending file "%s"...' % options.first,
368 sys.stdout.flush()
369
eb026d93
B
370 __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
371 smtpuser, smtppassword)
b4bddc06
CM
372
373 print 'done'
374
375 # send the patches
376 if options.template:
2bb96902 377 tfile_list = [options.template]
b4bddc06 378 else:
2bb96902
CM
379 tfile_list = []
380
381 tfile_list += [os.path.join(git.base_dir, 'patchmail.tmpl'),
382 os.path.join(sys.prefix,
383 'share/stgit/templates/patchmail.tmpl')]
384 tmpl = None
385 for tfile in tfile_list:
386 if os.path.isfile(tfile):
387 tmpl = file(tfile).read()
388 break
389 if not tmpl:
390 raise CmdException, 'No e-mail template file: %s or %s' \
391 % (tfile_list[-1], tfile_list[-2])
b4bddc06
CM
392
393 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
394 msg_id = email.Utils.make_msgid('stgit')
2bb96902
CM
395 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
396 options)
397 from_addr, to_addr_list = __parse_addresses(msg)
398
b4bddc06
CM
399 # subsequent e-mails are seen as replies to the first one
400 if not ref_id:
401 ref_id = msg_id
402
403 print 'Sending patch "%s"...' % p,
404 sys.stdout.flush()
405
eb026d93
B
406 __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
407 smtpuser, smtppassword)
b4bddc06
CM
408
409 print 'done'