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