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] [<patch>]
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).
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.
42 SMTP authentication is also possible with '--smtp-user' and
43 '--smtp-password' options, also available as configuration settings:
44 'smtpuser' and 'smtppassword'.
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:
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
66 For the preamble e-mail template, only the %(date)s, %(endofheaders)s
67 and %(totalnr)s variables are supported."""
69 options
= [make_option('-a', '--all',
70 help = 'e-mail all the applied patches',
71 action
= 'store_true'),
72 make_option('-r', '--range',
73 metavar
= '[PATCH1][:[PATCH2]]',
74 help = 'e-mail patches between PATCH1 and PATCH2'),
75 make_option('-t', '--template', metavar
= 'FILE',
76 help = 'use FILE as the message template'),
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',
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')]
89 def __parse_addresses(string
):
90 """Return a two elements tuple: (from, [to])
92 def __addr_list(string
):
93 return re
.split('.*?([\w\.]+@[\w\.]+)', string
)[1:-1:2]
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
)
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'
108 return (from_addr_list
[0], to_addr_list
)
110 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
111 smtpuser
, smtppassword
):
112 """Send the message using the given SMTP server
115 s
= smtplib
.SMTP(smtpserver
)
116 except Exception, err
:
117 raise CmdException
, str(err
)
121 if smtpuser
and smtppassword
:
123 s
.login(smtpuser
, smtppassword
)
125 s
.sendmail(from_addr
, to_addr_list
, msg
)
126 # give recipients a chance of receiving patches in the correct order
128 except Exception, err
:
129 raise CmdException
, str(err
)
133 def __build_first(tmpl
, total_nr
, msg_id
):
134 """Build the first message (series description) to be sent via SMTP
136 headers_end
= 'Message-Id: %s\n' %
(msg_id
)
137 total_nr_str
= str(total_nr
)
139 tmpl_dict
= {'endofheaders': headers_end
,
140 'date': email
.Utils
.formatdate(localtime
= True),
141 'totalnr': total_nr_str
}
144 msg
= tmpl % tmpl_dict
145 except KeyError, err
:
146 raise CmdException
, 'Unknown patch template variable: %s' \
149 raise CmdException
, 'Only "%(name)s" variables are ' \
150 'supported in the patch template'
155 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
= None):
156 """Build the message to be sent via SMTP
158 p
= crt_series
.get_patch(patch
)
160 descr
= p
.get_description().strip()
161 descr_lines
= descr
.split('\n')
163 short_descr
= descr_lines
[0].rstrip()
164 long_descr
= reduce(lambda x
, y
: x
+ '\n' + y
,
165 descr_lines
[1:], '').lstrip()
167 headers_end
= 'Message-Id: %s\n' %
(msg_id
)
169 headers_end
+= "In-Reply-To: %s\n" %
(ref_id
)
170 headers_end
+= "References: %s\n" %
(ref_id
)
172 total_nr_str
= str(total_nr
)
173 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
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
]:
196 msg
= tmpl % tmpl_dict
197 except KeyError, err
:
198 raise CmdException
, 'Unknown patch template variable: %s' \
201 raise CmdException
, 'Only "%(name)s" variables are ' \
202 'supported in the patch template'
207 def func(parser
, options
, args
):
208 """Send the patches by e-mail using the patchmail.tmpl file as
212 parser
.error('incorrect number of arguments')
214 if not config
.has_option('stgit', 'smtpserver'):
215 raise CmdException
, 'smtpserver not defined'
216 smtpserver
= config
.get('stgit', 'smtpserver')
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')
225 applied
= crt_series
.get_applied()
228 if args
[0] in applied
:
231 raise CmdException
, 'Patch "%s" not applied' % args
[0]
235 boundaries
= options
.range.split(':')
236 if len(boundaries
) == 1:
237 start
= boundaries
[0]
239 elif len(boundaries
) == 2:
240 if boundaries
[0] == '':
243 start
= boundaries
[0]
244 if boundaries
[1] == '':
249 raise CmdException
, 'incorrect parameters to "--range"'
252 start_idx
= applied
.index(start
)
254 raise CmdException
, 'Patch "%s" not applied' % start
256 stop_idx
= applied
.index(stop
) + 1
258 raise CmdException
, 'Patch "%s" not applied' % stop
260 if start_idx
>= stop_idx
:
261 raise CmdException
, 'Incorrect patch range order'
263 patches
= applied
[start_idx
:stop_idx
]
265 raise CmdException
, 'Incorrect options. Unknown patches to send'
267 if options
.smtp_password
:
268 smtppassword
= options
.smtp_password
270 if options
.smtp_user
:
271 smtpuser
= options
.smtp_user
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'
278 total_nr
= len(patches
)
280 raise CmdException
, 'No patches to send'
282 ref_id
= options
.refid
284 if options
.sleep
!= None:
285 sleep
= options
.sleep
289 # send the first message (if any)
291 tmpl
= file(options
.first
).read()
292 from_addr
, to_addr_list
= __parse_addresses(tmpl
)
294 msg_id
= email
.Utils
.make_msgid('stgit')
295 msg
= __build_first(tmpl
, total_nr
, msg_id
)
297 # subsequent e-mails are seen as replies to the first one
300 print 'Sending file "%s"...' % options
.first
,
303 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
304 smtpuser
, smtppassword
)
310 tfile
= options
.template
312 tfile
= os
.path
.join(git
.base_dir
, 'patchmail.tmpl')
313 tmpl
= file(tfile
).read()
315 from_addr
, to_addr_list
= __parse_addresses(tmpl
)
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
324 print 'Sending patch "%s"...' % p
,
327 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
328 smtpuser
, smtppassword
)