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