154df9c9ace60a5a9d84109d7238521b489341e8
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 template e-mail headers and body must be separated by
56 '%(endofheaders)s' variable, which is replaced by StGIT with
57 additional headers and a blank line. The patch e-mail template accepts
58 the following variables:
60 %(patch)s - patch name
61 %(maintainer)s - 'authname <authemail>' as read from the config file
62 %(shortdescr)s - the first line of the patch description
63 %(longdescr)s - the rest of the patch description, after the first line
64 %(endofheaders)s - delimiter between e-mail headers and body
65 %(diff)s - unified diff of the patch
66 %(diffstat)s - diff statistics
67 %(date)s - current date/time
68 %(version)s - ' version' string passed on the command line (or empty)
69 %(prefix)s - 'prefix ' string passed on the command line
70 %(patchnr)s - patch number
71 %(totalnr)s - total number of patches to be sent
72 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
73 %(authname)s - author's name
74 %(authemail)s - author's email
75 %(authdate)s - patch creation date
76 %(commname)s - committer's name
77 %(commemail)s - committer's e-mail
79 For the preamble e-mail template, only the %(maintainer)s, %(date)s,
80 %(endofheaders)s, %(version)s, %(patchnr)s, %(totalnr)s and %(number)s
81 variables are supported."""
83 options
= [make_option('-a', '--all',
84 help = 'e-mail all the applied patches',
85 action
= 'store_true'),
87 help = 'add TO to the To: list',
90 help = 'add CC to the Cc: list',
93 help = 'add BCC to the Bcc: list',
96 help = 'automatically cc the patch signers',
97 action
= 'store_true'),
98 make_option('--noreply',
99 help = 'do not send subsequent messages as replies',
100 action
= 'store_true'),
101 make_option('-v', '--version', metavar
= 'VERSION',
102 help = 'add VERSION to the [PATCH ...] prefix'),
103 make_option('--prefix', metavar
= 'PREFIX',
104 help = 'add PREFIX to the [... PATCH ...] prefix'),
105 make_option('-t', '--template', metavar
= 'FILE',
106 help = 'use FILE as the message template'),
107 make_option('-c', '--cover', metavar
= 'FILE',
108 help = 'send FILE as the cover message'),
109 make_option('-e', '--edit-cover',
110 help = 'edit the cover message before sending',
111 action
= 'store_true'),
112 make_option('-E', '--edit-patches',
113 help = 'edit each patch before sending',
114 action
= 'store_true'),
115 make_option('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
116 help = 'sleep for SECONDS between e-mails sending'),
117 make_option('--refid',
118 help = 'use REFID as the reference id'),
119 make_option('-u', '--smtp-user', metavar
= 'USER',
120 help = 'username for SMTP authentication'),
121 make_option('-p', '--smtp-password', metavar
= 'PASSWORD',
122 help = 'username for SMTP authentication'),
123 make_option('-b', '--branch',
124 help = 'use BRANCH instead of the default one'),
125 make_option('-m', '--mbox',
126 help = 'generate an mbox file instead of sending',
127 action
= 'store_true')]
130 def __get_maintainer():
131 """Return the 'authname <authemail>' string as read from the
134 if config
.has_option('stgit', 'authname') \
135 and config
.has_option('stgit', 'authemail'):
136 return '%s <%s>' %
(config
.get('stgit', 'authname'),
137 config
.get('stgit', 'authemail'))
141 def __parse_addresses(addresses
):
142 """Return a two elements tuple: (from, [to])
144 def __addr_list(addrs
):
145 m
= re
.search('[^@\s<,]+@[^>\s,]+', addrs
);
148 return [ m
.group() ] + __addr_list(addrs
[m
.end():])
152 for line
in addresses
.split('\n'):
153 if re
.match('from:\s+', line
, re
.I
):
154 from_addr_list
+= __addr_list(line
)
155 elif re
.match('(to|cc|bcc):\s+', line
, re
.I
):
156 to_addr_list
+= __addr_list(line
)
158 if len(from_addr_list
) == 0:
159 raise CmdException
, 'No "From" address'
160 if len(to_addr_list
) == 0:
161 raise CmdException
, 'No "To/Cc/Bcc" addresses'
163 return (from_addr_list
[0], to_addr_list
)
165 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
166 smtpuser
, smtppassword
):
167 """Send the message using the given SMTP server
170 s
= smtplib
.SMTP(smtpserver
)
171 except Exception, err
:
172 raise CmdException
, str(err
)
176 if smtpuser
and smtppassword
:
178 s
.login(smtpuser
, smtppassword
)
180 s
.sendmail(from_addr
, to_addr_list
, msg
)
181 # give recipients a chance of receiving patches in the correct order
183 except Exception, err
:
184 raise CmdException
, str(err
)
188 def __build_address_headers(msg
, options
, extra_cc
= []):
189 """Build the address headers and check existing headers in the
192 def __replace_header(header
, addr
):
194 crt_addr
= msg
[header
]
198 msg
[header
] = ', '.join([crt_addr
, addr
])
206 if config
.has_option('stgit', 'autobcc'):
207 autobcc
= config
.get('stgit', 'autobcc')
212 to_addr
= ', '.join(options
.to
)
214 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
216 cc_addr
= ', '.join(extra_cc
)
218 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
222 __replace_header('To', to_addr
)
223 __replace_header('Cc', cc_addr
)
224 __replace_header('Bcc', bcc_addr
)
226 def __get_signers_list(msg
):
227 """Return the address list generated from signed-off-by and
228 acked-by lines in the message.
232 r
= re
.compile('^(signed-off-by|acked-by):\s+(.+)$', re
.I
)
233 for line
in msg
.split('\n'):
236 addr_list
.append(m
.expand('\g<2>'))
240 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
241 """Build extra email headers and encoding
244 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
245 msg
['Message-ID'] = msg_id
247 msg
['In-Reply-To'] = ref_id
248 msg
['References'] = ref_id
249 msg
['User-Agent'] = 'StGIT/%s' % version
.version
251 def __encode_message(msg
):
252 # 7 or 8 bit encoding
253 charset
= email
.Charset
.Charset('utf-8')
254 charset
.body_encoding
= None
257 for header
, value
in msg
.items():
259 for word
in value
.split(' '):
261 uword
= unicode(word
, 'utf-8')
262 except UnicodeDecodeError:
263 # maybe we should try a different encoding or report
264 # the error. At the moment, we just ignore it
266 words
.append(email
.Header
.Header(uword
).encode())
267 new_val
= ' '.join(words
)
268 msg
.replace_header(header
, new_val
)
270 # encode the body and set the MIME and encoding headers
271 msg
.set_charset(charset
)
273 def edit_message(msg
):
274 fname
= '.stgitmail.txt'
276 # create the initial file
282 if config
.has_option('stgit', 'editor'):
283 editor
= config
.get('stgit', 'editor')
284 elif 'EDITOR' in os
.environ
:
285 editor
= os
.environ
['EDITOR']
288 editor
+= ' %s' % fname
290 print 'Invoking the editor: "%s"...' % editor
,
292 print 'done (exit code: %d)' % os
.system(editor
)
294 # read the message back
301 def __build_cover(tmpl
, total_nr
, msg_id
, options
):
302 """Build the cover message (series description) to be sent via SMTP
304 maintainer
= __get_maintainer()
309 version_str
= ' %s' % options
.version
314 prefix_str
= options
.prefix
+ ' '
318 total_nr_str
= str(total_nr
)
319 patch_nr_str
= '0'.zfill(len(total_nr_str
))
321 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
325 tmpl_dict
= {'maintainer': maintainer
,
326 # for backward template compatibility
328 # for backward template compatibility
330 'version': version_str
,
331 'prefix': prefix_str
,
332 'patchnr': patch_nr_str
,
333 'totalnr': total_nr_str
,
334 'number': number_str
}
337 msg_string
= tmpl % tmpl_dict
338 except KeyError, err
:
339 raise CmdException
, 'Unknown patch template variable: %s' \
342 raise CmdException
, 'Only "%(name)s" variables are ' \
343 'supported in the patch template'
345 # The Python email message
347 msg
= email
.message_from_string(msg_string
)
348 except Exception, ex
:
349 raise CmdException
, 'template parsing error: %s' % str
(ex
)
351 __build_address_headers(msg
, options
)
352 __build_extra_headers(msg
, msg_id
, options
.refid
)
353 __encode_message(msg
)
355 msg_string
= msg
.as_string(options
.mbox
)
357 if options
.edit_cover
:
358 msg_string
= edit_message(msg_string
)
360 return msg_string
.strip('\n')
362 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
363 """Build the message to be sent via SMTP
365 p
= crt_series
.get_patch(patch
)
367 descr
= p
.get_description().strip()
368 descr_lines
= descr
.split('\n')
370 short_descr
= descr_lines
[0].rstrip()
371 long_descr
= '\n'.join(descr_lines
[1:]).lstrip()
373 maintainer
= __get_maintainer()
375 maintainer
= '%s <%s>' %
(p
.get_commname(), p
.get_commemail())
378 version_str
= ' %s' % options
.version
383 prefix_str
= options
.prefix
+ ' '
387 total_nr_str
= str(total_nr
)
388 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
390 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
394 tmpl_dict
= {'patch': patch
,
395 'maintainer': maintainer
,
396 'shortdescr': short_descr
,
397 'longdescr': long_descr
,
398 # for backward template compatibility
400 'diff': git
.diff(rev1
= git_id('%s//bottom' % patch
),
401 rev2
= git_id('%s//top' % patch
)),
402 'diffstat': git
.diffstat(rev1
= git_id('%s//bottom'%patch
),
403 rev2
= git_id('%s//top' % patch
)),
404 # for backward template compatibility
406 'version': version_str
,
407 'prefix': prefix_str
,
408 'patchnr': patch_nr_str
,
409 'totalnr': total_nr_str
,
410 'number': number_str
,
411 'authname': p
.get_authname(),
412 'authemail': p
.get_authemail(),
413 'authdate': p
.get_authdate(),
414 'commname': p
.get_commname(),
415 'commemail': p
.get_commemail()}
417 for key
in tmpl_dict
:
418 if not tmpl_dict
[key
]:
422 msg_string
= tmpl % tmpl_dict
423 except KeyError, err
:
424 raise CmdException
, 'Unknown patch template variable: %s' \
427 raise CmdException
, 'Only "%(name)s" variables are ' \
428 'supported in the patch template'
430 # The Python email message
432 msg
= email
.message_from_string(msg_string
)
433 except Exception, ex
:
434 raise CmdException
, 'template parsing error: %s' % str
(ex
)
437 extra_cc
= __get_signers_list(descr
)
441 __build_address_headers(msg
, options
, extra_cc
)
442 __build_extra_headers(msg
, msg_id
, ref_id
)
443 __encode_message(msg
)
445 msg_string
= msg
.as_string(options
.mbox
)
447 if options
.edit_patches
:
448 msg_string
= edit_message(msg_string
)
450 return msg_string
.strip('\n')
452 def func(parser
, options
, args
):
453 """Send the patches by e-mail using the patchmail.tmpl file as
456 smtpserver
= config
.get('stgit', 'smtpserver')
460 if config
.has_option('stgit', 'smtpuser'):
461 smtpuser
= config
.get('stgit', 'smtpuser')
462 if config
.has_option('stgit', 'smtppassword'):
463 smtppassword
= config
.get('stgit', 'smtppassword')
465 applied
= crt_series
.get_applied()
470 patches
= parse_patches(args
, applied
)
472 raise CmdException
, 'Incorrect options. Unknown patches to send'
474 if options
.smtp_password
:
475 smtppassword
= options
.smtp_password
477 if options
.smtp_user
:
478 smtpuser
= options
.smtp_user
480 if (smtppassword
and not smtpuser
):
481 raise CmdException
, 'SMTP password supplied, username needed'
482 if (smtpuser
and not smtppassword
):
483 raise CmdException
, 'SMTP username supplied, password needed'
485 total_nr
= len(patches
)
487 raise CmdException
, 'No patches to send'
492 ref_id
= options
.refid
494 if options
.sleep
!= None:
495 sleep
= options
.sleep
497 sleep
= config
.getint('stgit', 'smtpdelay')
499 # send the cover message (if any)
500 if options
.cover
or options
.edit_cover
:
501 # find the template file
503 tmpl
= file(options
.cover
).read()
505 tmpl
= templates
.get_template('covermail.tmpl')
507 raise CmdException
, 'No cover message template file found'
509 msg_id
= email
.Utils
.make_msgid('stgit')
510 msg
= __build_cover(tmpl
, total_nr
, msg_id
, options
)
511 from_addr
, to_addr_list
= __parse_addresses(msg
)
513 # subsequent e-mails are seen as replies to the first one
514 if not options
.noreply
:
521 print 'Sending the cover message...',
523 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
524 smtpuser
, smtppassword
)
529 tmpl
= file(options
.template
).read()
531 tmpl
= templates
.get_template('patchmail.tmpl')
533 raise CmdException
, 'No e-mail template file found'
535 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
536 msg_id
= email
.Utils
.make_msgid('stgit')
537 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
539 from_addr
, to_addr_list
= __parse_addresses(msg
)
541 # subsequent e-mails are seen as replies to the first one
542 if not options
.noreply
and not ref_id
:
549 print 'Sending patch "%s"...' % p
,
551 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
552 smtpuser
, smtppassword
)