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
, version
, templates
24 from stgit
.config
import config
27 help = 'send a patch or series of patches by e-mail'
28 usage
= """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
30 Send a patch or a range of patches by e-mail using the 'smtpserver'
31 configuration option. The From address and the e-mail format are
32 generated from the template file passed as argument to '--template'
33 (defaulting to '.git/patchmail.tmpl' or
34 '~/.stgit/templates/patchmail.tmpl' or or
35 '/usr/share/stgit/templates/patchmail.tmpl'). The To/Cc/Bcc addresses
36 can either be added to the template file or passed via the
37 corresponding command line options.
39 A preamble e-mail can be sent using the '--cover' and/or '--edit'
40 options. The first allows the user to specify a file to be used as a
41 template. The latter option will invoke the editor on the specified
42 file (defaulting to '.git/covermail.tmpl' or
43 '~/.stgit/templates/covermail.tmpl' or
44 '/usr/share/stgit/templates/covermail.tmpl').
46 All 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
48 replies to a different e-mail by using the '--refid' option.
50 SMTP authentication is also possible with '--smtp-user' and
51 '--smtp-password' options, also available as configuration settings:
52 'smtpuser' and 'smtppassword'.
54 The template e-mail headers and body must be separated by
55 '%(endofheaders)s' variable, which is replaced by StGIT with
56 additional headers and a blank line. The patch e-mail template accepts
57 the following variables:
59 %(patch)s - patch name
60 %(maintainer)s - 'authname <authemail>' as read from the config file
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
67 %(version)s - ' version' string passed on the command line (or empty)
68 %(prefix)s - 'prefix ' string passed on the command line
69 %(patchnr)s - patch number
70 %(totalnr)s - total number of patches to be sent
71 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
72 %(authname)s - author's name
73 %(authemail)s - author's email
74 %(authdate)s - patch creation date
75 %(commname)s - committer's name
76 %(commemail)s - committer's e-mail
78 For the preamble e-mail template, only the %(maintainer)s, %(date)s,
79 %(endofheaders)s, %(version)s, %(patchnr)s, %(totalnr)s and %(number)s
80 variables are supported."""
82 options
= [make_option('-a', '--all',
83 help = 'e-mail all the applied patches',
84 action
= 'store_true'),
86 help = 'add TO to the To: list',
89 help = 'add CC to the Cc: list',
92 help = 'add BCC to the Bcc: list',
95 help = 'automatically cc the patch signers',
96 action
= 'store_true'),
97 make_option('--noreply',
98 help = 'do not send subsequent messages as replies',
99 action
= 'store_true'),
100 make_option('-v', '--version', metavar
= 'VERSION',
101 help = 'add VERSION to the [PATCH ...] prefix'),
102 make_option('--prefix', metavar
= 'PREFIX',
103 help = 'add PREFIX to the [... PATCH ...] prefix'),
104 make_option('-t', '--template', metavar
= 'FILE',
105 help = 'use FILE as the message template'),
106 make_option('-c', '--cover', metavar
= 'FILE',
107 help = 'send FILE as the cover message'),
108 make_option('-e', '--edit',
109 help = 'edit the cover message before sending',
110 action
= 'store_true'),
111 make_option('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
112 help = 'sleep for SECONDS between e-mails sending'),
113 make_option('--refid',
114 help = 'use REFID as the reference id'),
115 make_option('-u', '--smtp-user', metavar
= 'USER',
116 help = 'username for SMTP authentication'),
117 make_option('-p', '--smtp-password', metavar
= 'PASSWORD',
118 help = 'username for SMTP authentication'),
119 make_option('-b', '--branch',
120 help = 'use BRANCH instead of the default one'),
121 make_option('-m', '--mbox',
122 help = 'generate an mbox file instead of sending',
123 action
= 'store_true')]
126 def __get_maintainer():
127 """Return the 'authname <authemail>' string as read from the
130 if config
.has_option('stgit', 'authname') \
131 and config
.has_option('stgit', 'authemail'):
132 return '%s <%s>' %
(config
.get('stgit', 'authname'),
133 config
.get('stgit', 'authemail'))
137 def __parse_addresses(addresses
):
138 """Return a two elements tuple: (from, [to])
140 def __addr_list(addrs
):
141 m
= re
.search('[^@\s<,]+@[^>\s,]+', addrs
);
144 return [ m
.group() ] + __addr_list(addrs
[m
.end():])
148 for line
in addresses
.split('\n'):
149 if re
.match('from:\s+', line
, re
.I
):
150 from_addr_list
+= __addr_list(line
)
151 elif re
.match('(to|cc|bcc):\s+', line
, re
.I
):
152 to_addr_list
+= __addr_list(line
)
154 if len(from_addr_list
) == 0:
155 raise CmdException
, 'No "From" address'
156 if len(to_addr_list
) == 0:
157 raise CmdException
, 'No "To/Cc/Bcc" addresses'
159 return (from_addr_list
[0], to_addr_list
)
161 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
162 smtpuser
, smtppassword
):
163 """Send the message using the given SMTP server
166 s
= smtplib
.SMTP(smtpserver
)
167 except Exception, err
:
168 raise CmdException
, str(err
)
172 if smtpuser
and smtppassword
:
174 s
.login(smtpuser
, smtppassword
)
176 s
.sendmail(from_addr
, to_addr_list
, msg
)
177 # give recipients a chance of receiving patches in the correct order
179 except Exception, err
:
180 raise CmdException
, str(err
)
184 def __write_mbox(from_addr
, msg
):
185 """Write an mbox like file to the standard output
187 r
= re
.compile('^From ', re
.M
)
188 msg
= r
.sub('>\g<0>', msg
)
190 print 'From %s %s' %
(from_addr
, datetime
.datetime
.today().ctime())
194 def __build_address_headers(tmpl
, options
, extra_cc
= []):
195 """Build the address headers and check existing headers in the
209 def replace_header(header
, addr
, tmpl
):
210 r
= re
.compile('^' + header
+ ':\s+.+$', re
.I | re
.M
)
212 tmpl
= r
.sub('\g<0>, ' + addr
, tmpl
, 1)
215 h
= header
+ ': ' + addr
224 if config
.has_option('stgit', 'autobcc'):
225 autobcc
= config
.get('stgit', 'autobcc')
230 to_addr
= csv(options
.to
)
232 cc_addr
= csv(options
.cc
+ extra_cc
)
234 cc_addr
= csv(extra_cc
)
236 bcc_addr
= csv(options
.bcc
+ [autobcc
])
240 # replace existing headers
242 tmpl
, h
= replace_header('To', to_addr
, tmpl
)
246 tmpl
, h
= replace_header('Cc', cc_addr
, tmpl
)
250 tmpl
, h
= replace_header('Bcc', bcc_addr
, tmpl
)
256 def __get_signers_list(msg
):
257 """Return the address list generated from signed-off-by and
258 acked-by lines in the message.
262 r
= re
.compile('^(signed-off-by|acked-by):\s+(.+)$', re
.I
)
263 for line
in msg
.split('\n'):
266 addr_list
.append(m
.expand('\g<2>'))
270 def __build_extra_headers():
271 """Build extra headers like content-type etc.
273 headers
= 'Content-Type: text/plain; charset=utf-8; format=fixed\n'
274 headers
+= 'Content-Transfer-Encoding: 8bit\n'
275 headers
+= 'User-Agent: StGIT/%s\n' % version
.version
279 def __build_cover(tmpl
, total_nr
, msg_id
, options
):
280 """Build the cover message (series description) to be sent via SMTP
282 maintainer
= __get_maintainer()
286 tmpl
, headers_end
= __build_address_headers(tmpl
, options
)
287 headers_end
+= 'Message-Id: %s\n' % msg_id
289 headers_end
+= "In-Reply-To: %s\n" % options
.refid
290 headers_end
+= "References: %s\n" % options
.refid
291 headers_end
+= __build_extra_headers()
294 version_str
= ' %s' % options
.version
299 prefix_str
= options
.prefix
+ ' '
303 total_nr_str
= str(total_nr
)
304 patch_nr_str
= '0'.zfill(len(total_nr_str
))
306 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
310 tmpl_dict
= {'maintainer': maintainer
,
311 'endofheaders': headers_end
,
312 'date': email
.Utils
.formatdate(localtime
= True),
313 'version': version_str
,
314 'prefix': prefix_str
,
315 'patchnr': patch_nr_str
,
316 'totalnr': total_nr_str
,
317 'number': number_str
}
320 msg
= tmpl % tmpl_dict
321 except KeyError, err
:
322 raise CmdException
, 'Unknown patch template variable: %s' \
325 raise CmdException
, 'Only "%(name)s" variables are ' \
326 'supported in the patch template'
329 fname
= '.stgitmail.txt'
331 # create the initial file
332 f
= file(fname
, 'w+')
337 if config
.has_option('stgit', 'editor'):
338 editor
= config
.get('stgit', 'editor')
339 elif 'EDITOR' in os
.environ
:
340 editor
= os
.environ
['EDITOR']
343 editor
+= ' %s' % fname
345 print 'Invoking the editor: "%s"...' % editor
,
347 print 'done (exit code: %d)' % os
.system(editor
)
349 # read the message back
354 return msg
.strip('\n')
356 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
357 """Build the message to be sent via SMTP
359 p
= crt_series
.get_patch(patch
)
361 descr
= p
.get_description().strip()
362 descr_lines
= descr
.split('\n')
364 short_descr
= descr_lines
[0].rstrip()
365 long_descr
= reduce(lambda x
, y
: x
+ '\n' + y
,
366 descr_lines
[1:], '').lstrip()
368 maintainer
= __get_maintainer()
370 maintainer
= '%s <%s>' %
(p
.get_commname(), p
.get_commemail())
373 extra_cc
= __get_signers_list(descr
)
377 tmpl
, headers_end
= __build_address_headers(tmpl
, options
, extra_cc
)
378 headers_end
+= 'Message-Id: %s\n' % msg_id
380 headers_end
+= "In-Reply-To: %s\n" % ref_id
381 headers_end
+= "References: %s\n" % ref_id
382 headers_end
+= __build_extra_headers()
385 version_str
= ' %s' % options
.version
390 prefix_str
= options
.prefix
+ ' '
394 total_nr_str
= str(total_nr
)
395 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
397 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
401 tmpl_dict
= {'patch': patch
,
402 'maintainer': maintainer
,
403 'shortdescr': short_descr
,
404 'longdescr': long_descr
,
405 'endofheaders': headers_end
,
406 'diff': git
.diff(rev1
= git_id('%s//bottom' % patch
),
407 rev2
= git_id('%s//top' % patch
)),
408 'diffstat': git
.diffstat(rev1
= git_id('%s//bottom'%patch
),
409 rev2
= git_id('%s//top' % patch
)),
410 'date': email
.Utils
.formatdate(localtime
= True),
411 'version': version_str
,
412 'prefix': prefix_str
,
413 'patchnr': patch_nr_str
,
414 'totalnr': total_nr_str
,
415 'number': number_str
,
416 'authname': p
.get_authname(),
417 'authemail': p
.get_authemail(),
418 'authdate': p
.get_authdate(),
419 'commname': p
.get_commname(),
420 'commemail': p
.get_commemail()}
421 for key
in tmpl_dict
:
422 if not tmpl_dict
[key
]:
426 msg
= tmpl % tmpl_dict
427 except KeyError, err
:
428 raise CmdException
, 'Unknown patch template variable: %s' \
431 raise CmdException
, 'Only "%(name)s" variables are ' \
432 'supported in the patch template'
434 return msg
.strip('\n')
436 def func(parser
, options
, args
):
437 """Send the patches by e-mail using the patchmail.tmpl file as
440 smtpserver
= config
.get('stgit', 'smtpserver')
444 if config
.has_option('stgit', 'smtpuser'):
445 smtpuser
= config
.get('stgit', 'smtpuser')
446 if config
.has_option('stgit', 'smtppassword'):
447 smtppassword
= config
.get('stgit', 'smtppassword')
449 applied
= crt_series
.get_applied()
454 patches
= parse_patches(args
, applied
)
456 raise CmdException
, 'Incorrect options. Unknown patches to send'
458 if options
.smtp_password
:
459 smtppassword
= options
.smtp_password
461 if options
.smtp_user
:
462 smtpuser
= options
.smtp_user
464 if (smtppassword
and not smtpuser
):
465 raise CmdException
, 'SMTP password supplied, username needed'
466 if (smtpuser
and not smtppassword
):
467 raise CmdException
, 'SMTP username supplied, password needed'
469 total_nr
= len(patches
)
471 raise CmdException
, 'No patches to send'
476 ref_id
= options
.refid
478 if options
.sleep
!= None:
479 sleep
= options
.sleep
481 sleep
= config
.getint('stgit', 'smtpdelay')
483 # send the cover message (if any)
484 if options
.cover
or options
.edit
:
485 # find the template file
487 tmpl
= file(options
.cover
).read()
489 tmpl
= templates
.get_template('covermail.tmpl')
491 raise CmdException
, 'No cover message template file found'
493 msg_id
= email
.Utils
.make_msgid('stgit')
494 msg
= __build_cover(tmpl
, total_nr
, msg_id
, options
)
495 from_addr
, to_addr_list
= __parse_addresses(msg
)
497 # subsequent e-mails are seen as replies to the first one
498 if not options
.noreply
:
502 __write_mbox(from_addr
, msg
)
504 print 'Sending the cover message...',
506 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
507 smtpuser
, smtppassword
)
512 tmpl
= file(options
.template
).read()
514 tmpl
= templates
.get_template('patchmail.tmpl')
516 raise CmdException
, 'No e-mail template file found'
518 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
519 msg_id
= email
.Utils
.make_msgid('stgit')
520 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
522 from_addr
, to_addr_list
= __parse_addresses(msg
)
524 # subsequent e-mails are seen as replies to the first one
525 if not options
.noreply
and not ref_id
:
529 __write_mbox(from_addr
, msg
)
531 print 'Sending patch "%s"...' % p
,
533 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
534 smtpuser
, smtppassword
)