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