Add patch history support
[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'),
d0d139a3
CM
93 make_option('-v', '--version', metavar = 'VERSION',
94 help = 'add VERSION to the [PATCH ...] prefix'),
9a316368
CM
95 make_option('-t', '--template', metavar = 'FILE',
96 help = 'use FILE as the message template'),
e3e05587
CM
97 make_option('-c', '--cover', metavar = 'FILE',
98 help = 'send FILE as the cover message'),
99 make_option('-e', '--edit',
100 help = 'edit the cover message before sending',
101 action = 'store_true'),
b4bddc06
CM
102 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
103 help = 'sleep for SECONDS between e-mails sending'),
104 make_option('--refid',
d0d139a3 105 help = 'use REFID as the reference id'),
eb026d93
B
106 make_option('-u', '--smtp-user', metavar = 'USER',
107 help = 'username for SMTP authentication'),
108 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
2f7c8b0b
CM
109 help = 'username for SMTP authentication'),
110 make_option('-b', '--branch',
29f00589
CM
111 help = 'use BRANCH instead of the default one'),
112 make_option('-m', '--mbox',
113 help = 'generate an mbox file instead of sending',
114 action = 'store_true')]
b4bddc06
CM
115
116
dae0f0be
CM
117def __get_maintainer():
118 """Return the 'authname <authemail>' string as read from the
119 configuration file
120 """
121 if config.has_option('stgit', 'authname') \
122 and config.has_option('stgit', 'authemail'):
123 return '%s <%s>' % (config.get('stgit', 'authname'),
124 config.get('stgit', 'authemail'))
125 else:
126 return None
127
7cc615f3 128def __parse_addresses(addresses):
b4bddc06
CM
129 """Return a two elements tuple: (from, [to])
130 """
7cc615f3
CL
131 def __addr_list(addrs):
132 m = re.search('[^@\s<,]+@[^>\s,]+', addrs);
d60cd083
CM
133 if (m == None):
134 return []
7cc615f3 135 return [ m.group() ] + __addr_list(addrs[m.end():])
b4bddc06
CM
136
137 from_addr_list = []
138 to_addr_list = []
7cc615f3 139 for line in addresses.split('\n'):
b4bddc06
CM
140 if re.match('from:\s+', line, re.I):
141 from_addr_list += __addr_list(line)
142 elif re.match('(to|cc|bcc):\s+', line, re.I):
143 to_addr_list += __addr_list(line)
144
24aadb3f 145 if len(from_addr_list) == 0:
b4bddc06
CM
146 raise CmdException, 'No "From" address'
147 if len(to_addr_list) == 0:
148 raise CmdException, 'No "To/Cc/Bcc" addresses'
149
150 return (from_addr_list[0], to_addr_list)
151
eb026d93
B
152def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
153 smtpuser, smtppassword):
b4bddc06
CM
154 """Send the message using the given SMTP server
155 """
156 try:
157 s = smtplib.SMTP(smtpserver)
158 except Exception, err:
159 raise CmdException, str(err)
160
161 s.set_debuglevel(0)
162 try:
eb026d93
B
163 if smtpuser and smtppassword:
164 s.ehlo()
165 s.login(smtpuser, smtppassword)
166
b4bddc06
CM
167 s.sendmail(from_addr, to_addr_list, msg)
168 # give recipients a chance of receiving patches in the correct order
169 time.sleep(sleep)
170 except Exception, err:
171 raise CmdException, str(err)
172
173 s.quit()
174
29f00589
CM
175def __write_mbox(from_addr, msg):
176 """Write an mbox like file to the standard output
177 """
178 r = re.compile('^From ', re.M)
179 msg = r.sub('>\g<0>', msg)
180
181 print 'From %s %s' % (from_addr, datetime.datetime.today().ctime())
182 print msg
183 print
184
e83b3149
PO
185def __build_address_headers(options):
186 headers_end = ''
187 if options.to:
d60cd083
CM
188 headers_end += 'To: '
189 for to in options.to:
190 headers_end += '%s, ' % to
191 headers_end = headers_end[:-2] + '\n'
e83b3149 192 if options.cc:
d60cd083
CM
193 headers_end += 'Cc: '
194 for cc in options.cc:
195 headers_end += '%s, ' % cc
196 headers_end = headers_end[:-2] + '\n'
e83b3149 197 if options.bcc:
d60cd083
CM
198 headers_end += 'Bcc: '
199 for bcc in options.bcc:
200 headers_end += '%s, ' % bcc
201 headers_end = headers_end[:-2] + '\n'
e83b3149
PO
202 return headers_end
203
19a56fa1
CM
204def __build_extra_headers():
205 """Build extra headers like content-type etc.
206 """
207 headers = 'Content-Type: text/plain; charset=utf-8; format=fixed\n'
208 headers += 'Content-Transfer-Encoding: 8bit\n'
209 headers += 'User-Agent: StGIT/%s\n' % version.version
210
211 return headers
212
e3e05587
CM
213def __build_cover(tmpl, total_nr, msg_id, options):
214 """Build the cover message (series description) to be sent via SMTP
b4bddc06 215 """
dae0f0be
CM
216 maintainer = __get_maintainer()
217 if not maintainer:
218 maintainer = ''
219
e83b3149 220 headers_end = __build_address_headers(options)
2bb96902 221 headers_end += 'Message-Id: %s\n' % msg_id