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