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
, basedir
, version
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_extra_headers():
206 """Build extra headers like content-type etc.
208 headers
= 'Content-Type: text/plain; charset=utf-8; format=fixed\n'
209 headers
+= 'Content-Transfer-Encoding: 8bit\n'
210 headers
+= 'User-Agent: StGIT/%s\n' % version
.version
214 def __build_cover(tmpl
, total_nr
, msg_id
, options
):
215 """Build the cover message (series description) to be sent via SMTP
217 maintainer
= __get_maintainer()
221 headers_end
= __build_address_headers(options
)
222 headers_end
+= 'Message-Id: %s\n' % msg_id
224 headers_end
+= "In-Reply-To: %s\n" % options
.refid
225 headers_end
+= "References: %s\n" % options
.refid
226 headers_end
+= __build_extra_headers()
229 version_str
= ' %s' % options
.version
233 total_nr_str
= str(total_nr
)
234 patch_nr_str
= '0'.zfill(len(total_nr_str
))
236 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
240 tmpl_dict
= {'maintainer': maintainer
,
241 'endofheaders': headers_end
,
242 'date': email
.Utils
.formatdate(localtime
= True),
243 'version': version_str
,
244 'patchnr': patch_nr_str
,
245 'totalnr': total_nr_str
,
246 'number': number_str
}
249 msg
= tmpl % tmpl_dict
250 except KeyError, err
:
251 raise CmdException
, 'Unknown patch template variable: %s' \
254 raise CmdException
, 'Only "%(name)s" variables are ' \
255 'supported in the patch template'
258 fname
= '.stgitmail.txt'
260 # create the initial file
261 f
= file(fname
, 'w+')
266 if config
.has_option('stgit', 'editor'):
267 editor
= config
.get('stgit', 'editor')
268 elif 'EDITOR' in os
.environ
:
269 editor
= os
.environ
['EDITOR']
272 editor
+= ' %s' % fname
274 print 'Invoking the editor: "%s"...' % editor
,
276 print 'done (exit code: %d)' % os
.system(editor
)
278 # read the message back
283 return msg
.strip('\n')
285 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
286 """Build the message to be sent via SMTP
288 p
= crt_series
.get_patch(patch
)
290 descr
= p
.get_description().strip()
291 descr_lines
= descr
.split('\n')
293 short_descr
= descr_lines
[0].rstrip()
294 long_descr
= reduce(lambda x
, y
: x
+ '\n' + y
,
295 descr_lines
[1:], '').lstrip()
297 maintainer
= __get_maintainer()
299 maintainer
= '%s <%s>' %
(p
.get_commname(), p
.get_commemail())
301 headers_end
= __build_address_headers(options
)
302 headers_end
+= 'Message-Id: %s\n' % msg_id
304 headers_end
+= "In-Reply-To: %s\n" % ref_id
305 headers_end
+= "References: %s\n" % ref_id
306 headers_end
+= __build_extra_headers()
309 version_str
= ' %s' % options
.version
313 total_nr_str
= str(total_nr
)
314 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
316 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
320 tmpl_dict
= {'patch': patch
,
321 'maintainer': maintainer
,
322 'shortdescr': short_descr
,
323 'longdescr': long_descr
,
324 'endofheaders': headers_end
,
325 'diff': git
.diff(rev1
= git_id('%s/bottom' % patch
),
326 rev2
= git_id('%s/top' % patch
)),
327 'diffstat': git
.diffstat(rev1
= git_id('%s/bottom'%patch
),
328 rev2
= git_id('%s/top' % patch
)),
329 'date': email
.Utils
.formatdate(localtime
= True),
330 'version': version_str
,
331 'patchnr': patch_nr_str
,
332 'totalnr': total_nr_str
,
333 'number': number_str
,
334 'authname': p
.get_authname(),
335 'authemail': p
.get_authemail(),
336 'authdate': p
.get_authdate(),
337 'commname': p
.get_commname(),
338 'commemail': p
.get_commemail()}
339 for key
in tmpl_dict
:
340 if not tmpl_dict
[key
]:
344 msg
= tmpl % tmpl_dict
345 except KeyError, err
:
346 raise CmdException
, 'Unknown patch template variable: %s' \
349 raise CmdException
, 'Only "%(name)s" variables are ' \
350 'supported in the patch template'
352 return msg
.strip('\n')
354 def func(parser
, options
, args
):
355 """Send the patches by e-mail using the patchmail.tmpl file as
358 smtpserver
= config
.get('stgit', 'smtpserver')
362 if config
.has_option('stgit', 'smtpuser'):
363 smtpuser
= config
.get('stgit', 'smtpuser')
364 if config
.has_option('stgit', 'smtppassword'):
365 smtppassword
= config
.get('stgit', 'smtppassword')
367 applied
= crt_series
.get_applied()
368 unapplied
= crt_series
.get_unapplied()
372 if patch
in unapplied
:
373 raise CmdException
, 'Patch "%s" not applied' % patch
374 if not patch
in applied
:
375 raise CmdException
, 'Patch "%s" does not exist' % patch
380 boundaries
= options
.range.split(':')
381 if len(boundaries
) == 1:
382 start
= boundaries
[0]
384 elif len(boundaries
) == 2:
385 if boundaries
[0] == '':
388 start
= boundaries
[0]
389 if boundaries
[1] == '':
394 raise CmdException
, 'incorrect parameters to "--range"'
397 start_idx
= applied
.index(start
)
399 if start
in unapplied
:
400 raise CmdException
, 'Patch "%s" not applied' % start
402 raise CmdException
, 'Patch "%s" does not exist' % start
404 stop_idx
= applied
.index(stop
) + 1
406 if stop
in unapplied
:
407 raise CmdException
, 'Patch "%s" not applied' % stop
409 raise CmdException
, 'Patch "%s" does not exist' % stop
411 if start_idx
>= stop_idx
:
412 raise CmdException
, 'Incorrect patch range order'
414 patches
= applied
[start_idx
:stop_idx
]
416 raise CmdException
, 'Incorrect options. Unknown patches to send'
418 if options
.smtp_password
:
419 smtppassword
= options
.smtp_password
421 if options
.smtp_user
:
422 smtpuser
= options
.smtp_user
424 if (smtppassword
and not smtpuser
):
425 raise CmdException
, 'SMTP password supplied, username needed'
426 if (smtpuser
and not smtppassword
):
427 raise CmdException
, 'SMTP username supplied, password needed'
429 total_nr
= len(patches
)
431 raise CmdException
, 'No patches to send'
433 ref_id
= options
.refid
435 if options
.sleep
!= None:
436 sleep
= options
.sleep
438 sleep
= config
.getint('stgit', 'smtpdelay')
440 # send the cover message (if any)
441 if options
.cover
or options
.edit
:
442 # find the template file
444 tfile_list
= [options
.cover
]
446 tfile_list
= [os
.path
.join(basedir
.get(), 'covermail.tmpl'),
447 os
.path
.join(sys
.prefix
,
448 'share/stgit/templates/covermail.tmpl')]
451 for tfile
in tfile_list
:
452 if os
.path
.isfile(tfile
):
453 tmpl
= file(tfile
).read()
456 raise CmdException
, 'No cover message template file found'
458 msg_id
= email
.Utils
.make_msgid('stgit')
459 msg
= __build_cover(tmpl
, total_nr
, msg_id
, options
)
460 from_addr
, to_addr_list
= __parse_addresses(msg
)
462 # subsequent e-mails are seen as replies to the first one
466 __write_mbox(from_addr
, msg
)
468 print 'Sending the cover message...',
470 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
471 smtpuser
, smtppassword
)
476 tfile_list
= [options
.template
]
478 tfile_list
= [os
.path
.join(basedir
.get(), 'patchmail.tmpl'),
479 os
.path
.join(sys
.prefix
,
480 'share/stgit/templates/patchmail.tmpl')]
482 for tfile
in tfile_list
:
483 if os
.path
.isfile(tfile
):
484 tmpl
= file(tfile
).read()
487 raise CmdException
, 'No e-mail template file found'
489 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
490 msg_id
= email
.Utils
.make_msgid('stgit')
491 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
493 from_addr
, to_addr_list
= __parse_addresses(msg
)
495 # subsequent e-mails are seen as replies to the first one
500 __write_mbox(from_addr
, msg
)
502 print 'Sending patch "%s"...' % p
,
504 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
505 smtpuser
, smtppassword
)