chiark / gitweb /
ceccdd6369d7d6b867b656194ee8154b456656d2
[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, smtplib, email.Utils
19 from optparse import OptionParser, make_option
20 from time import gmtime, strftime
21
22 from stgit.commands.common import *
23 from stgit.utils import *
24 from stgit import stack, git
25 from stgit.config import config
26
27
28 help = 'send a patch or series of patches by e-mail'
29 usage = """%prog [options] [<patch>]"""
30
31 options = [make_option('-a', '--all',
32                        help = 'e-mail all the applied patches',
33                        action = 'store_true'),
34            make_option('-r', '--range',
35                        metavar = '[PATCH1][:[PATCH2]]',
36                        help = 'e-mail patches between PATCH1 and PATCH2'),
37            make_option('-t', '--template', metavar = 'FILE',
38                        help = 'use FILE as the message template'),
39            make_option('-f', '--first', metavar = 'FILE',
40                        help = 'send FILE as the first message'),
41            make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
42                        help = 'sleep for SECONDS between e-mails sending'),
43            make_option('--refid',
44                        help = 'Use REFID as the reference id'),
45            make_option('-u', '--smtp-user', metavar = 'USER',
46                        help = 'username for SMTP authentication'),
47            make_option('-p', '--smtp-password', metavar = 'PASSWORD',
48                        help = 'username for SMTP authentication')]
49
50
51 def __parse_addresses(string):
52     """Return a two elements tuple: (from, [to])
53     """
54     def __addr_list(string):
55         return re.split('.*?([\w\.]+@[\w\.]+)', string)[1:-1:2]
56
57     from_addr_list = []
58     to_addr_list = []
59     for line in string.split('\n'):
60         if re.match('from:\s+', line, re.I):
61             from_addr_list += __addr_list(line)
62         elif re.match('(to|cc|bcc):\s+', line, re.I):
63             to_addr_list += __addr_list(line)
64
65     if len(from_addr_list) != 1:
66         raise CmdException, 'No "From" address'
67     if len(to_addr_list) == 0:
68         raise CmdException, 'No "To/Cc/Bcc" addresses'
69
70     return (from_addr_list[0], to_addr_list)
71
72 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
73                    smtpuser, smtppassword):
74     """Send the message using the given SMTP server
75     """
76     try:
77         s = smtplib.SMTP(smtpserver)
78     except Exception, err:
79         raise CmdException, str(err)
80
81     s.set_debuglevel(0)
82     try:
83         if smtpuser and smtppassword:
84             s.ehlo()
85             s.login(smtpuser, smtppassword)
86
87         s.sendmail(from_addr, to_addr_list, msg)
88         # give recipients a chance of receiving patches in the correct order
89         time.sleep(sleep)
90     except Exception, err:
91         raise CmdException, str(err)
92
93     s.quit()
94
95 def __build_first(tmpl, total_nr, msg_id):
96     """Build the first message (series description) to be sent via SMTP
97     """
98     headers_end = 'Message-Id: %s\n' % (msg_id)
99     total_nr_str = str(total_nr)
100
101     tmpl_dict = {'endofheaders': headers_end,
102                  'date':         email.Utils.formatdate(localtime = True),
103                  'totalnr':      total_nr_str}
104
105     try:
106         msg = tmpl % tmpl_dict
107     except KeyError, err:
108         raise CmdException, 'Unknown patch template variable: %s' \
109               % err
110     except TypeError:
111         raise CmdException, 'Only "%(name)s" variables are ' \
112               'supported in the patch template'
113
114     return msg
115
116
117 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id = None):
118     """Build the message to be sent via SMTP
119     """
120     p = crt_series.get_patch(patch)
121
122     descr = p.get_description().strip()
123     descr_lines = descr.split('\n')
124
125     short_descr = descr_lines[0].rstrip()
126     long_descr = reduce(lambda x, y: x + '\n' + y,
127                         descr_lines[1:], '').lstrip()
128
129     headers_end = 'Message-Id: %s\n' % (msg_id)
130     if ref_id:
131         headers_end += "In-Reply-To: %s\n" % (ref_id)
132         headers_end += "References: %s\n" % (ref_id)
133
134     total_nr_str = str(total_nr)
135     patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
136
137     tmpl_dict = {'patch':        patch,
138                  'shortdescr':   short_descr,
139                  'longdescr':    long_descr,
140                  'endofheaders': headers_end,
141                  'diff':         git.diff(rev1 = git_id('%s/bottom' % patch),
142                                           rev2 = git_id('%s/top' % patch)),
143                  'diffstat':     git.diffstat(rev1 = git_id('%s/bottom'%patch),
144                                               rev2 = git_id('%s/top' % patch)),
145                  'date':         email.Utils.formatdate(localtime = True),
146                  'patchnr':      patch_nr_str,
147                  'totalnr':      total_nr_str,
148                  'authname':     p.get_authname(),
149                  'authemail':    p.get_authemail(),
150                  'authdate':     p.get_authdate(),
151                  'commname':     p.get_commname(),
152                  'commemail':    p.get_commemail()}
153     for key in tmpl_dict:
154         if not tmpl_dict[key]:
155             tmpl_dict[key] = ''
156
157     try:
158         msg = tmpl % tmpl_dict
159     except KeyError, err:
160         raise CmdException, 'Unknown patch template variable: %s' \
161               % err
162     except TypeError:
163         raise CmdException, 'Only "%(name)s" variables are ' \
164               'supported in the patch template'
165
166     return msg
167
168
169 def func(parser, options, args):
170     """Send the patches by e-mail using the patchmail.tmpl file as
171     a template
172     """
173     if len(args) > 1:
174         parser.error('incorrect number of arguments')
175
176     if not config.has_option('stgit', 'smtpserver'):
177         raise CmdException, 'smtpserver not defined'
178     smtpserver = config.get('stgit', 'smtpserver')
179
180     smtpuser = None
181     smtppassword = None
182     if config.has_option('stgit', 'smtpuser'):
183         smtpuser = config.get('stgit', 'smtpuser')
184     if config.has_option('stgit', 'smtppassword'):
185         smtppassword = config.get('stgit', 'smtppassword')
186
187     applied = crt_series.get_applied()
188
189     if len(args) == 1:
190         if args[0] in applied:
191             patches = [args[0]]
192         else:
193             raise CmdException, 'Patch "%s" not applied' % args[0]
194     elif options.all:
195         patches = applied
196     elif options.range:
197         boundaries = options.range.split(':')
198         if len(boundaries) == 1:
199             start = boundaries[0]
200             stop = boundaries[0]
201         elif len(boundaries) == 2:
202             if boundaries[0] == '':
203                 start = applied[0]
204             else:
205                 start = boundaries[0]
206             if boundaries[1] == '':
207                 stop = applied[-1]
208             else:
209                 stop = boundaries[1]
210         else:
211             raise CmdException, 'incorrect parameters to "--range"'
212
213         if start in applied:
214             start_idx = applied.index(start)
215         else:
216             raise CmdException, 'Patch "%s" not applied' % start
217         if stop in applied:
218             stop_idx = applied.index(stop) + 1
219         else:
220             raise CmdException, 'Patch "%s" not applied' % stop
221
222         if start_idx >= stop_idx:
223             raise CmdException, 'Incorrect patch range order'
224
225         patches = applied[start_idx:stop_idx]
226     else:
227         raise CmdException, 'Incorrect options. Unknown patches to send'
228
229     if options.smtp_password:
230         smtppassword = options.smtp_password
231
232     if options.smtp_user:
233         smtpuser = options.smtp_user
234
235     if (smtppassword and not smtpuser):
236         raise CmdException, 'SMTP password supplied, username needed'
237     if (smtpuser and not smtppassword):
238         raise CmdException, 'SMTP username supplied, password needed'
239
240     total_nr = len(patches)
241     if total_nr == 0:
242         raise CmdException, 'No patches to send'
243
244     ref_id = options.refid
245
246     if options.sleep != None:
247         sleep = options.sleep
248     else:
249         sleep = 2
250
251     # send the first message (if any)
252     if options.first:
253         tmpl = file(options.first).read()
254         from_addr, to_addr_list = __parse_addresses(tmpl)
255
256         msg_id = email.Utils.make_msgid('stgit')
257         msg = __build_first(tmpl, total_nr, msg_id)
258
259         # subsequent e-mails are seen as replies to the first one
260         ref_id = msg_id
261
262         print 'Sending file "%s"...' % options.first,
263         sys.stdout.flush()
264
265         __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
266                        smtpuser, smtppassword)
267
268         print 'done'
269
270     # send the patches
271     if options.template:
272         tfile = options.template
273     else:
274         tfile = os.path.join(git.base_dir, 'patchmail.tmpl')
275     tmpl = file(tfile).read()
276
277     from_addr, to_addr_list = __parse_addresses(tmpl)
278
279     for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
280         msg_id = email.Utils.make_msgid('stgit')
281         msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id)
282         # subsequent e-mails are seen as replies to the first one
283         if not ref_id:
284             ref_id = msg_id
285
286         print 'Sending patch "%s"...' % p,
287         sys.stdout.flush()
288
289         __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
290                        smtpuser, smtppassword)
291
292         print 'done'