~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/msgeditor.py

  • Committer: Martin
  • Date: 2010-05-03 20:57:39 UTC
  • mto: This revision was merged to the branch mainline in revision 5204.
  • Revision ID: gzlist@googlemail.com-20100503205739-n326zdvevv0rmruh
Retain original stack and error message when translating to ValueError in bencode

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2010 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
"""Commit message editor support."""
 
19
 
 
20
import codecs
 
21
import os
 
22
from subprocess import call
 
23
import sys
 
24
 
 
25
from bzrlib import (
 
26
    config,
 
27
    osutils,
 
28
    trace,
 
29
    transport,
 
30
    ui,
 
31
    )
 
32
from bzrlib.errors import BzrError, BadCommitMessageEncoding
 
33
from bzrlib.hooks import HookPoint, Hooks
 
34
 
 
35
 
 
36
def _get_editor():
 
37
    """Return a sequence of possible editor binaries for the current platform"""
 
38
    try:
 
39
        yield os.environ["BZR_EDITOR"], '$BZR_EDITOR'
 
40
    except KeyError:
 
41
        pass
 
42
 
 
43
    e = config.GlobalConfig().get_editor()
 
44
    if e is not None:
 
45
        yield e, config.config_filename()
 
46
 
 
47
    for varname in 'VISUAL', 'EDITOR':
 
48
        if varname in os.environ:
 
49
            yield os.environ[varname], '$' + varname
 
50
 
 
51
    if sys.platform == 'win32':
 
52
        for editor in 'wordpad.exe', 'notepad.exe':
 
53
            yield editor, None
 
54
    else:
 
55
        for editor in ['/usr/bin/editor', 'vi', 'pico', 'nano', 'joe']:
 
56
            yield editor, None
 
57
 
 
58
 
 
59
def _run_editor(filename):
 
60
    """Try to execute an editor to edit the commit message."""
 
61
    for candidate, candidate_source in _get_editor():
 
62
        edargs = candidate.split(' ')
 
63
        try:
 
64
            ## mutter("trying editor: %r", (edargs +[filename]))
 
65
            x = call(edargs + [filename])
 
66
        except OSError, e:
 
67
            if candidate_source is not None:
 
68
                # We tried this editor because some user configuration (an
 
69
                # environment variable or config file) said to try it.  Let
 
70
                # the user know their configuration is broken.
 
71
                trace.warning(
 
72
                    'Could not start editor "%s" (specified by %s): %s\n'
 
73
                    % (candidate, candidate_source, str(e)))
 
74
            continue
 
75
            raise
 
76
        if x == 0:
 
77
            return True
 
78
        elif x == 127:
 
79
            continue
 
80
        else:
 
81
            break
 
82
    raise BzrError("Could not start any editor.\nPlease specify one with:\n"
 
83
                   " - $BZR_EDITOR\n - editor=/some/path in %s\n"
 
84
                   " - $VISUAL\n - $EDITOR" % \
 
85
                    config.config_filename())
 
86
 
 
87
 
 
88
DEFAULT_IGNORE_LINE = "%(bar)s %(msg)s %(bar)s" % \
 
89
    { 'bar' : '-' * 14, 'msg' : 'This line and the following will be ignored' }
 
90
 
 
91
 
 
92
def edit_commit_message(infotext, ignoreline=DEFAULT_IGNORE_LINE,
 
93
                        start_message=None):
 
94
    """Let the user edit a commit message in a temp file.
 
95
 
 
96
    This is run if they don't give a message or
 
97
    message-containing file on the command line.
 
98
 
 
99
    :param infotext:    Text to be displayed at bottom of message
 
100
                        for the user's reference;
 
101
                        currently similar to 'bzr status'.
 
102
 
 
103
    :param ignoreline:  The separator to use above the infotext.
 
104
 
 
105
    :param start_message:   The text to place above the separator, if any.
 
106
                            This will not be removed from the message
 
107
                            after the user has edited it.
 
108
 
 
109
    :return:    commit message or None.
 
110
    """
 
111
 
 
112
    if not start_message is None:
 
113
        start_message = start_message.encode(osutils.get_user_encoding())
 
114
    infotext = infotext.encode(osutils.get_user_encoding(), 'replace')
 
115
    return edit_commit_message_encoded(infotext, ignoreline, start_message)
 
116
 
 
117
 
 
118
def edit_commit_message_encoded(infotext, ignoreline=DEFAULT_IGNORE_LINE,
 
119
                                start_message=None):
 
120
    """Let the user edit a commit message in a temp file.
 
121
 
 
122
    This is run if they don't give a message or
 
123
    message-containing file on the command line.
 
124
 
 
125
    :param infotext:    Text to be displayed at bottom of message
 
126
                        for the user's reference;
 
127
                        currently similar to 'bzr status'.
 
128
                        The string is already encoded
 
129
 
 
130
    :param ignoreline:  The separator to use above the infotext.
 
131
 
 
132
    :param start_message:   The text to place above the separator, if any.
 
133
                            This will not be removed from the message
 
134
                            after the user has edited it.
 
135
                            The string is already encoded
 
136
 
 
137
    :return:    commit message or None.
 
138
    """
 
139
    msgfilename = None
 
140
    try:
 
141
        msgfilename, hasinfo = _create_temp_file_with_commit_template(
 
142
                                    infotext, ignoreline, start_message)
 
143
        if not msgfilename:
 
144
            return None
 
145
        basename = osutils.basename(msgfilename)
 
146
        msg_transport = transport.get_transport(osutils.dirname(msgfilename))
 
147
        reference_content = msg_transport.get_bytes(basename)
 
148
        if not _run_editor(msgfilename):
 
149
            return None
 
150
        edited_content = msg_transport.get_bytes(basename)
 
151
        if edited_content == reference_content:
 
152
            if not ui.ui_factory.get_boolean(
 
153
                "Commit message was not edited, use anyway"):
 
154
                # Returning "" makes cmd_commit raise 'empty commit message
 
155
                # specified' which is a reasonable error, given the user has
 
156
                # rejected using the unedited template.
 
157
                return ""
 
158
        started = False
 
159
        msg = []
 
160
        lastline, nlines = 0, 0
 
161
        # codecs.open() ALWAYS opens file in binary mode but we need text mode
 
162
        # 'rU' mode useful when bzr.exe used on Cygwin (bialix 20070430)
 
163
        f = file(msgfilename, 'rU')
 
164
        try:
 
165
            try:
 
166
                for line in codecs.getreader(osutils.get_user_encoding())(f):
 
167
                    stripped_line = line.strip()
 
168
                    # strip empty line before the log message starts
 
169
                    if not started:
 
170
                        if stripped_line != "":
 
171
                            started = True
 
172
                        else:
 
173
                            continue
 
174
                    # check for the ignore line only if there
 
175
                    # is additional information at the end
 
176
                    if hasinfo and stripped_line == ignoreline:
 
177
                        break
 
178
                    nlines += 1
 
179
                    # keep track of the last line that had some content
 
180
                    if stripped_line != "":
 
181
                        lastline = nlines
 
182
                    msg.append(line)
 
183
            except UnicodeDecodeError:
 
184
                raise BadCommitMessageEncoding()
 
185
        finally:
 
186
            f.close()
 
187
 
 
188
        if len(msg) == 0:
 
189
            return ""
 
190
        # delete empty lines at the end
 
191
        del msg[lastline:]
 
192
        # add a newline at the end, if needed
 
193
        if not msg[-1].endswith("\n"):
 
194
            return "%s%s" % ("".join(msg), "\n")
 
195
        else:
 
196
            return "".join(msg)
 
197
    finally:
 
198
        # delete the msg file in any case
 
199
        if msgfilename is not None:
 
200
            try:
 
201
                os.unlink(msgfilename)
 
202
            except IOError, e:
 
203
                trace.warning(
 
204
                    "failed to unlink %s: %s; ignored", msgfilename, e)
 
205
 
 
206
 
 
207
def _create_temp_file_with_commit_template(infotext,
 
208
                                           ignoreline=DEFAULT_IGNORE_LINE,
 
209
                                           start_message=None):
 
210
    """Create temp file and write commit template in it.
 
211
 
 
212
    :param infotext:    Text to be displayed at bottom of message
 
213
                        for the user's reference;
 
214
                        currently similar to 'bzr status'.
 
215
                        The text is already encoded.
 
216
 
 
217
    :param ignoreline:  The separator to use above the infotext.
 
218
 
 
219
    :param start_message:   The text to place above the separator, if any.
 
220
                            This will not be removed from the message
 
221
                            after the user has edited it.
 
222
                            The string is already encoded
 
223
 
 
224
    :return:    2-tuple (temp file name, hasinfo)
 
225
    """
 
226
    import tempfile
 
227
    tmp_fileno, msgfilename = tempfile.mkstemp(prefix='bzr_log.',
 
228
                                               dir='.',
 
229
                                               text=True)
 
230
    msgfilename = osutils.basename(msgfilename)
 
231
    msgfile = os.fdopen(tmp_fileno, 'w')
 
232
    try:
 
233
        if start_message is not None:
 
234
            msgfile.write("%s\n" % start_message)
 
235
 
 
236
        if infotext is not None and infotext != "":
 
237
            hasinfo = True
 
238
            msgfile.write("\n\n%s\n\n%s" %(ignoreline, infotext))
 
239
        else:
 
240
            hasinfo = False
 
241
    finally:
 
242
        msgfile.close()
 
243
 
 
244
    return (msgfilename, hasinfo)
 
245
 
 
246
 
 
247
def make_commit_message_template(working_tree, specific_files):
 
248
    """Prepare a template file for a commit into a branch.
 
249
 
 
250
    Returns a unicode string containing the template.
 
251
    """
 
252
    # TODO: make provision for this to be overridden or modified by a hook
 
253
    #
 
254
    # TODO: Rather than running the status command, should prepare a draft of
 
255
    # the revision to be committed, then pause and ask the user to
 
256
    # confirm/write a message.
 
257
    from StringIO import StringIO       # must be unicode-safe
 
258
    from bzrlib.status import show_tree_status
 
259
    status_tmp = StringIO()
 
260
    show_tree_status(working_tree, specific_files=specific_files,
 
261
                     to_file=status_tmp, verbose=True)
 
262
    return status_tmp.getvalue()
 
263
 
 
264
 
 
265
def make_commit_message_template_encoded(working_tree, specific_files,
 
266
                                         diff=None, output_encoding='utf-8'):
 
267
    """Prepare a template file for a commit into a branch.
 
268
 
 
269
    Returns an encoded string.
 
270
    """
 
271
    # TODO: make provision for this to be overridden or modified by a hook
 
272
    #
 
273
    # TODO: Rather than running the status command, should prepare a draft of
 
274
    # the revision to be committed, then pause and ask the user to
 
275
    # confirm/write a message.
 
276
    from StringIO import StringIO       # must be unicode-safe
 
277
    from bzrlib.diff import show_diff_trees
 
278
 
 
279
    template = make_commit_message_template(working_tree, specific_files)
 
280
    template = template.encode(output_encoding, "replace")
 
281
 
 
282
    if diff:
 
283
        stream = StringIO()
 
284
        show_diff_trees(working_tree.basis_tree(),
 
285
                        working_tree, stream, specific_files,
 
286
                        path_encoding=output_encoding)
 
287
        template = template + '\n' + stream.getvalue()
 
288
 
 
289
    return template
 
290
 
 
291
 
 
292
class MessageEditorHooks(Hooks):
 
293
    """A dictionary mapping hook name to a list of callables for message editor
 
294
    hooks.
 
295
 
 
296
    e.g. ['commit_message_template'] is the list of items to be called to
 
297
    generate a commit message template
 
298
    """
 
299
 
 
300
    def __init__(self):
 
301
        """Create the default hooks.
 
302
 
 
303
        These are all empty initially.
 
304
        """
 
305
        Hooks.__init__(self)
 
306
        self.create_hook(HookPoint('commit_message_template',
 
307
            "Called when a commit message is being generated. "
 
308
            "commit_message_template is called with the bzrlib.commit.Commit "
 
309
            "object and the message that is known so far. "
 
310
            "commit_message_template must return a new message to use (which "
 
311
            "could be the same as it was given. When there are multiple "
 
312
            "hooks registered for commit_message_template, they are chained "
 
313
            "with the result from the first passed into the second, and so "
 
314
            "on.", (1, 10), None))
 
315
 
 
316
 
 
317
hooks = MessageEditorHooks()
 
318
 
 
319
 
 
320
def generate_commit_message_template(commit, start_message=None):
 
321
    """Generate a commit message template.
 
322
 
 
323
    :param commit: Commit object for the active commit.
 
324
    :param start_message: Message to start with.
 
325
    :return: A start commit message or None for an empty start commit message.
 
326
    """
 
327
    start_message = None
 
328
    for hook in hooks['commit_message_template']:
 
329
        start_message = hook(commit, start_message)
 
330
    return start_message