Allow hand-editing of patches before sending
[stgit] / stgit / commands / mail.py
CommitLineData
b4bddc06
CM
1__copyright__ = """
2Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
3
4This program is free software; you can redistribute it and/or modify
5it under the terms of the GNU General Public License version 2 as
6published by the Free Software Foundation.
7
8This program is distributed in the hope that it will be useful,
9but WITHOUT ANY WARRANTY; without even the implied warranty of
10MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11GNU General Public License for more details.
12
13You should have received a copy of the GNU General Public License
14along with this program; if not, write to the Free Software
15Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16"""
17
29f00589 18import sys, os, re, time, datetime, smtplib, email.Utils
b4bddc06 19from optparse import OptionParser, make_option
b4bddc06
CM
20
21from stgit.commands.common import *
22from stgit.utils import *
1f3bb017 23from stgit import stack, git, version, templates
b4bddc06
CM
24from stgit.config import config
25
26
27help = 'send a patch or series of patches by e-mail'
6b1e0111 28usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
26aab5b0 29
6b1e0111
CM
30Send a patch or a range of patches by e-mail using the 'smtpserver'
31configuration option. The From address and the e-mail format are
32generated from the template file passed as argument to '--template'
33(defaulting to '.git/patchmail.tmpl' or
34'~/.stgit/templates/patchmail.tmpl' or or
94d18868 35'/usr/share/stgit/templates/patchmail.tmpl'). The To/Cc/Bcc addresses
2bb96902
CM
36can either be added to the template file or passed via the
37corresponding command line options.
38
0ba13ee9
KH
39A preamble e-mail can be sent using the '--cover' and/or
40'--edit-cover' options. The first allows the user to specify a file to
41be used as a template. The latter option will invoke the editor on the
42specified file (defaulting to '.git/covermail.tmpl' or
94d18868
YD
43'~/.stgit/templates/covermail.tmpl' or
44'/usr/share/stgit/templates/covermail.tmpl').
e3e05587
CM
45
46All the subsequent e-mails appear as replies to the first e-mail sent
47(either the preamble or the first patch). E-mails can be seen as
48replies to a different e-mail by using the '--refid' option.
26aab5b0
CM
49
50SMTP authentication is also possible with '--smtp-user' and
51'--smtp-password' options, also available as configuration settings:
52'smtpuser' and 'smtppassword'.
53
54The template e-mail headers and body must be separated by
55'%(endofheaders)s' variable, which is replaced by StGIT with
56additional headers and a blank line. The patch e-mail template accepts
57the following variables:
58
59 %(patch)s - patch name
dae0f0be 60 %(maintainer)s - 'authname <authemail>' as read from the config file
26aab5b0
CM
61 %(shortdescr)s - the first line of the patch description
62 %(longdescr)s - the rest of the patch description, after the first line
63 %(endofheaders)s - delimiter between e-mail headers and body
64 %(diff)s - unified diff of the patch
65 %(diffstat)s - diff statistics
66 %(date)s - current date/time
d0d139a3 67 %(version)s - ' version' string passed on the command line (or empty)
d323b5da 68 %(prefix)s - 'prefix ' string passed on the command line
26aab5b0
CM
69 %(patchnr)s - patch number
70 %(totalnr)s - total number of patches to be sent
b8d258e5 71 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
26aab5b0
CM
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
dae0f0be 78For the preamble e-mail template, only the %(maintainer)s, %(date)s,
d0d139a3
CM
79%(endofheaders)s, %(version)s, %(patchnr)s, %(totalnr)s and %(number)s
80variables are supported."""
b4bddc06 81
9a316368
CM
82options = [make_option('-a', '--all',
83 help = 'e-mail all the applied patches',
84 action = 'store_true'),
2bb96902 85 make_option('--to',
e83b3149
PO
86 help = 'add TO to the To: list',
87 action = 'append'),
2bb96902 88 make_option('--cc',
e83b3149
PO
89 help = 'add CC to the Cc: list',
90 action = 'append'),
2bb96902 91 make_option('--bcc',
e83b3149
PO
92 help = 'add BCC to the Bcc: list',
93 action = 'append'),
f8d1cf65
CM
94 make_option('--auto',
95 help = 'automatically cc the patch signers',
96 action = 'store_true'),
d1ed3a12
CM
97 make_option('--noreply',
98 help = 'do not send subsequent messages as replies',
99 action = 'store_true'),
d0d139a3
CM
100 make_option('-v', '--version', metavar = 'VERSION',
101 help = 'add VERSION to the [PATCH ...] prefix'),
d323b5da
RR
102 make_option('--prefix', metavar = 'PREFIX',
103 help = 'add PREFIX to the [... PATCH ...] prefix'),
9a316368
CM
104 make_option('-t', '--template', metavar = 'FILE',
105 help = 'use FILE as the message template'),
e3e05587
CM
106 make_option('-c', '--cover', metavar = 'FILE',
107 help = 'send FILE as the cover message'),
0ba13ee9 108 make_option('-e', '--edit-cover',
e3e05587
CM
109 help = 'edit the cover message before sending',
110 action = 'store_true'),
0ba13ee9
KH
111 make_option('-E', '--edit-patches',
112 help = 'edit each patch before sending',
113 action = 'store_true'),
b4bddc06
CM
114 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
115 help = 'sleep for SECONDS between e-mails sending'),
116 make_option('--refid',
d0d139a3 117 help = 'use REFID as the reference id'),
eb026d93
B
118 make_option('-u', '--smtp-user', metavar = 'USER',
119 help = 'username for SMTP authentication'),
120 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
2f7c8b0b
CM
121 help = 'username for SMTP authentication'),
122 make_option('-b', '--branch',
29f00589
CM
123 help = 'use BRANCH instead of the default one'),
124 make_option('-m', '--mbox',
125 help = 'generate an mbox file instead of sending',
126 action = 'store_true')]
b4bddc06
CM
127
128
dae0f0be
CM
129def __get_maintainer():
130 """Return the 'authname <authemail>' string as read from the
131 configuration file
132 """
133 if config.has_option('stgit', 'authname') \
134 and config.has_option('stgit', 'authemail'):
135 return '%s <%s>' % (config.get('stgit', 'authname'),
136 config.get('stgit', 'authemail'))
137 else:
138 return None
139
7cc615f3 140def __parse_addresses(addresses):
b4bddc06
CM
141 """Return a two elements tuple: (from, [to])
142 """
7cc615f3
CL
143 def __addr_list(addrs):
144 m = re.search('[^@\s<,]+@[^>\s,]+', addrs);
d60cd083
CM
145 if (m == None):
146 return []
7cc615f3 147 return [ m.group() ] + __addr_list(addrs[m.end():])
b4bddc06
CM
148
149 from_addr_list = []
150 to_addr_list = []
7cc615f3 151 for line in addresses.split('\n'):
b4bddc06
CM
152 if re.match('from:\s+', line, re.I):
153 from_addr_list += __addr_list(line)
154 elif re.match('(to|cc|bcc):\s+', line, re.I):
155 to_addr_list += __addr_list(line)
156
24aadb3f 157 if len(from_addr_list) == 0:
b4bddc06
CM
158 raise CmdException, 'No "From" address'
159 if len(to_addr_list) == 0:
160 raise CmdException, 'No "To/Cc/Bcc" addresses'
161
162 return (from_addr_list[0], to_addr_list)
163
eb026d93
B
164def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
165 smtpuser, smtppassword):
b4bddc06
CM
166 """Send the message using the given SMTP server
167 """
168 try:
169 s = smtplib.SMTP(smtpserver)
170 except Exception, err:
171 raise CmdException, str(err)
172
173 s.set_debuglevel(0)
174 try:
eb026d93
B
175 if smtpuser and smtppassword:
176 s.ehlo()
177 s.login(smtpuser, smtppassword)
178
b4bddc06
CM
179 s.sendmail(from_addr, to_addr_list, msg)
180 # give recipients a chance of receiving patches in the correct order
181 time.sleep(sleep)
182 except Exception, err:
183 raise CmdException, str(err)
184
185 s.quit()
186
29f00589
CM
187def __write_mbox(from_addr, msg):
188 """Write an mbox like file to the standard output
189 """
190 r = re.compile('^From ', re.M)
191 msg = r.sub('>\g<0>', msg)
192
193 print 'From %s %s' % (from_addr, datetime.datetime.today().ctime())
194 print msg
195 print
196
f8d1cf65
CM
197def __build_address_headers(tmpl, options, extra_cc = []):
198 """Build the address headers and check existing headers in the
199 template.
200 """
201 def csv(lst):
d884c4d8
CM
202 s = ''
203 for i in lst:
204 if not i:
205 continue
206 if s:
207 s += ', ' + i
208 else:
209 s = i
210 return s
f8d1cf65
CM
211
212 def replace_header(header, addr, tmpl):
213 r = re.compile('^' + header + ':\s+.+$', re.I | re.M)
214 if r.search(tmpl):
215 tmpl = r.sub('\g<0>, ' + addr, tmpl, 1)
216 h = ''
217 else:
218 h = header + ': ' + addr
219
220 return tmpl, h
221
222 headers = ''
223 to_addr = ''
224 cc_addr = ''
225 bcc_addr = ''
226
d884c4d8
CM
227 if config.has_option('stgit', 'autobcc'):
228 autobcc = config.get('stgit', 'autobcc')
229 else:
230 autobcc = ''
231
e83b3149 232 if options.to:
f8d1cf65 233 to_addr = csv(options.to)
e83b3149 234 if options.cc:
f8d1cf65
CM
235 cc_addr = csv(options.cc + extra_cc)
236 elif extra_cc:
237 cc_addr = csv(extra_cc)
e83b3149 238 if options.bcc:
d884c4d8
CM
239 bcc_addr = csv(options.bcc + [autobcc])
240 elif autobcc:
241 bcc_addr = autobcc
f8d1cf65
CM
242
243 # replace existing headers
244 if to_addr:
245 tmpl, h = replace_header('To', to_addr, tmpl)
246 if h:
247 headers += h + '\n'
248 if cc_addr:
249 tmpl, h = replace_header('Cc', cc_addr, tmpl)
250 if h:
251 headers += h + '\n'
252 if bcc_addr:
253 tmpl, h = replace_header('Bcc', bcc_addr, tmpl)
254 if h:
255 headers += h + '\n'
256
257 return tmpl, headers
258
259def __get_signers_list(msg):
260 """Return the address list generated from signed-off-by and
261 acked-by lines in the message.
262 """
263 addr_list = []
264
265 r = re.compile('^(signed-off-by|acked-by):\s+(.+)$', re.I)
266 for line in msg.split('\n'):
267 m = r.match(line)
268 if m:
269 addr_list.append(m.expand('\g<2>'))
270
271 return addr_list
e83b3149 272
19a56fa1
CM
273def __build_extra_headers():
274 """Build extra headers like content-type etc.
275 """
276 headers = 'Content-Type: text/plain; charset=utf-8; format=fixed\n'
277 headers += 'Content-Transfer-Encoding: 8bit\n'
278 headers += 'User-Agent: StGIT/%s\n' % version.version
279
280 return headers
281
0ba13ee9
KH
282def edit_message(msg):
283 fname = '.stgitmail.txt'
284
285 # create the initial file
286 f = file(fname, 'w')
287 f.write(msg)
288 f.close()
289
290 # the editor
291 if config.has_option('stgit', 'editor'):
292 editor = config.get('stgit', 'editor')
293 elif 'EDITOR' in os.environ:
294 editor = os.environ['EDITOR']
295 else:
296 editor = 'vi'
297 editor += ' %s' % fname
298
299 print 'Invoking the editor: "%s"...' % editor,
300 sys.stdout.flush()
301 print 'done (exit code: %d)' % os.system(editor)
302
303 # read the message back
304 f = file(fname)
305 msg = f.read()
306 f.close()
307
308 return msg
309
e3e05587
CM
310def __build_cover(tmpl, total_nr, msg_id, options):
311 """Build the cover message (series description) to be sent via SMTP
b4bddc06 312 """
dae0f0be
CM
313 maintainer = __get_maintainer()
314 if not maintainer:
315 maintainer = ''
316
f8d1cf65 317 tmpl, headers_end = __build_address_headers(tmpl, options)
2bb96902 318 headers_end += 'Message-Id: %s\n' % msg_id