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
, smtplib
, email
.Utils
19 from optparse
import OptionParser
, make_option
20 from time
import gmtime
, strftime
22 from stgit
.commands
.common
import *
23 from stgit
.utils
import *
24 from stgit
import stack
, git
25 from stgit
.config
import config
28 help = 'send a patch or series of patches by e-mail'
29 usage
= """%prog [options] [<patch>]"""
31 options
= [make_option('-a', '--all',
32 help = 'e-mail all the applied patches',
33 action
= 'store_true'),
34 make_option('-r', '--range',
35 metavar
= '[PATCH1][:[PATCH2]]',
36 help = 'e-mail patches between PATCH1 and PATCH2'),
37 make_option('-t', '--template', metavar
= 'FILE',
38 help = 'use FILE as the message template'),
39 make_option('-f', '--first', metavar
= 'FILE',
40 help = 'send FILE as the first message'),
41 make_option('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
42 help = 'sleep for SECONDS between e-mails sending'),
43 make_option('--refid',
44 help = 'Use REFID as the reference id'),
45 make_option('-u', '--smtp-user', metavar
= 'USER',
46 help = 'username for SMTP authentication'),
47 make_option('-p', '--smtp-password', metavar
= 'PASSWORD',
48 help = 'username for SMTP authentication')]
51 def __parse_addresses(string
):
52 """Return a two elements tuple: (from, [to])
54 def __addr_list(string
):
55 return re
.split('.*?([\w\.]+@[\w\.]+)', string
)[1:-1:2]
59 for line
in string
.split('\n'):
60 if re
.match('from:\s+', line
, re
.I
):
61 from_addr_list
+= __addr_list(line
)
62 elif re
.match('(to|cc|bcc):\s+', line
, re
.I
):
63 to_addr_list
+= __addr_list(line
)
65 if len(from_addr_list
) != 1:
66 raise CmdException
, 'No "From" address'
67 if len(to_addr_list
) == 0:
68 raise CmdException
, 'No "To/Cc/Bcc" addresses'
70 return (from_addr_list
[0], to_addr_list
)
72 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
73 smtpuser
, smtppassword
):
74 """Send the message using the given SMTP server
77 s
= smtplib
.SMTP(smtpserver
)
78 except Exception, err
:
79 raise CmdException
, str(err
)
83 if smtpuser
and smtppassword
:
85 s
.login(smtpuser
, smtppassword
)
87 s
.sendmail(from_addr
, to_addr_list
, msg
)
88 # give recipients a chance of receiving patches in the correct order
90 except Exception, err
:
91 raise CmdException
, str(err
)
95 def __build_first(tmpl
, total_nr
, msg_id
):
96 """Build the first message (series description) to be sent via SMTP
98 headers_end
= 'Message-Id: %s\n' %
(msg_id
)
99 total_nr_str
= str(total_nr
)
101 tmpl_dict
= {'endofheaders': headers_end
,
102 'date': email
.Utils
.formatdate(localtime
= True),
103 'totalnr': total_nr_str
}
106 msg
= tmpl % tmpl_dict
107 except KeyError, err
:
108 raise CmdException
, 'Unknown patch template variable: %s' \
111 raise CmdException
, 'Only "%(name)s" variables are ' \
112 'supported in the patch template'
117 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
= None):
118 """Build the message to be sent via SMTP
120 p
= crt_series
.get_patch(patch
)
122 descr
= p
.get_description().strip()
123 descr_lines
= descr
.split('\n')
125 short_descr
= descr_lines
[0].rstrip()
126 long_descr
= reduce(lambda x
, y
: x
+ '\n' + y
,
127 descr_lines
[1:], '').lstrip()
129 headers_end
= 'Message-Id: %s\n' %
(msg_id
)
131 headers_end
+= "In-Reply-To: %s\n" %
(ref_id
)
132 headers_end
+= "References: %s\n" %
(ref_id
)
134 total_nr_str
= str(total_nr
)
135 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
137 tmpl_dict
= {'patch': patch
,
138 'shortdescr': short_descr
,
139 'longdescr': long_descr
,
140 'endofheaders': headers_end
,
141 'diff': git
.diff(rev1
= git_id('%s/bottom' % patch
),
142 rev2
= git_id('%s/top' % patch
)),
143 'diffstat': git
.diffstat(rev1
= git_id('%s/bottom'%patch
),
144 rev2
= git_id('%s/top' % patch
)),
145 'date': email
.Utils
.formatdate(localtime
= True),
146 'patchnr': patch_nr_str
,
147 'totalnr': total_nr_str
,
148 'authname': p
.get_authname(),
149 'authemail': p
.get_authemail(),
150 'authdate': p
.get_authdate(),
151 'commname': p
.get_commname(),
152 'commemail': p
.get_commemail()}
153 for key
in tmpl_dict
:
154 if not tmpl_dict
[key
]:
158 msg
= tmpl % tmpl_dict
159 except KeyError, err
:
160 raise CmdException
, 'Unknown patch template variable: %s' \
163 raise CmdException
, 'Only "%(name)s" variables are ' \
164 'supported in the patch template'
169 def func(parser
, options
, args
):
170 """Send the patches by e-mail using the patchmail.tmpl file as
174 parser
.error('incorrect number of arguments')
176 if not config
.has_option('stgit', 'smtpserver'):
177 raise CmdException
, 'smtpserver not defined'
178 smtpserver
= config
.get('stgit', 'smtpserver')
182 if config
.has_option('stgit', 'smtpuser'):
183 smtpuser
= config
.get('stgit', 'smtpuser')
184 if config
.has_option('stgit', 'smtppassword'):
185 smtppassword
= config
.get('stgit', 'smtppassword')
187 applied
= crt_series
.get_applied()
190 if args
[0] in applied
:
193 raise CmdException
, 'Patch "%s" not applied' % args
[0]
197 boundaries
= options
.range.split(':')
198 if len(boundaries
) == 1:
199 start
= boundaries
[0]
201 elif len(boundaries
) == 2:
202 if boundaries
[0] == '':
205 start
= boundaries
[0]
206 if boundaries
[1] == '':
211 raise CmdException
, 'incorrect parameters to "--range"'
214 start_idx
= applied
.index(start
)
216 raise CmdException
, 'Patch "%s" not applied' % start
218 stop_idx
= applied
.index(stop
) + 1
220 raise CmdException
, 'Patch "%s" not applied' % stop
222 if start_idx
>= stop_idx
:
223 raise CmdException
, 'Incorrect patch range order'
225 patches
= applied
[start_idx
:stop_idx
]
227 raise CmdException
, 'Incorrect options. Unknown patches to send'
229 if options
.smtp_password
:
230 smtppassword
= options
.smtp_password
232 if options
.smtp_user
:
233 smtpuser
= options
.smtp_user
235 if (smtppassword
and not smtpuser
):
236 raise CmdException
, 'SMTP password supplied, username needed'
237 if (smtpuser
and not smtppassword
):
238 raise CmdException
, 'SMTP username supplied, password needed'
240 total_nr
= len(patches
)
242 raise CmdException
, 'No patches to send'
244 ref_id
= options
.refid
246 if options
.sleep
!= None:
247 sleep
= options
.sleep
251 # send the first message (if any)
253 tmpl
= file(options
.first
).read()
254 from_addr
, to_addr_list
= __parse_addresses(tmpl
)
256 msg_id
= email
.Utils
.make_msgid('stgit')
257 msg
= __build_first(tmpl
, total_nr
, msg_id
)
259 # subsequent e-mails are seen as replies to the first one
262 print 'Sending file "%s"...' % options
.first
,
265 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
266 smtpuser
, smtppassword
)
272 tfile
= options
.template
274 tfile
= os
.path
.join(git
.base_dir
, 'patchmail.tmpl')
275 tmpl
= file(tfile
).read()
277 from_addr
, to_addr_list
= __parse_addresses(tmpl
)
279 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
280 msg_id
= email
.Utils
.make_msgid('stgit')
281 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
)
282 # subsequent e-mails are seen as replies to the first one
286 print 'Sending patch "%s"...' % p
,
289 __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
290 smtpuser
, smtppassword
)