Regression test for "stg assimilate"
[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
e3e05587
CM
39A preamble e-mail can be sent using the '--cover' and/or '--edit'
40options. The first allows the user to specify a file to be used as a
41template. The latter option will invoke the editor on the specified
94d18868
YD
42file (defaulting to '.git/covermail.tmpl' or
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)
26aab5b0
CM
68 %(patchnr)s - patch number
69 %(totalnr)s - total number of patches to be sent
b8d258e5 70 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
26aab5b0
CM
71 %(authname)s - author's name
72 %(authemail)s - author's email
73 %(authdate)s - patch creation date
74 %(commname)s - committer's name
75 %(commemail)s - committer's e-mail
76
dae0f0be 77For the preamble e-mail template, only the %(maintainer)s, %(date)s,
d0d139a3
CM
78%(endofheaders)s, %(version)s, %(patchnr)s, %(totalnr)s and %(number)s
79variables are supported."""
b4bddc06 80
9a316368
CM
81options = [make_option('-a', '--all',
82 help = 'e-mail all the applied patches',
83 action = 'store_true'),
2bb96902 84 make_option('--to',
e83b3149
PO
85 help = 'add TO to the To: list',
86 action = 'append'),
2bb96902 87 make_option('--cc',
e83b3149
PO
88 help = 'add CC to the Cc: list',
89 action = 'append'),
2bb96902 90 make_option('--bcc',
e83b3149
PO
91 help = 'add BCC to the Bcc: list',
92 action = 'append'),
f8d1cf65
CM
93 make_option('--auto',
94 help = 'automatically cc the patch signers',
95 action = 'store_true'),
d1ed3a12
CM
96 make_option('--noreply',
97 help = 'do not send subsequent messages as replies',
98 action = 'store_true'),
d0d139a3
CM
99 make_option('-v', '--version', metavar = 'VERSION',
100 help = 'add VERSION to the [PATCH ...] prefix'),
9a316368
CM
101 make_option('-t', '--template', metavar = 'FILE',
102 help = 'use FILE as the message template'),
e3e05587
CM
103 make_option('-c', '--cover', metavar = 'FILE',
104 help = 'send FILE as the cover message'),
105 make_option('-e', '--edit',
106 help = 'edit the cover message before sending',
107 action = 'store_true'),
b4bddc06
CM
108 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
109 help = 'sleep for SECONDS between e-mails sending'),
110 make_option('--refid',
d0d139a3 111 help = 'use REFID as the reference id'),
eb026d93
B
112 make_option('-u', '--smtp-user', metavar = 'USER',
113 help = 'username for SMTP authentication'),
114 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
2f7c8b0b
CM
115 help = 'username for SMTP authentication'),
116 make_option('-b', '--branch',
29f00589
CM
117 help = 'use BRANCH instead of the default one'),
118 make_option('-m', '--mbox',
119 help = 'generate an mbox file instead of sending',
120 action = 'store_true')]
b4bddc06
CM
121
122
dae0f0be
CM
123def __get_maintainer():
124 """Return the 'authname <authemail>' string as read from the
125 configuration file
126 """
127 if config.has_option('stgit', 'authname') \
128 and config.has_option('stgit', 'authemail'):
129 return '%s <%s>' % (config.get('stgit', 'authname'),
130 config.get('stgit', 'authemail'))
131 else:
132 return None
133
7cc615f3 134def __parse_addresses(addresses):
b4bddc06
CM
135 """Return a two elements tuple: (from, [to])
136 """
7cc615f3
CL
137 def __addr_list(addrs):
138 m = re.search('[^@\s<,]+@[^>\s,]+', addrs);
d60cd083
CM
139 if (m == None):
140 return []
7cc615f3 141 return [ m.group() ] + __addr_list(addrs[m.end():])
b4bddc06
CM
142
143 from_addr_list = []
144 to_addr_list = []
7cc615f3 145 for line in addresses.split('\n'):
b4bddc06
CM
146 if re.match('from:\s+', line, re.I):
147 from_addr_list += __addr_list(line)
148 elif re.match('(to|cc|bcc):\s+', line, re.I):
149 to_addr_list += __addr_list(line)
150
24aadb3f 151 if len(from_addr_list) == 0:
b4bddc06
CM
152 raise CmdException, 'No "From" address'
153 if len(to_addr_list) == 0:
154 raise CmdException, 'No "To/Cc/Bcc" addresses'
155
156 return (from_addr_list[0], to_addr_list)
157
eb026d93
B
158def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
159 smtpuser, smtppassword):
b4bddc06
CM
160 """Send the message using the given SMTP server
161 """
162 try:
163 s = smtplib.SMTP(smtpserver)
164 except Exception, err:
165 raise CmdException, str(err)
166
167 s.set_debuglevel(0)
168 try:
eb026d93
B
169 if smtpuser and smtppassword:
170 s.ehlo()
171 s.login(smtpuser, smtppassword)
172
b4bddc06
CM
173 s.sendmail(from_addr, to_addr_list, msg)
174 # give recipients a chance of receiving patches in the correct order
175 time.sleep(sleep)
176 except Exception, err:
177 raise CmdException, str(err)
178
179 s.quit()
180
29f00589
CM
181def __write_mbox(from_addr, msg):
182 """Write an mbox like file to the standard output
183 """
184 r = re.compile('^From ', re.M)
185 msg = r.sub('>\g<0>', msg)
186
187 print 'From %s %s' % (from_addr, datetime.datetime.today().ctime())
188 print msg
189 print
190
f8d1cf65
CM
191def __build_address_headers(tmpl, options, extra_cc = []):
192 """Build the address headers and check existing headers in the
193 template.
194 """
195 def csv(lst):
196 return reduce(lambda x, y: x + ', ' + y, lst)
197
198 def replace_header(header, addr, tmpl):
199 r = re.compile('^' + header + ':\s+.+$', re.I | re.M)
200 if r.search(tmpl):
201 tmpl = r.sub('\g<0>, ' + addr, tmpl, 1)
202 h = ''
203 else:
204 h = header + ': ' + addr
205
206 return tmpl, h
207
208 headers = ''
209 to_addr = ''
210 cc_addr = ''
211 bcc_addr = ''
212
e83b3149 213 if options.to:
f8d1cf65 214 to_addr = csv(options.to)
e83b3149 215 if options.cc:
f8d1cf65
CM
216 cc_addr = csv(options.cc + extra_cc)
217 elif extra_cc:
218 cc_addr = csv(extra_cc)
e83b3149 219 if options.bcc:
f8d1cf65
CM
220 bcc_addr = csv(options.bcc)
221
222 # replace existing headers
223 if to_addr:
224 tmpl, h = replace_header('To', to_addr, tmpl)
225 if h:
226 headers += h + '\n'
227 if cc_addr:
228 tmpl, h = replace_header('Cc', cc_addr, tmpl)
229 if h:
230 headers += h + '\n'
231 if bcc_addr:
232 tmpl, h = replace_header('Bcc', bcc_addr, tmpl)
233 if h:
234 headers += h + '\n'
235
236 return tmpl, headers
237
238def __get_signers_list(msg):
239 """Return the address list generated from signed-off-by and
240 acked-by lines in the message.
241 """
242 addr_list = []
243
244 r = re.compile('^(signed-off-by|acked-by):\s+(.+)$', re.I)
245 for line in msg.split('\n'):
246 m = r.match(line)
247 if m:
248 addr_list.append(m.expand('\g<2>'))
249
250 return addr_list
e83b3149 251
19a56fa1
CM
252def __build_extra_headers():
253 """Build extra headers like content-type etc.
254 """
255 headers = 'Content-Type: text/plain; charset=utf-8; format=fixed\n'
256 headers += 'Content-Transfer-Encoding: 8bit\n'
257 headers += 'User-Agent: StGIT/%s\n' % version.version
258
259 return headers
260
e3e05587
CM
261def __build_cover(tmpl, total_nr, msg_id, options):
262 """Build the cover message (series description) to be sent via SMTP
b4bddc06 263 """
dae0f0be
CM
264 maintainer = __get_maintainer()
265 if not maintainer:
266 maintainer = ''
267
f8d1cf65 268 tmpl, headers_end = __build_address_headers(tmpl, options)
2bb96902 269 headers_end += 'Message-Id: %s\n' % msg_id