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
, socket
, smtplib
, getpass
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
.out
import *
25 from stgit
import stack
, git
, version
, templates
26 from stgit
.config
import config
29 help = 'send a patch or series of patches by e-mail'
30 usage
= """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
32 Send a patch or a range of patches by e-mail using the SMTP server
33 specified by the 'stgit.smtpserver' configuration option, or the
34 '--smtp-server' command line option. The From address and the e-mail
35 format are generated from the template file passed as argument to
36 '--template' (defaulting to '.git/patchmail.tmpl' or
37 '~/.stgit/templates/patchmail.tmpl' or
38 '/usr/share/stgit/templates/patchmail.tmpl').
40 The To/Cc/Bcc addresses can either be added to the template file or
41 passed via the corresponding command line options. They can be e-mail
42 addresses or aliases which are automatically expanded to the values
43 stored in the [mail "alias"] section of GIT configuration files.
45 A preamble e-mail can be sent using the '--cover' and/or
46 '--edit-cover' options. The first allows the user to specify a file to
47 be used as a template. The latter option will invoke the editor on the
48 specified file (defaulting to '.git/covermail.tmpl' or
49 '~/.stgit/templates/covermail.tmpl' or
50 '/usr/share/stgit/templates/covermail.tmpl').
52 All the subsequent e-mails appear as replies to the first e-mail sent
53 (either the preamble or the first patch). E-mails can be seen as
54 replies to a different e-mail by using the '--refid' option.
56 SMTP authentication is also possible with '--smtp-user' and
57 '--smtp-password' options, also available as configuration settings:
58 'smtpuser' and 'smtppassword'. TLS encryption can be enabled by
59 '--smtp-tls' option and 'smtptls' setting.
61 The following variables are accepted by both the preamble and the
62 patch e-mail templates:
64 %(diffstat)s - diff statistics
65 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
66 %(patchnr)s - patch number
67 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
68 %(totalnr)s - total number of patches to be sent
69 %(version)s - ' version' string passed on the command line (or empty)
71 In addition to the common variables, the preamble e-mail template
72 accepts the following:
74 %(shortlog)s - first line of each patch description, listed by author
76 In addition to the common variables, the patch e-mail template accepts
79 %(authdate)s - patch creation date
80 %(authemail)s - author's email
81 %(authname)s - author's name
82 %(commemail)s - committer's e-mail
83 %(commname)s - committer's name
84 %(diff)s - unified diff of the patch
85 %(fromauth)s - 'From: author\\n\\n' if different from sender
86 %(longdescr)s - the rest of the patch description, after the first line
87 %(patch)s - patch name
88 %(prefix)s - 'prefix ' string passed on the command line
89 %(shortdescr)s - the first line of the patch description"""
91 directory
= DirectoryHasRepository()
92 options
= [make_option('-a', '--all',
93 help = 'e-mail all the applied patches',
94 action
= 'store_true'),
96 help = 'add TO to the To: list',
99 help = 'add CC to the Cc: list',
102 help = 'add BCC to the Bcc: list',
104 make_option('--auto',
105 help = 'automatically cc the patch signers',
106 action
= 'store_true'),
107 make_option('--noreply',
108 help = 'do not send subsequent messages as replies',
109 action
= 'store_true'),
110 make_option('--unrelated',
111 help = 'send patches without sequence numbering',
112 action
= 'store_true'),
113 make_option('-v', '--version', metavar
= 'VERSION',
114 help = 'add VERSION to the [PATCH ...] prefix'),
115 make_option('--prefix', metavar
= 'PREFIX',
116 help = 'add PREFIX to the [... PATCH ...] prefix'),
117 make_option('-t', '--template', metavar
= 'FILE',
118 help = 'use FILE as the message template'),
119 make_option('-c', '--cover', metavar
= 'FILE',
120 help = 'send FILE as the cover message'),
121 make_option('-e', '--edit-cover',
122 help = 'edit the cover message before sending',
123 action
= 'store_true'),
124 make_option('-E', '--edit-patches',
125 help = 'edit each patch before sending',
126 action
= 'store_true'),
127 make_option('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
128 help = 'sleep for SECONDS between e-mails sending'),
129 make_option('--refid',
130 help = 'use REFID as the reference id'),
131 make_option('--smtp-server', metavar
= 'HOST[:PORT]',
132 help = 'SMTP server to use for sending mail'),
133 make_option('-u', '--smtp-user', metavar
= 'USER',
134 help = 'username for SMTP authentication'),
135 make_option('-p', '--smtp-password', metavar
= 'PASSWORD',
136 help = 'username for SMTP authentication'),
137 make_option('-T', '--smtp-tls',
138 help = 'use SMTP with TLS encryption',
139 action
= 'store_true'),
140 make_option('-b', '--branch',
141 help = 'use BRANCH instead of the default one'),
142 make_option('-O', '--diff-opts',
143 help = 'options to pass to git-diff'),
144 make_option('-m', '--mbox',
145 help = 'generate an mbox file instead of sending',
146 action
= 'store_true')]
150 """Return the 'authname <authemail>' string as read from the
153 sender
=config
.get('stgit.sender')
156 sender
= str(git
.user())
157 except git
.GitException
:
158 sender
= str(git
.author())
161 raise CmdException
, 'unknown sender details'
163 return address_or_alias(sender
)
165 def __parse_addresses(msg
):
166 """Return a two elements tuple: (from, [to])
168 def __addr_list(msg
, header
):
169 return [name_addr
[1] for name_addr
in
170 email
.Utils
.getaddresses(msg
.get_all(header
, []))]
172 from_addr_list
= __addr_list(msg
, 'From')
173 if len(from_addr_list
) == 0:
174 raise CmdException
, 'No "From" address'
176 to_addr_list
= __addr_list(msg
, 'To') + __addr_list(msg
, 'Cc') \
177 + __addr_list(msg
, 'Bcc')
178 if len(to_addr_list
) == 0:
179 raise CmdException
, 'No "To/Cc/Bcc" addresses'
181 return (from_addr_list
[0], to_addr_list
)
183 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
184 smtpuser
, smtppassword
, use_tls
):
185 """Send the message using the given SMTP server
188 s
= smtplib
.SMTP(smtpserver
)
189 except Exception, err
:
190 raise CmdException
, str(err
)
194 if smtpuser
and smtppassword
:
197 if not hasattr(socket
, 'ssl'):
198 raise CmdException
, "cannot use TLS - no SSL support in Python"
201 s
.login(smtpuser
, smtppassword
)
203 result
= s
.sendmail(from_addr
, to_addr_list
, msg
)
205 print "mail server refused delivery for the following recipients: %s" % result
206 # give recipients a chance of receiving patches in the correct order
208 except Exception, err
:
209 raise CmdException
, str(err
)
213 def __build_address_headers(msg
, options
, extra_cc
= []):
214 """Build the address headers and check existing headers in the
217 def __replace_header(header
, addr
):
219 crt_addr
= msg
[header
]
223 msg
[header
] = address_or_alias(', '.join([crt_addr
, addr
]))
225 msg
[header
] = address_or_alias(addr
)
231 autobcc
= config
.get('stgit.autobcc') or ''
234 to_addr
= ', '.join(options
.to
)
236 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
238 cc_addr
= ', '.join(extra_cc
)
240 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
244 __replace_header('To', to_addr
)
245 __replace_header('Cc', cc_addr
)
246 __replace_header('Bcc', bcc_addr
)
248 def __get_signers_list(msg
):
249 """Return the address list generated from signed-off-by and
250 acked-by lines in the message.
254 r
= re
.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re
.I
)
255 for line
in msg
.split('\n'):
258 addr_list
.append(m
.expand('\g<2>'))
262 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
263 """Build extra email headers and encoding
266 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
267 msg
['Message-ID'] = msg_id
269 msg
['In-Reply-To'] = ref_id
270 msg
['References'] = ref_id
271 msg
['User-Agent'] = 'StGIT/%s' % version
.version
273 def __encode_message(msg
):
274 # 7 or 8 bit encoding
275 charset
= email
.Charset
.Charset('utf-8')
276 charset
.body_encoding
= None
279 for header
, value
in msg
.items():
281 for word
in value
.split(' '):
283 uword
= unicode(word
, 'utf-8')
284 except UnicodeDecodeError:
285 # maybe we should try a different encoding or report
286 # the error. At the moment, we just ignore it
288 words
.append(email
.Header
.Header(uword
).encode())
289 new_val
= ' '.join(words
)
290 msg
.replace_header(header
, new_val
)
292 # encode the body and set the MIME and encoding headers
293 msg
.set_charset(charset
)
295 def __edit_message(msg
):
296 fname
= '.stgitmail.txt'
298 # create the initial file
305 # read the message back
312 def __build_cover(tmpl
, patches
, msg_id
, options
):
313 """Build the cover message (series description) to be sent via SMTP
315 sender
= __get_sender()
318 version_str
= ' %s' % options
.version
323 prefix_str
= options
.prefix
+ ' '
325 confprefix
= config
.get('stgit.mail.prefix')
327 prefix_str
= confprefix
+ ' '
331 total_nr_str
= str(len(patches
))
332 patch_nr_str
= '0'.zfill(len(total_nr_str
))
334 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
338 tmpl_dict
= {'sender': sender
,
339 # for backward template compatibility
340 'maintainer': sender
,
341 # for backward template compatibility
343 # for backward template compatibility
345 'version': version_str
,
346 'prefix': prefix_str
,
347 'patchnr': patch_nr_str
,
348 'totalnr': total_nr_str
,
349 'number': number_str
,
350 'shortlog': stack
.shortlog(crt_series
.get_patch(p
)
352 'diffstat': git
.diffstat(
353 rev1
= git_id(crt_series
, '%s//bottom' % patches
[0]),
354 rev2
= git_id(crt_series
, '%s//top' % patches
[-1]))}
357 msg_string
= tmpl % tmpl_dict
358 except KeyError, err
:
359 raise CmdException
, 'Unknown patch template variable: %s' \
362 raise CmdException
, 'Only "%(name)s" variables are ' \
363 'supported in the patch template'
365 if options
.edit_cover
:
366 msg_string
= __edit_message(msg_string
)
368 # The Python email message
370 msg
= email
.message_from_string(msg_string
)
371 except Exception, ex
:
372 raise CmdException
, 'template parsing error: %s' % str
(ex
)
374 __build_address_headers(msg
, options
)
375 __build_extra_headers(msg
, msg_id
, options
.refid
)
376 __encode_message(msg
)
380 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
381 """Build the message to be sent via SMTP
383 p
= crt_series
.get_patch(patch
)
385 descr
= p
.get_description().strip()
386 descr_lines
= descr
.split('\n')
388 short_descr
= descr_lines
[0].rstrip()
389 long_descr
= '\n'.join(descr_lines
[1:]).lstrip()
391 authname
= p
.get_authname();
392 authemail
= p
.get_authemail();
393 commname
= p
.get_commname();
394 commemail
= p
.get_commemail();
396 sender
= __get_sender()
398 fromauth
= '%s <%s>' %
(authname
, authemail
)
399 if fromauth
!= sender
:
400 fromauth
= 'From: %s\n\n' % fromauth
405 version_str
= ' %s' % options
.version
410 prefix_str
= options
.prefix
+ ' '
412 confprefix
= config
.get('stgit.mail.prefix')
414 prefix_str
= confprefix
+ ' '
418 if options
.diff_opts
:
419 diff_flags
= options
.diff_opts
.split()
423 total_nr_str
= str(total_nr
)
424 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
425 if not options
.unrelated
and total_nr
> 1:
426 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
430 tmpl_dict
= {'patch': patch
,
432 # for backward template compatibility
433 'maintainer': sender
,
434 'shortdescr': short_descr
,
435 'longdescr': long_descr
,
436 # for backward template compatibility
439 rev1
= git_id(crt_series
, '%s//bottom' % patch
),
440 rev2
= git_id(crt_series
, '%s//top' % patch
),
441 diff_flags
= diff_flags
),
442 'diffstat': git
.diffstat(
443 rev1
= git_id(crt_series
, '%s//bottom'%patch
),
444 rev2
= git_id(crt_series
, '%s//top' % patch
)),
445 # for backward template compatibility
447 'version': version_str
,
448 'prefix': prefix_str
,
449 'patchnr': patch_nr_str
,
450 'totalnr': total_nr_str
,
451 'number': number_str
,
452 'fromauth': fromauth
,
453 'authname': authname
,
454 'authemail': authemail
,
455 'authdate': p
.get_authdate(),
456 'commname': commname
,
457 'commemail': commemail
}
459 for key
in tmpl_dict
:
460 if not tmpl_dict
[key
]:
464 msg_string
= tmpl % tmpl_dict
465 except KeyError, err
:
466 raise CmdException
, 'Unknown patch template variable: %s' \
469 raise CmdException
, 'Only "%(name)s" variables are ' \
470 'supported in the patch template'
472 if options
.edit_patches
:
473 msg_string
= __edit_message(msg_string
)
475 # The Python email message
477 msg
= email
.message_from_string(msg_string
)
478 except Exception, ex
:
479 raise CmdException
, 'template parsing error: %s' % str
(ex
)
482 extra_cc
= __get_signers_list(descr
)
486 __build_address_headers(msg
, options
, extra_cc
)
487 __build_extra_headers(msg
, msg_id
, ref_id
)
488 __encode_message(msg
)
492 def func(parser
, options
, args
):
493 """Send the patches by e-mail using the patchmail.tmpl file as
496 smtpserver
= options
.smtp_server
or config
.get('stgit.smtpserver')
498 applied
= crt_series
.get_applied()
503 unapplied
= crt_series
.get_unapplied()
504 patches
= parse_patches(args
, applied
+ unapplied
, len(applied
))
506 raise CmdException
, 'Incorrect options. Unknown patches to send'
508 smtppassword
= options
.smtp_password
or config
.get('stgit.smtppassword')
509 smtpuser
= options
.smtp_user
or config
.get('stgit.smtpuser')
510 smtpusetls
= options
.smtp_tls
or config
.get('stgit.smtptls') == 'yes'
512 if (smtppassword
and not smtpuser
):
513 raise CmdException
, 'SMTP password supplied, username needed'
514 if (smtpusetls
and not smtpuser
):
515 raise CmdException
, 'SMTP over TLS requested, username needed'
516 if (smtpuser
and not smtppassword
):
517 smtppassword
= getpass
.getpass("Please enter SMTP password: ")
519 total_nr
= len(patches
)
521 raise CmdException
, 'No patches to send'
524 if options
.noreply
or options
.unrelated
:
525 raise CmdException
, \
526 '--refid option not allowed with --noreply or --unrelated'
527 ref_id
= options
.refid
531 sleep
= options
.sleep
or config
.getint('stgit.smtpdelay')
533 # send the cover message (if any)
534 if options
.cover
or options
.edit_cover
:
535 if options
.unrelated
:
536 raise CmdException
, 'cover sending not allowed with --unrelated'
538 # find the template file
540 tmpl
= file(options
.cover
).read()
542 tmpl
= templates
.get_template('covermail.tmpl')
544 raise CmdException
, 'No cover message template file found'
546 msg_id
= email
.Utils
.make_msgid('stgit')
547 msg
= __build_cover(tmpl
, patches
, msg_id
, options
)
548 from_addr
, to_addr_list
= __parse_addresses(msg
)
550 msg_string
= msg
.as_string(options
.mbox
)
552 # subsequent e-mails are seen as replies to the first one
553 if not options
.noreply
:
557 out
.stdout_raw(msg_string
+ '\n')
559 out
.start('Sending the cover message')
560 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
561 sleep
, smtpuser
, smtppassword
, smtpusetls
)
566 tmpl
= file(options
.template
).read()
568 tmpl
= templates
.get_template('patchmail.tmpl')
570 raise CmdException
, 'No e-mail template file found'
572 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
573 msg_id
= email
.Utils
.make_msgid('stgit')
574 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
576 from_addr
, to_addr_list
= __parse_addresses(msg
)
578 msg_string
= msg
.as_string(options
.mbox
)
580 # subsequent e-mails are seen as replies to the first one
581 if not options
.noreply
and not options
.unrelated
and not ref_id
:
585 out
.stdout_raw(msg_string
+ '\n')
587 out
.start('Sending patch "%s"' % p
)
588 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
589 sleep
, smtpuser
, smtppassword
, smtpusetls
)