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
, datetime
, smtplib
, email
.Utils
19 from optparse
import OptionParser
, make_option
21 from stgit
.commands
.common
import *
22 from stgit
.utils
import *
23 from stgit
import stack
, git
24 from stgit
.config
import config
27 help = 'send a patch or series of patches by e-mail'
28 usage
= """%prog [options] [<patch> [<patch2...]]
30 Send a patch or a range of patches (defaulting to the applied patches)
31 by e-mail using the 'smtpserver' configuration option. The From
32 address and the e-mail format are generated from the template file
33 passed as argument to '--template' (defaulting to .git/patchmail.tmpl
34 or /usr/share/stgit/templates/patchmail.tmpl). The To/Cc/Bcc addresses
35 can either be added to the template file or passed via the
36 corresponding command line options.
38 A preamble e-mail can be sent using the '--cover' and/or '--edit'
39 options. The first allows the user to specify a file to be used as a
40 template. The latter option will invoke the editor on the specified
41 file (defaulting to .git/covermail.tmpl or
42 /usr/share/stgit/templates/covermail.tmpl).
44 All the subsequent e-mails appear as replies to the first e-mail sent
45 (either the preamble or the first patch). E-mails can be seen as
46 replies to a different e-mail by using the '--refid' option.
48 SMTP authentication is also possible with '--smtp-user' and
49 '--smtp-password' options, also available as configuration settings:
50 'smtpuser' and 'smtppassword'.
52 The template e-mail headers and body must be separated by
53 '%(endofheaders)s' variable, which is replaced by StGIT with
54 additional headers and a blank line. The patch e-mail template accepts
55 the following variables:
57 %(patch)s - patch name
58 %(maintainer)s - 'authname <authemail>' as read from the config file
59 %(shortdescr)s - the first line of the patch description
60 %(longdescr)s - the rest of the patch description, after the first line
61 %(endofheaders)s - delimiter between e-mail headers and body
62 %(diff)s - unified diff of the patch
63 %(diffstat)s - diff statistics
64 %(date)s - current date/time
65 %(version)s - ' version' string passed on the command line (or empty)
66 %(patchnr)s - patch number
67 %(totalnr)s - total number of patches to be sent
68 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
69 %(authname)s - author's name
70 %(authemail)s - author's email
71 %(authdate)s - patch creation date
72 %(commname)s - committer's name
73 %(commemail)s - committer's e-mail
75 For the preamble e-mail template, only the %(maintainer)s, %(date)s,
76 %(endofheaders)s, %(version)s, %(patchnr)s, %(totalnr)s and %(number)s
77 variables are supported."""
79 options
= [make_option('-a', '--all',
80 help = 'e-mail all the applied patches',
81 action
= 'store_true'),
82 make_option('-r', '--range',
83 metavar
= '[PATCH1][:[PATCH2]]',
84 help = 'e-mail patches between PATCH1 and PATCH2'),
86 help = 'add TO to the To: list',
89 help = 'add CC to the Cc: list',
92 help = 'add BCC to the Bcc: list',
94 make_option('-v', '--version', metavar
= 'VERSION',
95 help = 'add VERSION to the [PATCH ...] prefix'),
96 make_option('-t', '--template', metavar
= 'FILE',
97 help = 'use FILE as the message template'),
98 make_option('-c', '--cover', metavar
= 'FILE',
99 help = 'send FILE as the cover message'),
100 make_option('-e', '--edit',
101 help = 'edit the cover message before sending',
102 action
= 'store_true'),
103 make_option('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
104 help = 'sleep for SECONDS between e-mails sending'),
105 make_option('--refid',
106 help = 'use REFID as the reference id'),
107 make_option('-u', '--smtp-user', metavar
= 'USER',
108 help = 'username for SMTP authentication'),
109 make_option('-p', '--smtp-password', metavar
= 'PASSWORD',
110 help = 'username for SMTP authentication'),
111 make_option('-b', '--branch',
112 help = 'use BRANCH instead of the default one'),
113 make_option('-m', '--mbox',
114 help = 'generate an mbox file instead of sending',
115 action
= 'store_true')]
118 def __get_maintainer():
119 """Return the 'authname <authemail>' string as read from the
122 if config
.has_option('stgit', 'authname') \
123 and config
.has_option('stgit', 'authemail'):
124 return '%s <%s>' %
(config
.get('stgit', 'authname'),
125 config
.get('stgit', 'authemail'))
129 def __parse_addresses(addresses
):
130 """Return a two elements tuple: (from, [to])
132 def __addr_list(addrs
):
133 m
= re
.search('[^@\s<,]+@[^>\s,]+', addrs
);
136 return [ m
.group() ] + __addr_list(addrs
[m
.end():])
140 for line
in addresses
.split('\n'):
141 if re
.match('from:\s+', line
, re
.I
):
142 from_addr_list
+= __addr_list(line
)
143 elif re
.match('(to|cc|bcc):\s+', line
, re
.I
):
144 to_addr_list
+= __addr_list(line
)
146 if len(from_addr_list
) == 0:
147 raise CmdException
, 'No "From" address'
148 if len(to_addr_list
) == 0:
149 raise CmdException
, 'No "To/Cc/Bcc" addresses'
151 return (from_addr_list
[0], to_addr_list
)
153 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
154 smtpuser
, smtppassword
):
155 """Send the message using the given SMTP server
158 s
= smtplib
.SMTP(smtpserver
)
159 except Exception, err
:
160 raise CmdException
, str(err
)
164 if smtpuser
and smtppassword
:
166 s
.login(smtpuser
, smtppassword
)
168 s
.sendmail(from_addr
, to_addr_list
, msg
)
169 # give recipients a chance of receiving patches in the correct order
171 except Exception, err
:
172 raise CmdException
, str(err
)
176 def __write_mbox(from_addr
, msg
):
177 """Write an mbox like file to the standard output
179 r
= re
.compile('^From ', re
.M
)
180 msg
= r
.sub('>\g<0>', msg
)
182 print 'From %s %s' %
(from_addr
, datetime
.datetime
.today().ctime())
186 def __build_address_headers(options
):
189 headers_end
+= 'To: '
190 for to
in options
.to
:
191 headers_end
+= '%s, ' % to
192 headers_end
= headers_end
[:-2] + '\n'
194 headers_end
+= 'Cc: '
195 for cc
in options
.cc
:
196 headers_end
+= '%s, ' % cc
197 headers_end
= headers_end
[:-2] + '\n'
199 headers_end
+= 'Bcc: '
200 for bcc
in options
.bcc
:
201 headers_end
+= '%s, ' % bcc
202 headers_end
= headers_end
[:-2] + '\n'
205 def __build_cover(tmpl
, total_nr
, msg_id
, options
):
206 """Build the cover message (series description) to be sent via SMTP
208 maintainer
= __get_maintainer()
212 headers_end
= __build_address_headers(options
)
213 headers_end
+= 'Message-Id: %s\n' % msg_id
215 headers_end
+= "In-Reply-To: %s\n" % options
.refid
216 headers_end
+= "References: %s\n" % options
.refid
219 version_str
= ' %s' % options
.version
223 total_nr_str
= str(total_nr
)
224 patch_nr_str
= '0'.zfill(len(total_nr_str
))
226 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
230 tmpl_dict
= {'maintainer': maintainer
,
231 'endofheaders': headers_end
,
232 'date': email
.Utils
.formatdate(localtime
= True),
233 'version': version_str
,
234 'patchnr': patch_nr_str
,
235 'totalnr': total_nr_str
,
236 'number': number_str
}
239 msg
= tmpl % tmpl_dict
240 except KeyError, err
:
241 raise CmdException
, 'Unknown patch template variable: %s' \
244 raise CmdException
, 'Only "%(name)s" variables are ' \
245 'supported in the patch template'
248 fname
= '.stgitmail.txt'
250 # create the initial file
251 f
= file(fname
, 'w+')
256 if config
.has_option('stgit', 'editor'):
257 editor
= config
.get('stgit', 'editor')
258 elif 'EDITOR' in os
.environ
:
259 editor
= os
.environ
['EDITOR']
262 editor
+= ' %s' % fname
264 print 'Invoking the editor: "%s"...' % editor
,
266 print 'done (exit code: %d)' % os
.system(editor
)
268 # read the message back
273 return msg
.strip('\n')
275 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
276 """Build the message to be sent via SMTP
278 p
= crt_series
.get_patch(patch
)
280 descr
= p
.get_description().strip()
281 descr_lines
= descr
.split('\n')
283 short_descr
= descr_lines
[0].rstrip()
284 long_descr
= reduce(lambda x
, y
: x
+ '\n' + y
,
285 descr_lines
[1:], '').lstrip()
287 maintainer
= __get_maintainer()
289 maintainer
= '%s <%s>' %
(p
.get_commname(), p
.get_commemail())
291 headers_end
= __build_address_headers(options
)
292 headers_end
+= 'Message-Id: %s\n' % msg_id
294 headers_end
+= "In-Reply-To: %s\n" % ref_id
295 headers_end
+= "References: %s\n" % ref_id
298 version_str
= ' %s' % options
.version
302 total_nr_str
= str(total_nr
)
303 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
305 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
309 tmpl_dict
= {'patch': patch
,
310 'maintainer': maintainer
,
311 'shortdescr': short_descr
,
312 'longdescr': long_descr
,
313 'endofheaders': headers_end
,
314 'diff': git
.diff(rev1
= git_id('%s/bottom' % patch
),
315 rev2
= git_id('%s/top' % patch
)),
316 'diffstat': git
.diffstat(rev1
= git_id('%s/bottom'%patch
),
317 rev2
= git_id('%s/top' % patch
)),
318 'date': email
.Utils
.formatdate(localtime
= True),
319 'version': version_str
,
320 'patchnr': patch_nr_str
,
321 'totalnr': total_nr_str
,
322 'number': number_str
,
323 'authname': p
.get_authname(),
324 'authemail': p
.get_authemail(),
325 'authdate': p
.get_authdate(),
326 'commname': p
.get_commname(),
327 'commemail': p
.get_commemail()}
328 for key
in tmpl_dict
:
329 if not tmpl_dict
[key
]:
333 msg
= tmpl % tmpl_dict
334 except KeyError, err
:
335 raise CmdException
, 'Unknown patch template variable: %s' \
338 raise CmdException
, 'Only "%(name)s" variables are ' \
339 'supported in the patch template'
341 return msg
.strip('\n')
343 def func(parser
, options
, args
):
344 """Send the patches by e-mail using the patchmail.tmpl file as
347 if not config
.has_option('stgit', 'smtpserver'):
348 raise CmdException
, 'smtpserver not defined'
349 smtpserver
= config
.get('stgit', 'smtpserver')
353 if config
.has_option('stgit', 'smtpuser'):
354 smtpuser
= config
.get('stgit', 'smtpuser')
355 if config
.has_option('stgit', 'smtppassword'):
356 smtppassword
= config
.get('stgit', 'smtppassword')
358 applied
= crt_series
.get_applied()
359 unapplied
= crt_series
.get_unapplied()
363 if patch
in unapplied
:
364 raise CmdException
, 'Patch "%s" not applied' % patch
365 if not patch
in applied
:
366 raise CmdException
, 'Patch "%s" does not exist' % patch
371 boundaries
= options
.range.split(':')
372 if len(boundaries
) == 1:
373 start
= boundaries
[0]
375 elif len(boundaries
) == 2:
376 if boundaries
[0] == '':
379 start
= boundaries
[0]
380 if boundaries
[1] == '':
385 raise CmdException
, 'incorrect parameters to "--range"'
388 start_idx
= applied
.index(start
)
390 if start
in unapplied
:
391 raise CmdException
, 'Patch "%s" not applied' % start
393 raise CmdException
, 'Patch "%s" does not exist' % start
395 stop_idx
= applied
.index(stop
) + 1
397 if stop
in unapplied
:
398 raise CmdException
, 'Patch "%s" not applied' % stop
400 raise CmdException
, 'Patch "%s" does not exist' % stop
402 if start_idx
>= stop_idx
:
403 raise CmdException
, 'Incorrect patch range order'
405 patches
= applied
[start_idx
:stop_idx
]
407 raise CmdException
, 'Incorrect options. Unknown patches to send'
409 if options
.smtp_password
:
410 smtppassword
= options
.smtp_password
412 if options
.smtp_user
:
413 smtpuser
= options
.smtp_user
415 if (smtppassword
and not smtpuser
):
416 raise CmdException
, 'SMTP password supplied, username needed'
417 if (smtpuser
and not smtppassword
):
418 raise CmdException
, 'SMTP username supplied, password needed'
420 total_nr
= len(patches
)
422 raise CmdException
, 'No patches to send'
424 ref_id
= options
.refid
426 if options
.sleep
!= None:
427 sleep
= options
.sleep
431 # send the cover message (if any)
432 if options
.cover
or options
.edit
:
433 # find the template file
435 tfile_list
= [options
.cover
]
437 tfile_list
= [os
.path
.join(git
.get_base_dir(), 'covermail.tmpl'),
438 os
.path
.join(sys
.prefix
,
439 'share/stgit/templates/covermail.tmpl')]
442 for tfile
in tfile_list
:
443 if os
.path
.isfile(tfile
):
444 tmpl
= file(tfile
).read()
447 raise CmdException
, 'No cover message template file found'
449 msg_id
= email
.Utils
.make_msgid('stgit')
450 msg
= __build_cover(tmpl
, total_nr
, msg_id
, options
)
451 from_addr
, to_addr_list
= __parse_addresses(msg
)
453 # subsequent e-mails are seen as replies to the first one
457 __write_mbox(from_addr
, msg
)
459 print 'Sending the cover message...',
461 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
462 smtpuser
, smtppassword
)
467 tfile_list
= [options
.template
]
469 tfile_list
= [os
.path
.join(git
.get_base_dir(), 'patchmail.tmpl'),
470 os
.path
.join(sys
.prefix
,
471 'share/stgit/templates/patchmail.tmpl')]
473 for tfile
in tfile_list
:
474 if os
.path
.isfile(tfile
):
475 tmpl
= file(tfile
).read()
478 raise CmdException
, 'No e-mail template file found'
480 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
481 msg_id
= email
.Utils
.make_msgid('stgit')
482 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
484 from_addr
, to_addr_list
= __parse_addresses(msg
)
486 # subsequent e-mails are seen as replies to the first one
491 __write_mbox(from_addr
, msg
)
493 print 'Sending patch "%s"...' % p
,
495 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
496 smtpuser
, smtppassword
)