Add --binary flag to commands that generate diffs
[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
19 import email, email.Utils, email.Header
20 from optparse import OptionParser, make_option
21
22 from stgit.commands.common import *
23 from stgit.utils import *
24 from stgit import stack, git, version, templates
25 from stgit.config import config
26
27
28 help = 'send a patch or series of patches by e-mail'
29 usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
30
31 Send a patch or a range of patches by e-mail using the 'smtpserver'
32 configuration option. The From address and the e-mail format are
33 generated from the template file passed as argument to '--template'
34 (defaulting to '.git/patchmail.tmpl' or
35 '~/.stgit/templates/patchmail.tmpl' or
36 '/usr/share/stgit/templates/patchmail.tmpl').
37
38 The To/Cc/Bcc addresses can either be added to the template file or
39 passed via the corresponding command line options. They can be e-mail
40 addresses or aliases which are automatically expanded to the values
41 stored in the [mail "alias"] section of GIT configuration files.
42
43 A 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
45 be used as a template. The latter option will invoke the editor on the
46 specified file (defaulting to '.git/covermail.tmpl' or
47 '~/.stgit/templates/covermail.tmpl' or
48 '/usr/share/stgit/templates/covermail.tmpl').
49
50 All 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
52 replies to a different e-mail by using the '--refid' option.
53
54 SMTP authentication is also possible with '--smtp-user' and
55 '--smtp-password' options, also available as configuration settings:
56 'smtpuser' and 'smtppassword'.
57
58 The patch e-mail template accepts the following variables:
59
60 %(patch)s - patch name
61 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
62 %(shortdescr)s - the first line of the patch description
63 %(longdescr)s - the rest of the patch description, after the first line
64 %(diff)s - unified diff of the patch
65 %(diffstat)s - diff statistics
66 %(version)s - ' version' string passed on the command line (or empty)
67 %(prefix)s - 'prefix ' string passed on the command line
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 %(fromauth)s - 'From: author\\n\\n' if different from sender
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
78 For the preamble e-mail template, only the %(sender)s, %(version)s,
79 %(patchnr)s, %(totalnr)s and %(number)s 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('--to',
85 help = 'add TO to the To: list',
86 action = 'append'),
87 make_option('--cc',
88 help = 'add CC to the Cc: list',
89 action = 'append'),
90 make_option('--bcc',
91 help = 'add BCC to the Bcc: list',
92 action = 'append'),
93 make_option('--auto',
94 help = 'automatically cc the patch signers',
95 action = 'store_true'),
96 make_option('--noreply',
97 help = 'do not send subsequent messages as replies',
98 action = 'store_true'),
99 make_option('-v', '--version', metavar = 'VERSION',
100 help = 'add VERSION to the [PATCH ...] prefix'),
101 make_option('--prefix', metavar = 'PREFIX',
102 help = 'add PREFIX to the [... PATCH ...] prefix'),
103 make_option('-t', '--template', metavar = 'FILE',
104 help = 'use FILE as the message template'),
105 make_option('-c', '--cover', metavar = 'FILE',
106 help = 'send FILE as the cover message'),
107 make_option('-e', '--edit-cover',
108 help = 'edit the cover message before sending',
109 action = 'store_true'),
110 make_option('-E', '--edit-patches',
111 help = 'edit each patch before sending',
112 action = 'store_true'),
113 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
114 help = 'sleep for SECONDS between e-mails sending'),
115 make_option('--refid',
116 help = 'use REFID as the reference id'),
117 make_option('-u', '--smtp-user', metavar = 'USER',
118 help = 'username for SMTP authentication'),
119 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
120 help = 'username for SMTP authentication'),
121 make_option('-b', '--branch',
122 help = 'use BRANCH instead of the default one'),
123 make_option('--binary',
124 help = 'output a diff even for binary files',
125 action = 'store_true'),
126 make_option('-m', '--mbox',
127 help = 'generate an mbox file instead of sending',
128 action = 'store_true')]
129
130
131 def __get_sender():
132 """Return the 'authname <authemail>' string as read from the
133 configuration file
134 """
135 sender=config.get('stgit.sender')
136 if not sender:
137 try:
138 sender = str(git.user())
139 except git.GitException:
140 sender = str(git.author())
141
142 if not sender:
143 raise CmdException, 'unknown sender details'
144
145 return address_or_alias(sender)
146
147 def __parse_addresses(msg):
148 """Return a two elements tuple: (from, [to])
149 """
150 def __addr_list(msg, header):
151 return [name_addr[1] for name_addr in
152 email.Utils.getaddresses(msg.get_all(header, []))]
153
154 from_addr_list = __addr_list(msg, 'From')
155 if len(from_addr_list) == 0:
156 raise CmdException, 'No "From" address'
157
158 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
159 + __addr_list(msg, 'Bcc')
160 if len(to_addr_list) == 0:
161 raise CmdException, 'No "To/Cc/Bcc" addresses'
162
163 return (from_addr_list[0], to_addr_list)
164
165 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
166 smtpuser, smtppassword):
167 """Send the message using the given SMTP server
168 """
169 try:
170 s = smtplib.SMTP(smtpserver)
171 except Exception, err:
172 raise CmdException, str(err)
173
174 s.set_debuglevel(0)
175 try:
176 if smtpuser and smtppassword:
177 s.ehlo()
178 s.login(smtpuser, smtppassword)
179
180 s.sendmail(from_addr, to_addr_list, msg)
181 # give recipients a chance of receiving patches in the correct order
182 time.sleep(sleep)
183 except Exception, err:
184 raise CmdException, str(err)
185
186 s.quit()
187
188 def __build_address_headers(msg, options, extra_cc = []):
189 """Build the address headers and check existing headers in the
190 template.
191 """
192 def __replace_header(header, addr):
193 if addr:
194 crt_addr = msg[header]
195 del msg[header]
196
197 if crt_addr:
198 msg[header] = address_or_alias(', '.join([crt_addr, addr]))
199 else:
200 msg[header] = address_or_alias(addr)
201
202 to_addr = ''
203 cc_addr = ''
204 bcc_addr = ''
205
206 autobcc = config.get('stgit.autobcc') or ''
207
208 if options.to:
209 to_addr = ', '.join(options.to)
210 if options.cc:
211 cc_addr = ', '.join(options.cc + extra_cc)
212 elif extra_cc:
213 cc_addr = ', '.join(extra_cc)
214 if options.bcc:
215 bcc_addr = ', '.join(options.bcc + [autobcc])
216 elif autobcc:
217 bcc_addr = autobcc
218
219 __replace_header('To', to_addr)
220 __replace_header('Cc', cc_addr)
221 __replace_header('Bcc', bcc_addr)
222
223 def __get_signers_list(msg):
224 """Return the address list generated from signed-off-by and
225 acked-by lines in the message.
226 """
227 addr_list = []
228
229 r = re.compile('^(signed-off-by|acked-by):\s+(.+)$', re.I)
230 for line in msg.split('\n'):
231 m = r.match(line)
232 if m:
233 addr_list.append(m.expand('\g<2>'))
234
235 return addr_list
236
237 def __build_extra_headers(msg, msg_id, ref_id = None):
238 """Build extra email headers and encoding
239 """
240 del msg['Date']
241 msg['Date'] = email.Utils.formatdate(localtime = True)
242 msg['Message-ID'] = msg_id
243 if ref_id:
244 msg['In-Reply-To'] = ref_id
245 msg['References'] = ref_id
246 msg['User-Agent'] = 'StGIT/%s' % version.version
247
248 def __encode_message(msg):
249 # 7 or 8 bit encoding
250 charset = email.Charset.Charset('utf-8')
251 charset.body_encoding = None
252
253 # encode headers
254 for header, value in msg.items():
255 words = []
256 for word in value.split(' '):
257 try:
258 uword = unicode(word, 'utf-8')
259 except UnicodeDecodeError:
260 # maybe we should try a different encoding or report
261 # the error. At the moment, we just ignore it
262 pass
263 words.append(email.Header.Header(uword).encode())
264 new_val = ' '.join(words)
265 msg.replace_header(header, new_val)
266
267 # encode the body and set the MIME and encoding headers
268 msg.set_charset(charset)
269
270 def __edit_message(msg):
271 fname = '.stgitmail.txt'
272
273 # create the initial file
274 f = file(fname, 'w')
275 f.write(msg)
276 f.close()
277
278 call_editor(fname)
279
280 # read the message back
281 f = file(fname)
282 msg = f.read()
283 f.close()
284
285 return msg
286
287 def __build_cover(tmpl, total_nr, msg_id, options):
288 """Build the cover message (series description) to be sent via SMTP
289 """
290 sender = __get_sender()
291
292 if options.version:
293 version_str = ' %s' % options.version
294 else:
295 version_str = ''
296
297 if options.prefix:
298 prefix_str = options.prefix + ' '
299 else:
300 prefix_str = ''
301
302 total_nr_str = str(total_nr)
303 patch_nr_str = '0'.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 = {'sender': sender,
310 # for backward template compatibility
311 'maintainer': sender,
312 # for backward template compatibility
313 'endofheaders': '',
314 # for backward template compatibility
315 'date': '',
316 'version': version_str,
317 'prefix': prefix_str,
318 'patchnr': patch_nr_str,
319 'totalnr': total_nr_str,
320 'number': number_str}
321
322 try:
323 msg_string = tmpl % tmpl_dict
324 except KeyError, err:
325 raise CmdException, 'Unknown patch template variable: %s' \
326 % err
327 except TypeError:
328 raise CmdException, 'Only "%(name)s" variables are ' \
329 'supported in the patch template'
330
331 if options.edit_cover:
332 msg_string = __edit_message(msg_string)
333
334 # The Python email message
335 try:
336 msg = email.message_from_string(msg_string)
337 except Exception, ex:
338 raise CmdException, 'template parsing error: %s' % str(ex)
339
340 __build_address_headers(msg, options)
341 __build_extra_headers(msg, msg_id, options.refid)
342 __encode_message(msg)
343
344 return msg
345
346 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
347 """Build the message to be sent via SMTP
348 """
349 p = crt_series.get_patch(patch)
350
351 descr = p.get_description().strip()
352 descr_lines = descr.split('\n')
353
354 short_descr = descr_lines[0].rstrip()
355 long_descr = '\n'.join(descr_lines[1:]).lstrip()
356
357 authname = p.get_authname();
358 authemail = p.get_authemail();
359 commname = p.get_commname();
360 commemail = p.get_commemail();
361
362 sender = __get_sender()
363
364 fromauth = '%s <%s>' % (authname, authemail)
365 if fromauth != sender:
366 fromauth = 'From: %s\n\n' % fromauth
367 else:
368 fromauth = ''
369
370 if options.version:
371 version_str = ' %s' % options.version
372 else:
373 version_str = ''
374
375 if options.prefix:
376 prefix_str = options.prefix + ' '
377 else:
378 prefix_str = ''
379
380 total_nr_str = str(total_nr)
381 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
382 if total_nr > 1:
383 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
384 else:
385 number_str = ''
386
387 tmpl_dict = {'patch': patch,
388 'sender': sender,
389 # for backward template compatibility
390 'maintainer': sender,
391 'shortdescr': short_descr,
392 'longdescr': long_descr,
393 # for backward template compatibility
394 'endofheaders': '',
395 'diff': git.diff(rev1 = git_id('%s//bottom' % patch),
396 rev2 = git_id('%s//top' % patch),
397 binary = options.binary),
398 'diffstat': git.diffstat(rev1 = git_id('%s//bottom'%patch),
399 rev2 = git_id('%s//top' % patch)),
400 # for backward template compatibility
401 'date': '',
402 'version': version_str,
403 'prefix': prefix_str,
404 'patchnr': patch_nr_str,
405 'totalnr': total_nr_str,
406 'number': number_str,
407 'fromauth': fromauth,
408 'authname': authname,
409 'authemail': authemail,
410 'authdate': p.get_authdate(),
411 'commname': commname,
412 'commemail': commemail}
413 # change None to ''
414 for key in tmpl_dict:
415 if not tmpl_dict[key]:
416 tmpl_dict[key] = ''
417
418 try:
419 msg_string = tmpl % tmpl_dict
420 except KeyError, err:
421 raise CmdException, 'Unknown patch template variable: %s' \
422 % err
423 except TypeError:
424 raise CmdException, 'Only "%(name)s" variables are ' \
425 'supported in the patch template'
426
427 if options.edit_patches:
428 msg_string = __edit_message(msg_string)
429
430 # The Python email message
431 try:
432 msg = email.message_from_string(msg_string)
433 except Exception, ex:
434 raise CmdException, 'template parsing error: %s' % str(ex)
435
436 if options.auto:
437 extra_cc = __get_signers_list(descr)
438 else:
439 extra_cc = []
440
441 __build_address_headers(msg, options, extra_cc)
442 __build_extra_headers(msg, msg_id, ref_id)
443 __encode_message(msg)
444
445 return msg
446
447 def func(parser, options, args):
448 """Send the patches by e-mail using the patchmail.tmpl file as
449 a template
450 """
451 smtpserver = config.get('stgit.smtpserver')
452
453 applied = crt_series.get_applied()
454
455 if options.all:
456 patches = applied
457 elif len(args) >= 1:
458 unapplied = crt_series.get_unapplied()
459 patches = parse_patches(args, applied + unapplied, len(applied))
460 else:
461 raise CmdException, 'Incorrect options. Unknown patches to send'
462
463 smtppassword = options.smtp_password or config.get('stgit.smtppassword')
464 smtpuser = options.smtp_user or config.get('stgit.smtpuser')
465
466 if (smtppassword and not smtpuser):
467 raise CmdException, 'SMTP password supplied, username needed'
468 if (smtpuser and not smtppassword):
469 raise CmdException, 'SMTP username supplied, password needed'
470
471 total_nr = len(patches)
472 if total_nr == 0:
473 raise CmdException, 'No patches to send'
474
475 if options.noreply:
476 ref_id = None
477 else:
478 ref_id = options.refid
479
480 sleep = options.sleep or config.getint('stgit.smtpdelay')
481
482 # send the cover message (if any)
483 if options.cover or options.edit_cover:
484 # find the template file
485 if options.cover:
486 tmpl = file(options.cover).read()
487 else:
488 tmpl = templates.get_template('covermail.tmpl')
489 if not tmpl:
490 raise CmdException, 'No cover message template file found'
491
492 msg_id = email.Utils.make_msgid('stgit')
493 msg = __build_cover(tmpl, total_nr, msg_id, options)
494 from_addr, to_addr_list = __parse_addresses(msg)
495
496 msg_string = msg.as_string(options.mbox)
497
498 # subsequent e-mails are seen as replies to the first one
499 if not options.noreply:
500 ref_id = msg_id
501
502 if options.mbox:
503 print msg_string
504 else:
505 print 'Sending the cover message...',
506 sys.stdout.flush()
507 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
508 sleep, smtpuser, smtppassword)
509 print 'done'
510
511 # send the patches
512 if options.template:
513 tmpl = file(options.template).read()
514 else:
515 tmpl = templates.get_template('patchmail.tmpl')
516 if not tmpl:
517 raise CmdException, 'No e-mail template file found'
518
519 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
520 msg_id = email.Utils.make_msgid('stgit')
521 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
522 options)
523 from_addr, to_addr_list = __parse_addresses(msg)
524
525 msg_string = msg.as_string(options.mbox)
526
527 # subsequent e-mails are seen as replies to the first one
528 if not options.noreply and not ref_id:
529 ref_id = msg_id
530
531 if options.mbox:
532 print msg_string
533 else:
534 print 'Sending patch "%s"...' % p,
535 sys.stdout.flush()
536 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
537 sleep, smtpuser, smtppassword)
538 print 'done'