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 %(sender)s - 'sender' or 'authname <authemail>' as per 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 %(fromauth)s - 'From: author\\n\\n' if different from sender
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 %(sender)s, %(version)s,
76 %(patchnr)s, %(totalnr)s and %(number)s variables are supported."""
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')]
126 """Return the 'authname <authemail>' string as read from the
129 if config
.has_option('stgit', 'sender'):
130 return config
.get('stgit', 'sender')
131 elif config
.has_option('stgit', 'authname') \
132 and config
.has_option('stgit', 'authemail'):
133 return '%s <%s>' %
(config
.get('stgit', 'authname'),
134 config
.get('stgit', 'authemail'))
136 raise CmdException
, 'unknown sender details'
138 def __parse_addresses(addresses
):
139 """Return a two elements tuple: (from, [to])
141 def __addr_list(addrs
):
142 m
= re
.search('[^@\s<,]+@[^>\s,]+', addrs
);
145 return [ m
.group() ] + __addr_list(addrs
[m
.end():])
149 for line
in addresses
.split('\n'):
150 if re
.match('from:\s+', line
, re
.I
):
151 from_addr_list
+= __addr_list(line
)
152 elif re
.match('(to|cc|bcc):\s+', line
, re
.I
):
153 to_addr_list
+= __addr_list(line
)
155 if len(from_addr_list
) == 0:
156 raise CmdException
, 'No "From" address'
157 if len(to_addr_list
) == 0:
158 raise CmdException
, 'No "To/Cc/Bcc" addresses'
160 return (from_addr_list
[0], to_addr_list
)
162 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
163 smtpuser
, smtppassword
):
164 """Send the message using the given SMTP server
167 s
= smtplib
.SMTP(smtpserver
)
168 except Exception, err
:
169 raise CmdException
, str(err
)
173 if smtpuser
and smtppassword
:
175 s
.login(smtpuser
, smtppassword
)
177 s
.sendmail(from_addr
, to_addr_list
, msg
)
178 # give recipients a chance of receiving patches in the correct order
180 except Exception, err
:
181 raise CmdException
, str(err
)
185 def __build_address_headers(msg
, options
, extra_cc
= []):
186 """Build the address headers and check existing headers in the
189 def __replace_header(header
, addr
):
191 crt_addr
= msg
[header
]
195 msg
[header
] = ', '.join([crt_addr
, addr
])
203 if config
.has_option('stgit', 'autobcc'):
204 autobcc
= config
.get('stgit', 'autobcc')
209 to_addr
= ', '.join(options
.to
)
211 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
213 cc_addr
= ', '.join(extra_cc
)
215 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
219 __replace_header('To', to_addr
)
220 __replace_header('Cc', cc_addr
)
221 __replace_header('Bcc', bcc_addr
)
223 def __get_signers_list(msg
):
224 """Return the address list generated from signed-off-by and
225 acked-by lines in the message.
229 r
= re
.compile('^(signed-off-by|acked-by):\s+(.+)$', re
.I
)
230 for line
in msg
.split('\n'):
233 addr_list
.append(m
.expand('\g<2>'))
237 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
238 """Build extra email headers and encoding
241 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
242 msg
['Message-ID'] = msg_id
244 msg
['In-Reply-To'] = ref_id
245 msg
['References'] = ref_id
246 msg
['User-Agent'] = 'StGIT/%s' % version
.version
248 def __encode_message(msg
):
249 # 7 or 8 bit encoding
250 charset
= email
.Charset
.Charset('utf-8')
251 charset
.body_encoding
= None
254 for header
, value
in msg
.items():
256 for word
in value
.split(' '):
258 uword
= unicode(word
, 'utf-8')
259 except UnicodeDecodeError:
260 # maybe we should try a different encoding or report
261 # the error. At the moment, we just ignore it
263 words
.append(email
.Header
.Header(uword
).encode())
264 new_val
= ' '.join(words
)
265 msg
.replace_header(header
, new_val
)
267 # encode the body and set the MIME and encoding headers
268 msg
.set_charset(charset
)
270 def __edit_message(msg
):
271 fname
= '.stgitmail.txt'
273 # create the initial file
279 if config
.has_option('stgit', 'editor'):
280 editor
= config
.get('stgit', 'editor')
281 elif 'EDITOR' in os
.environ
:
282 editor
= os
.environ
['EDITOR']
285 editor
+= ' %s' % fname
287 print 'Invoking the editor: "%s"...' % editor
,
289 print 'done (exit code: %d)' % os
.system(editor
)
291 # read the message back
298 def __build_cover(tmpl
, total_nr
, msg_id
, options
):
299 """Build the cover message (series description) to be sent via SMTP
301 sender
= __get_sender()
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
= {'sender': sender
,
321 # for backward template compatibility
322 'maintainer': sender
,
323 # for backward template compatibility
325 # for backward template compatibility
327 'version': version_str
,
328 'prefix': prefix_str
,
329 'patchnr': patch_nr_str
,
330 'totalnr': total_nr_str
,
331 'number': number_str
}
334 msg_string
= tmpl % tmpl_dict
335 except KeyError, err
:
336 raise CmdException
, 'Unknown patch template variable: %s' \
339 raise CmdException
, 'Only "%(name)s" variables are ' \
340 'supported in the patch template'
342 if options
.edit_cover
:
343 msg_string
= __edit_message(msg_string
)
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 return msg_string
.strip('\n')
359 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
360 """Build the message to be sent via SMTP
362 p
= crt_series
.get_patch(patch
)
364 descr
= p
.get_description().strip()
365 descr_lines
= descr
.split('\n')
367 short_descr
= descr_lines
[0].rstrip()
368 long_descr
= '\n'.join(descr_lines
[1:]).lstrip()
370 authname
= p
.get_authname();
371 authemail
= p
.get_authemail();
372 commname
= p
.get_commname();
373 commemail
= p
.get_commemail();
375 sender
= __get_sender()
377 fromauth
= '%s <%s>' %
(authname
, authemail
)
378 if fromauth
!= sender
:
379 fromauth
= 'From: %s\n\n' % fromauth
384 version_str
= ' %s' % options
.version
389 prefix_str
= options
.prefix
+ ' '
393 total_nr_str
= str(total_nr
)
394 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
396 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
400 tmpl_dict
= {'patch': patch
,
402 # for backward template compatibility
403 'maintainer': sender
,
404 'shortdescr': short_descr
,
405 'longdescr': long_descr
,
406 # for backward template compatibility
408 'diff': git
.diff(rev1
= git_id('%s//bottom' % patch
),
409 rev2
= git_id('%s//top' % patch
)),
410 'diffstat': git
.diffstat(rev1
= git_id('%s//bottom'%patch
),
411 rev2
= git_id('%s//top' % patch
)),
412 # for backward template compatibility
414 'version': version_str
,
415 'prefix': prefix_str
,
416 'patchnr': patch_nr_str
,
417 'totalnr': total_nr_str
,
418 'number': number_str
,
419 'fromauth': fromauth
,
420 'authname': authname
,
421 'authemail': authemail
,
422 'authdate': p
.get_authdate(),
423 'commname': commname
,
424 'commemail': commemail
}
426 for key
in tmpl_dict
:
427 if not tmpl_dict
[key
]:
431 msg_string
= tmpl % tmpl_dict
432 except KeyError, err
:
433 raise CmdException
, 'Unknown patch template variable: %s' \
436 raise CmdException
, 'Only "%(name)s" variables are ' \
437 'supported in the patch template'
439 if options
.edit_patches
:
440 msg_string
= __edit_message(msg_string
)
442 # The Python email message
444 msg
= email
.message_from_string(msg_string
)
445 except Exception, ex
:
446 raise CmdException
, 'template parsing error: %s' % str
(ex
)
449 extra_cc
= __get_signers_list(descr
)
453 __build_address_headers(msg
, options
, extra_cc
)
454 __build_extra_headers(msg
, msg_id
, ref_id
)
455 __encode_message(msg
)
457 msg_string
= msg
.as_string(options
.mbox
)
459 return msg_string
.strip('\n')
461 def func(parser
, options
, args
):
462 """Send the patches by e-mail using the patchmail.tmpl file as
465 smtpserver
= config
.get('stgit', 'smtpserver')
469 if config
.has_option('stgit', 'smtpuser'):
470 smtpuser
= config
.get('stgit', 'smtpuser')
471 if config
.has_option('stgit', 'smtppassword'):
472 smtppassword
= config
.get('stgit', 'smtppassword')
474 applied
= crt_series
.get_applied()
479 patches
= parse_patches(args
, applied
)
481 raise CmdException
, 'Incorrect options. Unknown patches to send'
483 if options
.smtp_password
:
484 smtppassword
= options
.smtp_password
486 if options
.smtp_user
:
487 smtpuser
= options
.smtp_user
489 if (smtppassword
and not smtpuser
):
490 raise CmdException
, 'SMTP password supplied, username needed'
491 if (smtpuser
and not smtppassword
):
492 raise CmdException
, 'SMTP username supplied, password needed'
494 total_nr
= len(patches
)
496 raise CmdException
, 'No patches to send'
501 ref_id
= options
.refid
503 if options
.sleep
!= None:
504 sleep
= options
.sleep
506 sleep
= config
.getint('stgit', 'smtpdelay')
508 # send the cover message (if any)
509 if options
.cover
or options
.edit_cover
:
510 # find the template file
512 tmpl
= file(options
.cover
).read()
514 tmpl
= templates
.get_template('covermail.tmpl')
516 raise CmdException
, 'No cover message template file found'
518 msg_id
= email
.Utils
.make_msgid('stgit')
519 msg
= __build_cover(tmpl
, total_nr
, msg_id
, options
)
520 from_addr
, to_addr_list
= __parse_addresses(msg
)
522 # subsequent e-mails are seen as replies to the first one
523 if not options
.noreply
:
530 print 'Sending the cover message...',
532 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
533 smtpuser
, smtppassword
)
538 tmpl
= file(options
.template
).read()
540 tmpl
= templates
.get_template('patchmail.tmpl')
542 raise CmdException
, 'No e-mail template file found'
544 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
545 msg_id
= email
.Utils
.make_msgid('stgit')
546 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
548 from_addr
, to_addr_list
= __parse_addresses(msg
)
550 # subsequent e-mails are seen as replies to the first one
551 if not options
.noreply
and not ref_id
:
558 print 'Sending patch "%s"...' % p
,
560 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
561 smtpuser
, smtppassword
)