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
36 '/usr/share/stgit/templates/patchmail.tmpl').
38 The To/Cc/Bcc addresses can either be added to the template file or
39 passed via the corresponding command line options. They can be e-mail
40 addresses or aliases which are automatically expanded to the values
41 stored in the [mail "alias"] section of GIT configuration files.
43 A preamble e-mail can be sent using the '--cover' and/or
44 '--edit-cover' options. The first allows the user to specify a file to
45 be used as a template. The latter option will invoke the editor on the
46 specified file (defaulting to '.git/covermail.tmpl' or
47 '~/.stgit/templates/covermail.tmpl' or
48 '/usr/share/stgit/templates/covermail.tmpl').
50 All the subsequent e-mails appear as replies to the first e-mail sent
51 (either the preamble or the first patch). E-mails can be seen as
52 replies to a different e-mail by using the '--refid' option.
54 SMTP authentication is also possible with '--smtp-user' and
55 '--smtp-password' options, also available as configuration settings:
56 'smtpuser' and 'smtppassword'.
58 The patch e-mail template accepts the following variables:
60 %(patch)s - patch name
61 %(sender)s - 'sender' or 'authname <authemail>' as per 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 %(diff)s - unified diff of the patch
65 %(diffstat)s - diff statistics
66 %(version)s - ' version' string passed on the command line (or empty)
67 %(prefix)s - 'prefix ' string passed on the command line
68 %(patchnr)s - patch number
69 %(totalnr)s - total number of patches to be sent
70 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
71 %(fromauth)s - 'From: author\\n\\n' if different from sender
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 %(sender)s, %(version)s,
79 %(patchnr)s, %(totalnr)s and %(number)s variables are supported."""
81 options
= [make_option('-a', '--all',
82 help = 'e-mail all the applied patches',
83 action
= 'store_true'),
85 help = 'add TO to the To: list',
88 help = 'add CC to the Cc: list',
91 help = 'add BCC to the Bcc: list',
94 help = 'automatically cc the patch signers',
95 action
= 'store_true'),
96 make_option('--noreply',
97 help = 'do not send subsequent messages as replies',
98 action
= 'store_true'),
99 make_option('-v', '--version', metavar
= 'VERSION',
100 help = 'add VERSION to the [PATCH ...] prefix'),
101 make_option('--prefix', metavar
= 'PREFIX',
102 help = 'add PREFIX to the [... PATCH ...] prefix'),
103 make_option('-t', '--template', metavar
= 'FILE',
104 help = 'use FILE as the message template'),
105 make_option('-c', '--cover', metavar
= 'FILE',
106 help = 'send FILE as the cover message'),
107 make_option('-e', '--edit-cover',
108 help = 'edit the cover message before sending',
109 action
= 'store_true'),
110 make_option('-E', '--edit-patches',
111 help = 'edit each patch before sending',
112 action
= 'store_true'),
113 make_option('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
114 help = 'sleep for SECONDS between e-mails sending'),
115 make_option('--refid',
116 help = 'use REFID as the reference id'),
117 make_option('-u', '--smtp-user', metavar
= 'USER',
118 help = 'username for SMTP authentication'),
119 make_option('-p', '--smtp-password', metavar
= 'PASSWORD',
120 help = 'username for SMTP authentication'),
121 make_option('-b', '--branch',
122 help = 'use BRANCH instead of the default one'),
123 make_option('-m', '--mbox',
124 help = 'generate an mbox file instead of sending',
125 action
= 'store_true')]
129 """Return the 'authname <authemail>' string as read from the
132 sender
=config
.get('stgit.sender')
135 sender
= str(git
.user())
136 except git
.GitException
:
137 sender
= str(git
.author())
140 raise CmdException
, 'unknown sender details'
142 return address_or_alias(sender
)
144 def __parse_addresses(addresses
):
145 """Return a two elements tuple: (from, [to])
147 def __addr_list(addrs
):
148 m
= re
.search('[^@\s<,]+@[^>\s,]+', addrs
);
151 return [ m
.group() ] + __addr_list(addrs
[m
.end():])
155 for line
in addresses
.split('\n'):
156 if re
.match('from:\s+', line
, re
.I
):
157 from_addr_list
+= __addr_list(line
)
158 elif re
.match('(to|cc|bcc):\s+', line
, re
.I
):
159 to_addr_list
+= __addr_list(line
)
161 if len(from_addr_list
) == 0:
162 raise CmdException
, 'No "From" address'
163 if len(to_addr_list
) == 0:
164 raise CmdException
, 'No "To/Cc/Bcc" addresses'
166 return (from_addr_list
[0], to_addr_list
)
168 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
169 smtpuser
, smtppassword
):
170 """Send the message using the given SMTP server
173 s
= smtplib
.SMTP(smtpserver
)
174 except Exception, err
:
175 raise CmdException
, str(err
)
179 if smtpuser
and smtppassword
:
181 s
.login(smtpuser
, smtppassword
)
183 s
.sendmail(from_addr
, to_addr_list
, msg
)
184 # give recipients a chance of receiving patches in the correct order
186 except Exception, err
:
187 raise CmdException
, str(err
)
191 def __build_address_headers(msg
, options
, extra_cc
= []):
192 """Build the address headers and check existing headers in the
195 def __replace_header(header
, addr
):
197 crt_addr
= msg
[header
]
201 msg
[header
] = address_or_alias(', '.join([crt_addr
, addr
]))
203 msg
[header
] = address_or_alias(addr
)
209 autobcc
= config
.get('stgit.autobcc') or ''
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 editor
= config
.get('stgit.editor')
285 elif 'EDITOR' in os
.environ
:
286 editor
= os
.environ
['EDITOR']
289 editor
+= ' %s' % fname
291 print 'Invoking the editor: "%s"...' % editor
,
293 print 'done (exit code: %d)' % os
.system(editor
)
295 # read the message back
302 def __build_cover(tmpl
, total_nr
, msg_id
, options
):
303 """Build the cover message (series description) to be sent via SMTP
305 sender
= __get_sender()
308 version_str
= ' %s' % options
.version
313 prefix_str
= options
.prefix
+ ' '
317 total_nr_str
= str(total_nr
)
318 patch_nr_str
= '0'.zfill(len(total_nr_str
))
320 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
324 tmpl_dict
= {'sender': sender
,
325 # for backward template compatibility
326 'maintainer': sender
,
327 # for backward template compatibility
329 # for backward template compatibility
331 'version': version_str
,
332 'prefix': prefix_str
,
333 'patchnr': patch_nr_str
,
334 'totalnr': total_nr_str
,
335 'number': number_str
}
338 msg_string
= tmpl % tmpl_dict
339 except KeyError, err
:
340 raise CmdException
, 'Unknown patch template variable: %s' \
343 raise CmdException
, 'Only "%(name)s" variables are ' \
344 'supported in the patch template'
346 if options
.edit_cover
:
347 msg_string
= __edit_message(msg_string
)
349 # The Python email message
351 msg
= email
.message_from_string(msg_string
)
352 except Exception, ex
:
353 raise CmdException
, 'template parsing error: %s' % str
(ex
)
355 __build_address_headers(msg
, options
)
356 __build_extra_headers(msg
, msg_id
, options
.refid
)
357 __encode_message(msg
)
359 msg_string
= msg
.as_string(options
.mbox
)
361 return msg_string
.strip('\n')
363 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
364 """Build the message to be sent via SMTP
366 p
= crt_series
.get_patch(patch
)
368 descr
= p
.get_description().strip()
369 descr_lines
= descr
.split('\n')
371 short_descr
= descr_lines
[0].rstrip()
372 long_descr
= '\n'.join(descr_lines
[1:]).lstrip()
374 authname
= p
.get_authname();
375 authemail
= p
.get_authemail();
376 commname
= p
.get_commname();
377 commemail
= p
.get_commemail();
379 sender
= __get_sender()
381 fromauth
= '%s <%s>' %
(authname
, authemail
)
382 if fromauth
!= sender
:
383 fromauth
= 'From: %s\n\n' % fromauth
388 version_str
= ' %s' % options
.version
393 prefix_str
= options
.prefix
+ ' '
397 total_nr_str
= str(total_nr
)
398 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
400 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
404 tmpl_dict
= {'patch': patch
,
406 # for backward template compatibility
407 'maintainer': sender
,
408 'shortdescr': short_descr
,
409 'longdescr': long_descr
,
410 # for backward template compatibility
412 'diff': git
.diff(rev1
= git_id('%s//bottom' % patch
),
413 rev2
= git_id('%s//top' % patch
)),
414 'diffstat': git
.diffstat(rev1
= git_id('%s//bottom'%patch
),
415 rev2
= git_id('%s//top' % patch
)),
416 # for backward template compatibility
418 'version': version_str
,
419 'prefix': prefix_str
,
420 'patchnr': patch_nr_str
,
421 'totalnr': total_nr_str
,
422 'number': number_str
,
423 'fromauth': fromauth
,
424 'authname': authname
,
425 'authemail': authemail
,
426 'authdate': p
.get_authdate(),
427 'commname': commname
,
428 'commemail': commemail
}
430 for key
in tmpl_dict
:
431 if not tmpl_dict
[key
]:
435 msg_string
= tmpl % tmpl_dict
436 except KeyError, err
:
437 raise CmdException
, 'Unknown patch template variable: %s' \
440 raise CmdException
, 'Only "%(name)s" variables are ' \
441 'supported in the patch template'
443 if options
.edit_patches
:
444 msg_string
= __edit_message(msg_string
)
446 # The Python email message
448 msg
= email
.message_from_string(msg_string
)
449 except Exception, ex
:
450 raise CmdException
, 'template parsing error: %s' % str
(ex
)
453 extra_cc
= __get_signers_list(descr
)
457 __build_address_headers(msg
, options
, extra_cc
)
458 __build_extra_headers(msg
, msg_id
, ref_id
)
459 __encode_message(msg
)
461 msg_string
= msg
.as_string(options
.mbox
)
463 return msg_string
.strip('\n')
465 def func(parser
, options
, args
):
466 """Send the patches by e-mail using the patchmail.tmpl file as
469 smtpserver
= config
.get('stgit.smtpserver')
471 applied
= crt_series
.get_applied()
476 unapplied
= crt_series
.get_unapplied()
477 patches
= parse_patches(args
, applied
+ unapplied
, len(applied
))
479 raise CmdException
, 'Incorrect options. Unknown patches to send'
481 smtppassword
= options
.smtp_password
or config
.get('stgit.smtppassword')
482 smtpuser
= options
.smtp_user
or config
.get('stgit.smtpuser')
484 if (smtppassword
and not smtpuser
):
485 raise CmdException
, 'SMTP password supplied, username needed'
486 if (smtpuser
and not smtppassword
):
487 raise CmdException
, 'SMTP username supplied, password needed'
489 total_nr
= len(patches
)
491 raise CmdException
, 'No patches to send'
496 ref_id
= options
.refid
498 sleep
= options
.sleep
or config
.getint('stgit.smtpdelay')
500 # send the cover message (if any)
501 if options
.cover
or options
.edit_cover
:
502 # find the template file
504 tmpl
= file(options
.cover
).read()
506 tmpl
= templates
.get_template('covermail.tmpl')
508 raise CmdException
, 'No cover message template file found'
510 msg_id
= email
.Utils
.make_msgid('stgit')
511 msg
= __build_cover(tmpl
, total_nr
, msg_id
, options
)
512 from_addr
, to_addr_list
= __parse_addresses(msg
)
514 # subsequent e-mails are seen as replies to the first one
515 if not options
.noreply
:
522 print 'Sending the cover message...',
524 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
525 smtpuser
, smtppassword
)
530 tmpl
= file(options
.template
).read()
532 tmpl
= templates
.get_template('patchmail.tmpl')
534 raise CmdException
, 'No e-mail template file found'
536 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
537 msg_id
= email
.Utils
.make_msgid('stgit')
538 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
540 from_addr
, to_addr_list
= __parse_addresses(msg
)
542 # subsequent e-mails are seen as replies to the first one
543 if not options
.noreply
and not ref_id
:
550 print 'Sending patch "%s"...' % p
,
552 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
553 smtpuser
, smtppassword
)