Create stgit/basedir.py for determining the .git directory
[stgit] / stgit / commands / mail.py
1 __copyright__ = """
2 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License version 2 as
6 published by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 """
17
18 import sys, os, re, time, datetime, smtplib, email.Utils
19 from optparse import OptionParser, make_option
20
21 from stgit.commands.common import *
22 from stgit.utils import *
23 from stgit import stack, git, basedir
24 from stgit.config import config
25
26
27 help = 'send a patch or series of patches by e-mail'
28 usage = """%prog [options] [<patch> [<patch2...]]
29
30 Send a patch or a range of patches (defaulting to the applied patches)
31 by e-mail using the 'smtpserver' configuration option. The From
32 address and the e-mail format are generated from the template file
33 passed as argument to '--template' (defaulting to .git/patchmail.tmpl
34 or /usr/share/stgit/templates/patchmail.tmpl). The To/Cc/Bcc addresses
35 can either be added to the template file or passed via the
36 corresponding command line options.
37
38 A preamble e-mail can be sent using the '--cover' and/or '--edit'
39 options. The first allows the user to specify a file to be used as a
40 template. The latter option will invoke the editor on the specified
41 file (defaulting to .git/covermail.tmpl or
42 /usr/share/stgit/templates/covermail.tmpl).
43
44 All the subsequent e-mails appear as replies to the first e-mail sent
45 (either the preamble or the first patch). E-mails can be seen as
46 replies to a different e-mail by using the '--refid' option.
47
48 SMTP authentication is also possible with '--smtp-user' and
49 '--smtp-password' options, also available as configuration settings:
50 'smtpuser' and 'smtppassword'.
51
52 The template e-mail headers and body must be separated by
53 '%(endofheaders)s' variable, which is replaced by StGIT with
54 additional headers and a blank line. The patch e-mail template accepts
55 the following variables:
56
57 %(patch)s - patch name
58 %(maintainer)s - 'authname <authemail>' as read from the config file
59 %(shortdescr)s - the first line of the patch description
60 %(longdescr)s - the rest of the patch description, after the first line
61 %(endofheaders)s - delimiter between e-mail headers and body
62 %(diff)s - unified diff of the patch
63 %(diffstat)s - diff statistics
64 %(date)s - current date/time
65 %(version)s - ' version' string passed on the command line (or empty)
66 %(patchnr)s - patch number
67 %(totalnr)s - total number of patches to be sent
68 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
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
75 For the preamble e-mail template, only the %(maintainer)s, %(date)s,
76 %(endofheaders)s, %(version)s, %(patchnr)s, %(totalnr)s and %(number)s
77 variables are supported."""
78
79 options = [make_option('-a', '--all',
80 help = 'e-mail all the applied patches',
81 action = 'store_true'),
82 make_option('-r', '--range',
83 metavar = '[PATCH1][:[PATCH2]]',
84 help = 'e-mail patches between PATCH1 and PATCH2'),
85 make_option('--to',
86 help = 'add TO to the To: list',
87 action = 'append'),
88 make_option('--cc',
89 help = 'add CC to the Cc: list',
90 action = 'append'),
91 make_option('--bcc',
92 help = 'add BCC to the Bcc: list',
93 action = 'append'),
94 make_option('-v', '--version', metavar = 'VERSION',
95 help = 'add VERSION to the [PATCH ...] prefix'),
96 make_option('-t', '--template', metavar = 'FILE',
97 help = 'use FILE as the message template'),
98 make_option('-c', '--cover', metavar = 'FILE',
99 help = 'send FILE as the cover message'),
100 make_option('-e', '--edit',
101 help = 'edit the cover message before sending',
102 action = 'store_true'),
103 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
104 help = 'sleep for SECONDS between e-mails sending'),
105 make_option('--refid',
106 help = 'use REFID as the reference id'),
107 make_option('-u', '--smtp-user', metavar = 'USER',
108 help = 'username for SMTP authentication'),
109 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
110 help = 'username for SMTP authentication'),
111 make_option('-b', '--branch',
112 help = 'use BRANCH instead of the default one'),
113 make_option('-m', '--mbox',
114 help = 'generate an mbox file instead of sending',
115 action = 'store_true')]
116
117
118 def __get_maintainer():
119 """Return the 'authname <authemail>' string as read from the
120 configuration file
121 """
122 if config.has_option('stgit', 'authname') \
123 and config.has_option('stgit', 'authemail'):
124 return '%s <%s>' % (config.get('stgit', 'authname'),
125 config.get('stgit', 'authemail'))
126 else:
127 return None
128
129 def __parse_addresses(addresses):
130 """Return a two elements tuple: (from, [to])
131 """
132 def __addr_list(addrs):
133 m = re.search('[^@\s<,]+@[^>\s,]+', addrs);
134 if (m == None):
135 return []
136 return [ m.group() ] + __addr_list(addrs[m.end():])
137
138 from_addr_list = []
139 to_addr_list = []
140 for line in addresses.split('\n'):
141 if re.match('from:\s+', line, re.I):
142 from_addr_list += __addr_list(line)
143 elif re.match('(to|cc|bcc):\s+', line, re.I):
144 to_addr_list += __addr_list(line)
145
146 if len(from_addr_list) == 0:
147 raise CmdException, 'No "From" address'
148 if len(to_addr_list) == 0:
149 raise CmdException, 'No "To/Cc/Bcc" addresses'
150
151 return (from_addr_list[0], to_addr_list)
152
153 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
154 smtpuser, smtppassword):
155 """Send the message using the given SMTP server
156 """
157 try:
158 s = smtplib.SMTP(smtpserver)
159 except Exception, err:
160 raise CmdException, str(err)
161
162 s.set_debuglevel(0)
163 try:
164 if smtpuser and smtppassword:
165 s.ehlo()
166 s.login(smtpuser, smtppassword)
167
168 s.sendmail(from_addr, to_addr_list, msg)
169 # give recipients a chance of receiving patches in the correct order
170 time.sleep(sleep)
171 except Exception, err:
172 raise CmdException, str(err)
173
174 s.quit()
175
176 def __write_mbox(from_addr, msg):
177 """Write an mbox like file to the standard output
178 """
179 r = re.compile('^From ', re.M)
180 msg = r.sub('>\g<0>', msg)
181
182 print 'From %s %s' % (from_addr, datetime.datetime.today().ctime())
183 print msg
184 print
185
186 def __build_address_headers(options):
187 headers_end = ''
188 if options.to:
189 headers_end += 'To: '
190 for to in options.to:
191 headers_end += '%s, ' % to
192 headers_end = headers_end[:-2] + '\n'
193 if options.cc:
194 headers_end += 'Cc: '
195 for cc in options.cc:
196 headers_end += '%s, ' % cc
197 headers_end = headers_end[:-2] + '\n'
198 if options.bcc:
199 headers_end += 'Bcc: '
200 for bcc in options.bcc:
201 headers_end += '%s, ' % bcc
202 headers_end = headers_end[:-2] + '\n'
203 return headers_end
204
205 def __build_cover(tmpl, total_nr, msg_id, options):
206 """Build the cover message (series description) to be sent via SMTP
207 """
208 maintainer = __get_maintainer()
209 if not maintainer:
210 maintainer = ''
211
212 headers_end = __build_address_headers(options)
213 headers_end += 'Message-Id: %s\n' % msg_id
214 if options.refid:
215 headers_end += "In-Reply-To: %s\n" % options.refid
216 headers_end += "References: %s\n" % options.refid
217
218 if options.version:
219 version_str = ' %s' % options.version
220 else:
221 version_str = ''
222
223 total_nr_str = str(total_nr)
224 patch_nr_str = '0'.zfill(len(total_nr_str))
225 if total_nr > 1:
226 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
227 else:
228 number_str = ''
229
230 tmpl_dict = {'maintainer': maintainer,
231 'endofheaders': headers_end,
232 'date': email.Utils.formatdate(localtime = True),
233 'version': version_str,
234 'patchnr': patch_nr_str,
235 'totalnr': total_nr_str,
236 'number': number_str}
237
238 try:
239 msg = tmpl % tmpl_dict
240 except KeyError, err:
241 raise CmdException, 'Unknown patch template variable: %s' \
242 % err
243 except TypeError:
244 raise CmdException, 'Only "%(name)s" variables are ' \
245 'supported in the patch template'
246
247 if options.edit:
248 fname = '.stgitmail.txt'
249
250 # create the initial file
251 f = file(fname, 'w+')
252 f.write(msg)
253 f.close()
254
255 # the editor
256 if config.has_option('stgit', 'editor'):
257 editor = config.get('stgit', 'editor')
258 elif 'EDITOR' in os.environ:
259 editor = os.environ['EDITOR']
260 else:
261 editor = 'vi'
262 editor += ' %s' % fname
263
264 print 'Invoking the editor: "%s"...' % editor,
265 sys.stdout.flush()
266 print 'done (exit code: %d)' % os.system(editor)
267
268 # read the message back
269 f = file(fname)
270 msg = f.read()
271 f.close()
272
273 return msg.strip('\n')
274
275 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
276 """Build the message to be sent via SMTP
277 """
278 p = crt_series.get_patch(patch)
279
280 descr = p.get_description().strip()
281 descr_lines = descr.split('\n')
282
283 short_descr = descr_lines[0].rstrip()
284 long_descr = reduce(lambda x, y: x + '\n' + y,
285 descr_lines[1:], '').lstrip()
286
287 maintainer = __get_maintainer()
288 if not maintainer:
289 maintainer = '%s <%s>' % (p.get_commname(), p.get_commemail())
290
291 headers_end = __build_address_headers(options)
292 headers_end += 'Message-Id: %s\n' % msg_id
293 if ref_id:
294 headers_end += "In-Reply-To: %s\n" % ref_id
295 headers_end += "References: %s\n" % ref_id
296
297 if options.version:
298 version_str = ' %s' % options.version
299 else:
300 version_str = ''
301
302 total_nr_str = str(total_nr)
303 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
304 if total_nr > 1:
305 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
306 else:
307 number_str = ''
308
309 tmpl_dict = {'patch': patch,
310 'maintainer': maintainer,
311 'shortdescr': short_descr,
312 'longdescr': long_descr,
313 'endofheaders': headers_end,
314 'diff': git.diff(rev1 = git_id('%s/bottom' % patch),
315 rev2 = git_id('%s/top' % patch)),
316 'diffstat': git.diffstat(rev1 = git_id('%s/bottom'%patch),
317 rev2 = git_id('%s/top' % patch)),
318 'date': email.Utils.formatdate(localtime = True),
319 'version': version_str,
320 'patchnr': patch_nr_str,
321 'totalnr': total_nr_str,
322 'number': number_str,
323 'authname': p.get_authname(),
324 'authemail': p.get_authemail(),
325 'authdate': p.get_authdate(),
326 'commname': p.get_commname(),
327 'commemail': p.get_commemail()}
328 for key in tmpl_dict:
329 if not tmpl_dict[key]:
330 tmpl_dict[key] = ''
331
332 try:
333 msg = tmpl % tmpl_dict
334 except KeyError, err:
335 raise CmdException, 'Unknown patch template variable: %s' \
336 % err
337 except TypeError:
338 raise CmdException, 'Only "%(name)s" variables are ' \
339 'supported in the patch template'
340
341 return msg.strip('\n')
342
343 def func(parser, options, args):
344 """Send the patches by e-mail using the patchmail.tmpl file as
345 a template
346 """
347 if not config.has_option('stgit', 'smtpserver'):
348 raise CmdException, 'smtpserver not defined'
349 smtpserver = config.get('stgit', 'smtpserver')
350
351 smtpuser = None
352 smtppassword = None
353 if config.has_option('stgit', 'smtpuser'):
354 smtpuser = config.get('stgit', 'smtpuser')
355 if config.has_option('stgit', 'smtppassword'):
356 smtppassword = config.get('stgit', 'smtppassword')
357
358 applied = crt_series.get_applied()
359 unapplied = crt_series.get_unapplied()
360
361 if len(args) >= 1:
362 for patch in args:
363 if patch in unapplied:
364 raise CmdException, 'Patch "%s" not applied' % patch
365 if not patch in applied:
366 raise CmdException, 'Patch "%s" does not exist' % patch
367 patches = args
368 elif options.all:
369 patches = applied
370 elif options.range:
371 boundaries = options.range.split(':')
372 if len(boundaries) == 1:
373 start = boundaries[0]
374 stop = boundaries[0]
375 elif len(boundaries) == 2:
376 if boundaries[0] == '':
377 start = applied[0]
378 else:
379 start = boundaries[0]
380 if boundaries[1] == '':
381 stop = applied[-1]
382 else:
383 stop = boundaries[1]
384 else:
385 raise CmdException, 'incorrect parameters to "--range"'
386
387 if start in applied:
388 start_idx = applied.index(start)
389 else:
390 if start in unapplied:
391 raise CmdException, 'Patch "%s" not applied' % start
392 else:
393 raise CmdException, 'Patch "%s" does not exist' % start
394 if stop in applied:
395 stop_idx = applied.index(stop) + 1
396 else:
397 if stop in unapplied:
398 raise CmdException, 'Patch "%s" not applied' % stop
399 else:
400 raise CmdException, 'Patch "%s" does not exist' % stop
401
402 if start_idx >= stop_idx:
403 raise CmdException, 'Incorrect patch range order'
404
405 patches = applied[start_idx:stop_idx]
406 else:
407 raise CmdException, 'Incorrect options. Unknown patches to send'
408
409 if options.smtp_password:
410 smtppassword = options.smtp_password
411
412 if options.smtp_user:
413 smtpuser = options.smtp_user
414
415 if (smtppassword and not smtpuser):
416 raise CmdException, 'SMTP password supplied, username needed'
417 if (smtpuser and not smtppassword):
418 raise CmdException, 'SMTP username supplied, password needed'
419
420 total_nr = len(patches)
421 if total_nr == 0:
422 raise CmdException, 'No patches to send'
423
424 ref_id = options.refid
425
426 if options.sleep != None:
427 sleep = options.sleep
428 else:
429 sleep = config.getint('stgit', 'smtpdelay')
430
431 # send the cover message (if any)
432 if options.cover or options.edit:
433 # find the template file
434 if options.cover:
435 tfile_list = [options.cover]
436 else:
437 tfile_list = [os.path.join(basedir.get(), 'covermail.tmpl'),
438 os.path.join(sys.prefix,
439 'share/stgit/templates/covermail.tmpl')]
440
441 tmpl = None
442 for tfile in tfile_list:
443 if os.path.isfile(tfile):
444 tmpl = file(tfile).read()
445 break
446 if not tmpl:
447 raise CmdException, 'No cover message template file found'
448
449 msg_id = email.Utils.make_msgid('stgit')
450 msg = __build_cover(tmpl, total_nr, msg_id, options)
451 from_addr, to_addr_list = __parse_addresses(msg)
452
453 # subsequent e-mails are seen as replies to the first one
454 ref_id = msg_id
455
456 if options.mbox:
457 __write_mbox(from_addr, msg)
458 else:
459 print 'Sending the cover message...',
460 sys.stdout.flush()
461 __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
462 smtpuser, smtppassword)
463 print 'done'
464
465 # send the patches
466 if options.template:
467 tfile_list = [options.template]
468 else:
469 tfile_list = [os.path.join(basedir.get(), 'patchmail.tmpl'),
470 os.path.join(sys.prefix,
471 'share/stgit/templates/patchmail.tmpl')]
472 tmpl = None
473 for tfile in tfile_list:
474 if os.path.isfile(tfile):
475 tmpl = file(tfile).read()
476 break
477 if not tmpl:
478 raise CmdException, 'No e-mail template file found'
479
480 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
481 msg_id = email.Utils.make_msgid('stgit')
482 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
483 options)
484 from_addr, to_addr_list = __parse_addresses(msg)
485
486 # subsequent e-mails are seen as replies to the first one
487 if not ref_id:
488 ref_id = msg_id
489
490 if options.mbox:
491 __write_mbox(from_addr, msg)
492 else:
493 print 'Sending patch "%s"...' % p,
494 sys.stdout.flush()
495 __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
496 smtpuser, smtppassword)
497 print 'done'