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