Remove the checking for the default configuration values
[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 smtpserver = config.get('stgit', 'smtpserver')
348
349 smtpuser = None
350 smtppassword = None
351 if config.has_option('stgit', 'smtpuser'):
352 smtpuser = config.get('stgit', 'smtpuser')
353 if config.has_option('stgit', 'smtppassword'):
354 smtppassword = config.get('stgit', 'smtppassword')
355
356 applied = crt_series.get_applied()
357 unapplied = crt_series.get_unapplied()
358
359 if len(args) >= 1:
360 for patch in args:
361 if patch in unapplied:
362 raise CmdException, 'Patch "%s" not applied' % patch
363 if not patch in applied:
364 raise CmdException, 'Patch "%s" does not exist' % patch
365 patches = args
366 elif options.all:
367 patches = applied
368 elif options.range:
369 boundaries = options.range.split(':')
370 if len(boundaries) == 1:
371 start = boundaries[0]
372 stop = boundaries[0]
373 elif len(boundaries) == 2:
374 if boundaries[0] == '':
375 start = applied[0]
376 else:
377 start = boundaries[0]
378 if boundaries[1] == '':
379 stop = applied[-1]
380 else:
381 stop = boundaries[1]
382 else:
383 raise CmdException, 'incorrect parameters to "--range"'
384
385 if start in applied:
386 start_idx = applied.index(start)
387 else:
388 if start in unapplied:
389 raise CmdException, 'Patch "%s" not applied' % start
390 else:
391 raise CmdException, 'Patch "%s" does not exist' % start
392 if stop in applied:
393 stop_idx = applied.index(stop) + 1
394 else:
395 if stop in unapplied:
396 raise CmdException, 'Patch "%s" not applied' % stop
397 else:
398 raise CmdException, 'Patch "%s" does not exist' % stop
399
400 if start_idx >= stop_idx:
401 raise CmdException, 'Incorrect patch range order'
402
403 patches = applied[start_idx:stop_idx]
404 else:
405 raise CmdException, 'Incorrect options. Unknown patches to send'
406
407 if options.smtp_password:
408 smtppassword = options.smtp_password
409
410 if options.smtp_user:
411 smtpuser = options.smtp_user
412
413 if (smtppassword and not smtpuser):
414 raise CmdException, 'SMTP password supplied, username needed'
415 if (smtpuser and not smtppassword):
416 raise CmdException, 'SMTP username supplied, password needed'
417
418 total_nr = len(patches)
419 if total_nr == 0:
420 raise CmdException, 'No patches to send'
421
422 ref_id = options.refid
423
424 if options.sleep != None:
425 sleep = options.sleep
426 else:
427 sleep = config.getint('stgit', 'smtpdelay')
428
429 # send the cover message (if any)
430 if options.cover or options.edit:
431 # find the template file
432 if options.cover:
433 tfile_list = [options.cover]
434 else:
435 tfile_list = [os.path.join(basedir.get(), 'covermail.tmpl'),
436 os.path.join(sys.prefix,
437 'share/stgit/templates/covermail.tmpl')]
438
439 tmpl = None
440 for tfile in tfile_list:
441 if os.path.isfile(tfile):
442 tmpl = file(tfile).read()
443 break
444 if not tmpl:
445 raise CmdException, 'No cover message template file found'
446
447 msg_id = email.Utils.make_msgid('stgit')
448 msg = __build_cover(tmpl, total_nr, msg_id, options)
449 from_addr, to_addr_list = __parse_addresses(msg)
450
451 # subsequent e-mails are seen as replies to the first one
452 ref_id = msg_id
453
454 if options.mbox:
455 __write_mbox(from_addr, msg)
456 else:
457 print 'Sending the cover message...',
458 sys.stdout.flush()
459 __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
460 smtpuser, smtppassword)
461 print 'done'
462
463 # send the patches
464 if options.template:
465 tfile_list = [options.template]
466 else:
467 tfile_list = [os.path.join(basedir.get(), 'patchmail.tmpl'),
468 os.path.join(sys.prefix,
469 'share/stgit/templates/patchmail.tmpl')]
470 tmpl = None
471 for tfile in tfile_list:
472 if os.path.isfile(tfile):
473 tmpl = file(tfile).read()
474 break
475 if not tmpl:
476 raise CmdException, 'No e-mail template file found'
477
478 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
479 msg_id = email.Utils.make_msgid('stgit')
480 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
481 options)
482 from_addr, to_addr_list = __parse_addresses(msg)
483
484 # subsequent e-mails are seen as replies to the first one
485 if not ref_id:
486 ref_id = msg_id
487
488 if options.mbox:
489 __write_mbox(from_addr, msg)
490 else:
491 print 'Sending patch "%s"...' % p,
492 sys.stdout.flush()
493 __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
494 smtpuser, smtppassword)
495 print 'done'