2 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
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.
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.
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
18 import sys, os, re, time, smtplib, email.Utils
19 from optparse import OptionParser, make_option
20 from time import gmtime, strftime
22 from stgit.commands.common import *
23 from stgit.utils import *
24 from stgit import stack, git
25 from stgit.config import config
28 help = 'send a patch or series of patches by e-mail'
29 usage = """%prog [options]"""
31 options = [make_option('-t', '--template', metavar = 'FILE',
32 help = 'use FILE as the message template'),
33 make_option('-r', '--range',
34 metavar = '[PATCH1][:[PATCH2]]',
35 help = 'e-mail patches between PATCH1 and PATCH2'),
36 make_option('-f', '--first', metavar = 'FILE',
37 help = 'send FILE as the first message'),
38 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
39 help = 'sleep for SECONDS between e-mails sending'),
40 make_option('--refid',
41 help = 'Use REFID as the reference id')]
44 def __parse_addresses(string):
45 """Return a two elements tuple: (from, [to])
47 def __addr_list(string):
48 return re.split('.*?([\w\.]+@[\w\.]+)', string)[1:-1:2]
52 for line in string.split('\n'):
53 if re.match('from:\s+', line, re.I):
54 from_addr_list += __addr_list(line)
55 elif re.match('(to|cc|bcc):\s+', line, re.I):
56 to_addr_list += __addr_list(line)
58 if len(from_addr_list) != 1:
59 raise CmdException, 'No "From" address'
60 if len(to_addr_list) == 0:
61 raise CmdException, 'No "To/Cc/Bcc" addresses'
63 return (from_addr_list[0], to_addr_list)
65 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep):
66 """Send the message using the given SMTP server
69 s = smtplib.SMTP(smtpserver)
70 except Exception, err:
71 raise CmdException, str(err)
75 s.sendmail(from_addr, to_addr_list, msg)
76 # give recipients a chance of receiving patches in the correct order
78 except Exception, err:
79 raise CmdException, str(err)
83 def __build_first(tmpl, total_nr, msg_id):
84 """Build the first message (series description) to be sent via SMTP
86 headers_end = 'Message-Id: %s\n' % (msg_id)
87 total_nr_str = str(total_nr)
89 tmpl_dict = {'endofheaders': headers_end,
90 'date': email.Utils.formatdate(localtime = True),
91 'totalnr': total_nr_str}
94 msg = tmpl % tmpl_dict
96 raise CmdException, 'Unknown patch template variable: %s' \
99 raise CmdException, 'Only "%(name)s" variables are ' \
100 'supported in the patch template'
105 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id = None):
106 """Build the message to be sent via SMTP
108 p = crt_series.get_patch(patch)
110 descr = p.get_description().strip()
111 descr_lines = descr.split('\n')
113 short_descr = descr_lines[0].rstrip()
114 long_descr = reduce(lambda x, y: x + '\n' + y,
115 descr_lines[1:], '').lstrip()
117 headers_end = 'Message-Id: %s\n' % (msg_id)
119 headers_end += "In-Reply-To: %s\n" % (ref_id)
120 headers_end += "References: %s\n" % (ref_id)
122 total_nr_str = str(total_nr)
123 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
125 tmpl_dict = {'patch': patch,
126 'shortdescr': short_descr,
127 'longdescr': long_descr,
128 'endofheaders': headers_end,
129 'diff': git.diff(rev1 = git_id('%s/bottom' % patch),
130 rev2 = git_id('%s/top' % patch)),
131 'diffstat': git.diffstat(rev1 = git_id('%s/bottom'%patch),
132 rev2 = git_id('%s/top' % patch)),
133 'date': email.Utils.formatdate(localtime = True),
134 'patchnr': patch_nr_str,
135 'totalnr': total_nr_str,
136 'authname': p.get_authname(),
137 'authemail': p.get_authemail(),
138 'authdate': p.get_authdate(),
139 'commname': p.get_commname(),
140 'commemail': p.get_commemail()}
141 for key in tmpl_dict:
142 if not tmpl_dict[key]:
146 msg = tmpl % tmpl_dict
147 except KeyError, err:
148 raise CmdException, 'Unknown patch template variable: %s' \
151 raise CmdException, 'Only "%(name)s" variables are ' \
152 'supported in the patch template'
157 def func(parser, options, args):
158 """Send the patches by e-mail using the patchmail.tmpl file as
162 parser.error('incorrect number of arguments')
164 if not config.has_option('stgit', 'smtpserver'):
165 raise CmdException, 'smtpserver not defined'
166 smtpserver = config.get('stgit', 'smtpserver')
168 applied = crt_series.get_applied()
171 boundaries = options.range.split(':')
172 if len(boundaries) == 1:
173 start = boundaries[0]
175 elif len(boundaries) == 2:
176 if boundaries[0] == '':
179 start = boundaries[0]
180 if boundaries[1] == '':
185 raise CmdException, 'incorrect parameters to "--range"'
188 start_idx = applied.index(start)
190 raise CmdException, 'Patch "%s" not applied' % start
192 stop_idx = applied.index(stop) + 1
194 raise CmdException, 'Patch "%s" not applied' % stop
196 if start_idx >= stop_idx:
197 raise CmdException, 'Incorrect patch range order'
200 stop_idx = len(applied)
202 patches = applied[start_idx:stop_idx]
203 total_nr = len(patches)
205 ref_id = options.refid
207 if options.sleep != None:
208 sleep = options.sleep
212 # send the first message (if any)
214 tmpl = file(options.first).read()
215 from_addr, to_addr_list = __parse_addresses(tmpl)
217 msg_id = email.Utils.make_msgid('stgit')
218 msg = __build_first(tmpl, total_nr, msg_id)
220 # subsequent e-mails are seen as replies to the first one
223 print 'Sending file "%s"...' % options.first,
226 __send_message(smtpserver, from_addr, to_addr_list, msg, sleep)
232 tfile = options.template
234 tfile = os.path.join(git.base_dir, 'patchmail.tmpl')
235 tmpl = file(tfile).read()
237 from_addr, to_addr_list = __parse_addresses(tmpl)
239 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
240 msg_id = email.Utils.make_msgid('stgit')
241 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id)
242 # subsequent e-mails are seen as replies to the first one
246 print 'Sending patch "%s"...' % p,
249 __send_message(smtpserver, from_addr, to_addr_list, msg, sleep)