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
19 import email
, email
.Utils
, email
.Header
20 from optparse
import OptionParser
, make_option
22 from stgit
.commands
.common
import *
23 from stgit
.utils
import *
24 from stgit
import stack
, git
, version
, templates
25 from stgit
.config
import config
28 help = 'send a patch or series of patches by e-mail'
29 usage
= """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
31 Send a patch or a range of patches by e-mail using the 'smtpserver'
32 configuration option. The From address and the e-mail format are
33 generated from the template file passed as argument to '--template'
34 (defaulting to '.git/patchmail.tmpl' or
35 '~/.stgit/templates/patchmail.tmpl' or or
36 '/usr/share/stgit/templates/patchmail.tmpl'). The To/Cc/Bcc addresses
37 can either be added to the template file or passed via the
38 corresponding command line options.
40 A preamble e-mail can be sent using the '--cover' and/or
41 '--edit-cover' options. The first allows the user to specify a file to
42 be used as a template. The latter option will invoke the editor on the
43 specified file (defaulting to '.git/covermail.tmpl' or
44 '~/.stgit/templates/covermail.tmpl' or
45 '/usr/share/stgit/templates/covermail.tmpl').
47 All the subsequent e-mails appear as replies to the first e-mail sent
48 (either the preamble or the first patch). E-mails can be seen as
49 replies to a different e-mail by using the '--refid' option.
51 SMTP authentication is also possible with '--smtp-user' and
52 '--smtp-password' options, also available as configuration settings:
53 'smtpuser' and 'smtppassword'.
55 The patch e-mail template accepts 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 %(diff)s - unified diff of the patch
62 %(diffstat)s - diff statistics
63 %(version)s - ' version' string passed on the command line (or empty)
64 %(prefix)s - 'prefix ' string passed on the command line
65 %(patchnr)s - patch number
66 %(totalnr)s - total number of patches to be sent
67 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
68 %(authname)s - author's name
69 %(authemail)s - author's email
70 %(authdate)s - patch creation date
71 %(commname)s - committer's name
72 %(commemail)s - committer's e-mail
74 For the preamble e-mail template, only the %(maintainer)s,
75 %(version)s, %(patchnr)s, %(totalnr)s and %(number)s variables are
78 options
= [make_option('-a', '--all',
79 help = 'e-mail all the applied patches',
80 action
= 'store_true'),
82 help = 'add TO to the To: list',
85 help = 'add CC to the Cc: list',
88 help = 'add BCC to the Bcc: list',
91 help = 'automatically cc the patch signers',
92 action
= 'store_true'),
93 make_option('--noreply',
94 help = 'do not send subsequent messages as replies',
95 action
= 'store_true'),
96 make_option('-v', '--version', metavar
= 'VERSION',
97 help = 'add VERSION to the [PATCH ...] prefix'),
98 make_option('--prefix', metavar
= 'PREFIX',
99 help = 'add PREFIX to the [... PATCH ...] prefix'),
100 make_option('-t', '--template', metavar
= 'FILE',
101 help = 'use FILE as the message template'),
102 make_option('-c', '--cover', metavar
= 'FILE',
103 help = 'send FILE as the cover message'),
104 make_option('-e', '--edit-cover',
105 help = 'edit the cover message before sending',
106 action
= 'store_true'),
107 make_option('-E', '--edit-patches',
108 help = 'edit each patch before sending',
109 action
= 'store_true'),
110 make_option('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
111 help = 'sleep for SECONDS between e-mails sending'),
112 make_option('--refid',
113 help = 'use REFID as the reference id'),
114 make_option('-u', '--smtp-user', metavar
= 'USER',
115 help = 'username for SMTP authentication'),
116 make_option('-p', '--smtp-password', metavar
= 'PASSWORD',
117 help = 'username for SMTP authentication'),
118 make_option('-b', '--branch',
119 help = 'use BRANCH instead of the default one'),
120 make_option('-m', '--mbox',
121 help = 'generate an mbox file instead of sending',
122 action
= 'store_true')]
125 def __get_maintainer():
126 """Return the 'authname <authemail>' string as read from the
129 if config
.has_option('stgit', 'authname') \
130 and config
.has_option('stgit', 'authemail'):
131 return '%s <%s>' %
(config
.get('stgit', 'authname'),
132 config
.get('stgit', 'authemail'))
136 def __parse_addresses(addresses
):
137 """Return a two elements tuple: (from, [to])
139 def __addr_list(addrs
):
140 m
= re
.search('[^@\s<,]+@[^>\s,]+', addrs
);
143 return [ m
.group() ] + __addr_list(addrs
[m
.end():])
147 for line
in addresses
.split('\n'):
148 if re
.match('from:\s+', line
, re
.I
):
149 from_addr_list
+= __addr_list(line
)
150 elif re
.match('(to|cc|bcc):\s+', line
, re
.I
):
151 to_addr_list
+= __addr_list(line
)
153 if len(from_addr_list
) == 0:
154 raise CmdException
, 'No "From" address'
155 if len(to_addr_list
) == 0:
156 raise CmdException
, 'No "To/Cc/Bcc" addresses'
158 return (from_addr_list
[0], to_addr_list
)
160 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
161 smtpuser
, smtppassword
):
162 """Send the message using the given SMTP server
165 s
= smtplib
.SMTP(smtpserver
)
166 except Exception, err
:
167 raise CmdException
, str(err
)
171 if smtpuser
and smtppassword
:
173 s
.login(smtpuser
, smtppassword
)
175 s
.sendmail(from_addr
, to_addr_list
, msg
)
176 # give recipients a chance of receiving patches in the correct order
178 except Exception, err
:
179 raise CmdException
, str(err
)
183 def __build_address_headers(msg
, options
, extra_cc
= []):
184 """Build the address headers and check existing headers in the
187 def __replace_header(header
, addr
):
189 crt_addr
= msg
[header
]
193 msg
[header
] = ', '.join([crt_addr
, addr
])
201 if config
.has_option('stgit', 'autobcc'):
202 autobcc
= config
.get('stgit', 'autobcc')
207 to_addr
= ', '.join(options
.to
)
209 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
211 cc_addr
= ', '.join(extra_cc
)
213 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
217 __replace_header('To', to_addr
)
218 __replace_header('Cc', cc_addr
)
219 __replace_header('Bcc', bcc_addr
)
221 def __get_signers_list(msg
):
222 """Return the address list generated from signed-off-by and
223 acked-by lines in the message.
227 r
= re
.compile('^(signed-off-by|acked-by):\s+(.+)$', re
.I
)
228 for line
in msg
.split('\n'):
231 addr_list
.append(m
.expand('\g<2>'))
235 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
236 """Build extra email headers and encoding
239 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
240 msg
['Message-ID'] = msg_id
242 msg
['In-Reply-To'] = ref_id
243 msg
['References'] = ref_id
244 msg
['User-Agent'] = 'StGIT/%s' % version
.version
246 def __encode_message(msg
):
247 # 7 or 8 bit encoding
248 charset
= email
.Charset
.Charset('utf-8')
249 charset
.body_encoding
= None
252 for header
, value
in msg
.items():
254 for word
in value
.split(' '):
256 uword
= unicode(word
, 'utf-8')
257 except UnicodeDecodeError:
258 # maybe we should try a different encoding or report
259 # the error. At the moment, we just ignore it
261 words
.append(email
.Header
.Header(uword
).encode())
262 new_val
= ' '.join(words
)
263 msg
.replace_header(header
, new_val
)
265 # encode the body and set the MIME and encoding headers
266 msg
.set_charset(charset
)
268 def edit_message(msg
):
269 fname
= '.stgitmail.txt'
271 # create the initial file
277 if config
.has_option('stgit', 'editor'):
278 editor
= config
.get('stgit', 'editor')
279 elif 'EDITOR' in os
.environ
:
280 editor
= os
.environ
['EDITOR']
283 editor
+= ' %s' % fname
285 print 'Invoking the editor: "%s"...' % editor
,
287 print 'done (exit code: %d)' % os
.system(editor
)
289 # read the message back
296 def __build_cover(tmpl
, total_nr
, msg_id
, options
):
297 """Build the cover message (series description) to be sent via SMTP
299 maintainer
= __get_maintainer()
304 version_str
= ' %s' % options
.version
309 prefix_str
= options
.prefix
+ ' '
313 total_nr_str
= str(total_nr
)
314 patch_nr_str
= '0'.zfill(len(total_nr_str
))
316 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
320 tmpl_dict
= {'maintainer': maintainer
,
321 # for backward template compatibility
323 # for backward template compatibility
325 'version': version_str
,
326 'prefix': prefix_str
,
327 'patchnr': patch_nr_str
,
328 'totalnr': total_nr_str
,
329 'number': number_str
}
332 msg_string
= tmpl % tmpl_dict
333 except KeyError, err
:
334 raise CmdException
, 'Unknown patch template variable: %s' \
337 raise CmdException
, 'Only "%(name)s" variables are ' \
338 'supported in the patch template'
340 # The Python email message
342 msg
= email
.message_from_string(msg_string
)
343 except Exception, ex
:
344 raise CmdException
, 'template parsing error: %s' % str
(ex
)
346 __build_address_headers(msg
, options
)
347 __build_extra_headers(msg
, msg_id
, options
.refid
)
348 __encode_message(msg
)
350 msg_string
= msg
.as_string(options
.mbox
)
352 if options
.edit_cover
:
353 msg_string
= edit_message(msg_string
)
355 return msg_string
.strip('\n')
357 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
358 """Build the message to be sent via SMTP
360 p
= crt_series
.get_patch(patch
)
362 descr
= p
.get_description().strip()
363 descr_lines
= descr
.split('\n')
365 short_descr
= descr_lines
[0].rstrip()
366 long_descr
= '\n'.join(descr_lines
[1:]).lstrip()
368 maintainer
= __get_maintainer()
370 maintainer
= '%s <%s>' %
(p
.get_commname(), p
.get_commemail())
373 version_str
= ' %s' % options
.version
378 prefix_str
= options
.prefix
+ ' '
382 total_nr_str
= str(total_nr
)
383 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
385 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
389 tmpl_dict
= {'patch': patch
,
390 'maintainer': maintainer
,
391 'shortdescr': short_descr
,
392 'longdescr': long_descr
,
393 # for backward template compatibility
395 'diff': git
.diff(rev1
= git_id('%s//bottom' % patch
),
396 rev2
= git_id('%s//top' % patch
)),
397 'diffstat': git
.diffstat(rev1
= git_id('%s//bottom'%patch
),
398 rev2
= git_id('%s//top' % patch
)),
399 # for backward template compatibility
401 'version': version_str
,
402 'prefix': prefix_str
,
403 'patchnr': patch_nr_str
,
404 'totalnr': total_nr_str
,
405 'number': number_str
,
406 'authname': p
.get_authname(),
407 'authemail': p
.get_authemail(),
408 'authdate': p
.get_authdate(),
409 'commname': p
.get_commname(),
410 'commemail': p
.get_commemail()}
412 for key
in tmpl_dict
:
413 if not tmpl_dict
[key
]:
417 msg_string
= tmpl % tmpl_dict
418 except KeyError, err
:
419 raise CmdException
, 'Unknown patch template variable: %s' \
422 raise CmdException
, 'Only "%(name)s" variables are ' \
423 'supported in the patch template'
425 # The Python email message
427 msg
= email
.message_from_string(msg_string
)
428 except Exception, ex
:
429 raise CmdException
, 'template parsing error: %s' % str
(ex
)
432 extra_cc
= __get_signers_list(descr
)
436 __build_address_headers(msg
, options
, extra_cc
)
437 __build_extra_headers(msg
, msg_id
, ref_id
)
438 __encode_message(msg
)
440 msg_string
= msg
.as_string(options
.mbox
)
442 if options
.edit_patches
:
443 msg_string
= edit_message(msg_string
)
445 return msg_string
.strip('\n')
447 def func(parser
, options
, args
):
448 """Send the patches by e-mail using the patchmail.tmpl file as
451 smtpserver
= config
.get('stgit', 'smtpserver')
455 if config
.has_option('stgit', 'smtpuser'):
456 smtpuser
= config
.get('stgit', 'smtpuser')
457 if config
.has_option('stgit', 'smtppassword'):
458 smtppassword
= config
.get('stgit', 'smtppassword')
460 applied
= crt_series
.get_applied()
465 patches
= parse_patches(args
, applied
)
467 raise CmdException
, 'Incorrect options. Unknown patches to send'
469 if options
.smtp_password
:
470 smtppassword
= options
.smtp_password
472 if options
.smtp_user
:
473 smtpuser
= options
.smtp_user
475 if (smtppassword
and not smtpuser
):
476 raise CmdException
, 'SMTP password supplied, username needed'
477 if (smtpuser
and not smtppassword
):
478 raise CmdException
, 'SMTP username supplied, password needed'
480 total_nr
= len(patches
)
482 raise CmdException
, 'No patches to send'
487 ref_id
= options
.refid
489 if options
.sleep
!= None:
490 sleep
= options
.sleep
492 sleep
= config
.getint('stgit', 'smtpdelay')
494 # send the cover message (if any)
495 if options
.cover
or options
.edit_cover
:
496 # find the template file
498 tmpl
= file(options
.cover
).read()
500 tmpl
= templates
.get_template('covermail.tmpl')
502 raise CmdException
, 'No cover message template file found'
504 msg_id
= email
.Utils
.make_msgid('stgit')
505 msg
= __build_cover(tmpl
, total_nr
, msg_id
, options
)
506 from_addr
, to_addr_list
= __parse_addresses(msg
)
508 # subsequent e-mails are seen as replies to the first one
509 if not options
.noreply
:
516 print 'Sending the cover message...',
518 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
519 smtpuser
, smtppassword
)
524 tmpl
= file(options
.template
).read()
526 tmpl
= templates
.get_template('patchmail.tmpl')
528 raise CmdException
, 'No e-mail template file found'
530 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
531 msg_id
= email
.Utils
.make_msgid('stgit')
532 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
534 from_addr
, to_addr_list
= __parse_addresses(msg
)
536 # subsequent e-mails are seen as replies to the first one
537 if not options
.noreply
and not ref_id
:
544 print 'Sending patch "%s"...' % p
,
546 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
547 smtpuser
, smtppassword
)