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