1
# Copyright (C) 2005-2011 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
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
22
revision as _mod_revision,
24
from ...config import (
31
from ...smtp_connection import SMTPConnection
32
from ...email_message import EmailMessage
35
class EmailSender(object):
36
"""An email message sender."""
38
_smtplib_implementation = SMTPConnection
40
def __init__(self, branch, revision_id, config, local_branch=None,
44
self.repository = branch.repository
45
if (local_branch is not None and
46
local_branch.repository.has_revision(revision_id)):
47
self.repository = local_branch.repository
48
self._revision_id = revision_id
53
def _setup_revision_and_revno(self):
54
self.revision = self.repository.get_revision(self._revision_id)
55
self.revno = self.branch.revision_id_to_revno(self._revision_id)
57
def _format(self, text):
59
'committer': self.revision.committer,
60
'message': self.revision.get_summary(),
61
'revision': '%d' % self.revno,
64
for name, value in fields.items():
65
text = text.replace('$%s' % name, value)
71
rev1 = rev2 = self.revno
76
# use 'replace' so that we don't abort if trying to write out
77
# in e.g. the default C locale.
79
# We must use StringIO.StringIO because we want a Unicode string that
80
# we can pass to send_email and have that do the proper encoding.
81
from io import StringIO
84
_body = self.config.get('post_commit_body')
86
_body = 'At %s\n\n' % self.url()
87
outf.write(self._format(_body))
89
log_format = self.config.get('post_commit_log_format')
90
lf = log.log_formatter(log_format,
95
if len(self.revision.parent_ids) <= 1:
96
# This is not a merge, so we can special case the display of one
97
# revision, and not have to encur the show_log overhead.
98
lr = log.LogRevision(self.revision, self.revno, 0, None)
101
# let the show_log code figure out what revisions need to be
102
# displayed, as this is a merge
103
log.show_log(self.branch,
110
return outf.getvalue()
113
"""Add the diff from the commit to the output.
115
If the diff has more than difflimit lines, it will be skipped.
117
difflimit = self.difflimit()
119
# No need to compute a diff if we aren't going to display it
122
from ...diff import show_diff_trees
123
# optionally show the diff if its smaller than the post_commit_difflimit option
124
revid_new = self.revision.revision_id
125
if self.revision.parent_ids:
126
revid_old = self.revision.parent_ids[0]
127
tree_new, tree_old = self.repository.revision_trees(
128
(revid_new, revid_old))
130
# revision_trees() doesn't allow None or 'null:' to be passed as a
131
# revision. So we need to call revision_tree() twice.
132
revid_old = _mod_revision.NULL_REVISION
133
tree_new = self.repository.revision_tree(revid_new)
134
tree_old = self.repository.revision_tree(revid_old)
136
# We can use a StringIO because show_diff_trees should only write
137
# 8-bit strings. It is an error to write a Unicode string here.
138
from io import StringIO
139
diff_content = StringIO()
140
diff_options = self.config.get('post_commit_diffoptions')
141
show_diff_trees(tree_old, tree_new, diff_content, None, diff_options)
142
numlines = diff_content.getvalue().count('\n') + 1
143
if numlines <= difflimit:
144
return diff_content.getvalue()
146
return ("\nDiff too large for email"
147
" (%d lines, the limit is %d).\n"
148
% (numlines, difflimit))
151
"""Maximum number of lines of diff to show."""
152
return self.config.get('post_commit_difflimit')
155
"""What mail program to use."""
156
return self.config.get('post_commit_mailer')
158
def _command_line(self):
159
cmd = [self.mailer(), '-s', self.subject(), '-a',
160
"From: " + self.from_address()]
161
cmd.extend(self.to())
165
"""What is the address the mail should go to."""
166
return self.config.get('post_commit_to')
169
"""What URL to display in the subject of the mail"""
170
url = self.config.get('post_commit_url')
172
url = self.config.get('public_branch')
174
url = self.branch.base
177
def from_address(self):
178
"""What address should I send from."""
179
result = self.config.get('post_commit_sender')
181
result = self.config.get('email')
184
def extra_headers(self):
185
"""Additional headers to include when sending."""
187
headers = self.config.get('revision_mail_headers')
191
key, value = line.split(": ", 1)
198
Depending on the configuration, this will either use smtplib, or it
199
will call out to the 'mail' program.
201
with self.branch.lock_read(), self.repository.lock_read():
202
# Do this after we have locked, to make things faster.
203
self._setup_revision_and_revno()
204
mailer = self.mailer()
205
if mailer == 'smtplib':
206
self._send_using_smtplib()
208
self._send_using_process()
210
def _send_using_process(self):
211
"""Spawn a 'mail' subprocess to send the email."""
212
# TODO think up a good test for this, but I think it needs
213
# a custom binary shipped with. RBC 20051021
214
with tempfile.NamedTemporaryFile() as msgfile:
215
msgfile.write(self.body().encode('utf8'))
216
diff = self.get_diff()
222
process = subprocess.Popen(self._command_line(),
223
stdin=msgfile.fileno())
227
raise errors.BzrError(
228
"Failed to send email: exit status %s" % (rc,))
230
def _send_using_smtplib(self):
231
"""Use python's smtplib to send the email."""
233
diff = self.get_diff()
234
subject = self.subject()
235
from_addr = self.from_address()
237
header = self.extra_headers()
239
msg = EmailMessage(from_addr, to_addrs, subject, body)
242
msg.add_inline_attachment(diff, self.diff_filename())
244
# Add revision_mail_headers to the headers
246
for k, v in header.items():
249
smtp = self._smtplib_implementation(self.config)
252
def should_send(self):
253
post_commit_push_pull = self.config.get('post_commit_push_pull')
254
if post_commit_push_pull and self.op == 'commit':
255
# We will be called again with a push op, send the mail then.
257
if not post_commit_push_pull and self.op != 'commit':
258
# Mailing on commit only, and this is a push/pull operation.
260
return bool(self.to() and self.from_address())
262
def send_maybe(self):
263
if self.should_send():
267
_subject = self.config.get('post_commit_subject')
269
_subject = ("Rev %d: %s in %s" %
271
self.revision.get_summary(),
273
return self._format(_subject)
275
def diff_filename(self):
276
return "patch-%s.diff" % (self.revno,)
279
opt_post_commit_body = Option("post_commit_body",
280
help="Body for post commit emails.")
281
opt_post_commit_subject = Option("post_commit_subject",
282
help="Subject for post commit emails.")
283
opt_post_commit_log_format = Option('post_commit_log_format',
284
default='long', help="Log format for option.")
285
opt_post_commit_difflimit = Option('post_commit_difflimit',
286
default=1000, from_unicode=int_from_store,
287
help="Maximum number of lines in diffs.")
288
opt_post_commit_push_pull = Option('post_commit_push_pull',
289
from_unicode=bool_from_store,
290
help="Whether to send emails on push and pull.")
291
opt_post_commit_diffoptions = Option('post_commit_diffoptions',
292
help="Diff options to use.")
293
opt_post_commit_sender = Option('post_commit_sender',
294
help='From address to use for emails.')
295
opt_post_commit_to = ListOption('post_commit_to',
296
help='Address to send commit emails to.')
297
opt_post_commit_mailer = Option('post_commit_mailer',
298
help='Mail client to use.', default='mail')
299
opt_post_commit_url = Option('post_commit_url',
300
help='URL to mention for branch in post commit messages.')
301
opt_revision_mail_headers = ListOption('revision_mail_headers',
302
help="Extra revision headers.")