/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/msgeditor.py

  • Committer: Andrew Bennetts
  • Date: 2008-04-02 00:14:00 UTC
  • mfrom: (3324 +trunk)
  • mto: This revision was merged to the branch mainline in revision 3756.
  • Revision ID: andrew.bennetts@canonical.com-20080402001400-r1pqse38i03dl97w
Merge from bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
 
18
"""Commit message editor support."""
 
19
 
 
20
import codecs
 
21
import errno
 
22
import os
 
23
from subprocess import call
 
24
import sys
 
25
 
 
26
import bzrlib.config as config
 
27
from bzrlib import osutils
 
28
from bzrlib.errors import BzrError, BadCommitMessageEncoding
 
29
from bzrlib.trace import warning, mutter
 
30
 
 
31
 
 
32
def _get_editor():
 
33
    """Return a sequence of possible editor binaries for the current platform"""
 
34
    try:
 
35
        yield os.environ["BZR_EDITOR"]
 
36
    except KeyError:
 
37
        pass
 
38
 
 
39
    e = config.GlobalConfig().get_editor()
 
40
    if e is not None:
 
41
        yield e
 
42
        
 
43
    for varname in 'VISUAL', 'EDITOR':
 
44
        if varname in os.environ:
 
45
            yield os.environ[varname]
 
46
 
 
47
    if sys.platform == 'win32':
 
48
        for editor in 'wordpad.exe', 'notepad.exe':
 
49
            yield editor
 
50
    else:
 
51
        for editor in ['/usr/bin/editor', 'vi', 'pico', 'nano', 'joe']:
 
52
            yield editor
 
53
 
 
54
 
 
55
def _run_editor(filename):
 
56
    """Try to execute an editor to edit the commit message."""
 
57
    for e in _get_editor():
 
58
        edargs = e.split(' ')
 
59
        try:
 
60
            ## mutter("trying editor: %r", (edargs +[filename]))
 
61
            x = call(edargs + [filename])
 
62
        except OSError, e:
 
63
           # We're searching for an editor, so catch safe errors and continue
 
64
           if e.errno in (errno.ENOENT, ):
 
65
               continue
 
66
           raise
 
67
        if x == 0:
 
68
            return True
 
69
        elif x == 127:
 
70
            continue
 
71
        else:
 
72
            break
 
73
    raise BzrError("Could not start any editor.\nPlease specify one with:\n"
 
74
                   " - $BZR_EDITOR\n - editor=/some/path in %s\n"
 
75
                   " - $VISUAL\n - $EDITOR" % \
 
76
                    config.config_filename())
 
77
 
 
78
 
 
79
DEFAULT_IGNORE_LINE = "%(bar)s %(msg)s %(bar)s" % \
 
80
    { 'bar' : '-' * 14, 'msg' : 'This line and the following will be ignored' }
 
81
 
 
82
 
 
83
def edit_commit_message(infotext, ignoreline=DEFAULT_IGNORE_LINE,
 
84
                        start_message=None):
 
85
    """Let the user edit a commit message in a temp file.
 
86
 
 
87
    This is run if they don't give a message or
 
88
    message-containing file on the command line.
 
89
 
 
90
    :param infotext:    Text to be displayed at bottom of message
 
91
                        for the user's reference;
 
92
                        currently similar to 'bzr status'.
 
93
 
 
94
    :param ignoreline:  The separator to use above the infotext.
 
95
 
 
96
    :param start_message:   The text to place above the separator, if any.
 
97
                            This will not be removed from the message
 
98
                            after the user has edited it.
 
99
 
 
100
    :return:    commit message or None.
 
101
    """
 
102
 
 
103
    if not start_message is None:
 
104
        start_message = start_message.encode(osutils.get_user_encoding())
 
105
    infotext = infotext.encode(osutils.get_user_encoding(), 'replace')
 
106
    return edit_commit_message_encoded(infotext, ignoreline, start_message)
 
107
 
 
108
 
 
109
def edit_commit_message_encoded(infotext, ignoreline=DEFAULT_IGNORE_LINE,
 
110
                                start_message=None):
 
111
    """Let the user edit a commit message in a temp file.
 
112
 
 
113
    This is run if they don't give a message or
 
114
    message-containing file on the command line.
 
115
 
 
116
    :param infotext:    Text to be displayed at bottom of message
 
117
                        for the user's reference;
 
118
                        currently similar to 'bzr status'.
 
119
                        The string is already encoded
 
120
 
 
121
    :param ignoreline:  The separator to use above the infotext.
 
122
 
 
123
    :param start_message:   The text to place above the separator, if any.
 
124
                            This will not be removed from the message
 
125
                            after the user has edited it.
 
126
                            The string is already encoded
 
127
 
 
128
    :return:    commit message or None.
 
129
    """
 
130
    msgfilename = None
 
131
    try:
 
132
        msgfilename, hasinfo = _create_temp_file_with_commit_template(
 
133
                                    infotext, ignoreline, start_message)
 
134
 
 
135
        if not msgfilename or not _run_editor(msgfilename):
 
136
            return None
 
137
        
 
138
        started = False
 
139
        msg = []
 
140
        lastline, nlines = 0, 0
 
141
        # codecs.open() ALWAYS opens file in binary mode but we need text mode
 
142
        # 'rU' mode useful when bzr.exe used on Cygwin (bialix 20070430)
 
143
        f = file(msgfilename, 'rU')
 
144
        try:
 
145
            try:
 
146
                for line in codecs.getreader(osutils.get_user_encoding())(f):
 
147
                    stripped_line = line.strip()
 
148
                    # strip empty line before the log message starts
 
149
                    if not started:
 
150
                        if stripped_line != "":
 
151
                            started = True
 
152
                        else:
 
153
                            continue
 
154
                    # check for the ignore line only if there
 
155
                    # is additional information at the end
 
156
                    if hasinfo and stripped_line == ignoreline:
 
157
                        break
 
158
                    nlines += 1
 
159
                    # keep track of the last line that had some content
 
160
                    if stripped_line != "":
 
161
                        lastline = nlines
 
162
                    msg.append(line)
 
163
            except UnicodeDecodeError:
 
164
                raise BadCommitMessageEncoding()
 
165
        finally:
 
166
            f.close()
 
167
 
 
168
        if len(msg) == 0:
 
169
            return ""
 
170
        # delete empty lines at the end
 
171
        del msg[lastline:]
 
172
        # add a newline at the end, if needed
 
173
        if not msg[-1].endswith("\n"):
 
174
            return "%s%s" % ("".join(msg), "\n")
 
175
        else:
 
176
            return "".join(msg)
 
177
    finally:
 
178
        # delete the msg file in any case
 
179
        if msgfilename is not None:
 
180
            try:
 
181
                os.unlink(msgfilename)
 
182
            except IOError, e:
 
183
                warning("failed to unlink %s: %s; ignored", msgfilename, e)
 
184
 
 
185
 
 
186
def _create_temp_file_with_commit_template(infotext,
 
187
                                           ignoreline=DEFAULT_IGNORE_LINE,
 
188
                                           start_message=None):
 
189
    """Create temp file and write commit template in it.
 
190
 
 
191
    :param infotext:    Text to be displayed at bottom of message
 
192
                        for the user's reference;
 
193
                        currently similar to 'bzr status'.
 
194
                        The text is already encoded.
 
195
 
 
196
    :param ignoreline:  The separator to use above the infotext.
 
197
 
 
198
    :param start_message:   The text to place above the separator, if any.
 
199
                            This will not be removed from the message
 
200
                            after the user has edited it.
 
201
                            The string is already encoded
 
202
 
 
203
    :return:    2-tuple (temp file name, hasinfo)
 
204
    """
 
205
    import tempfile
 
206
    tmp_fileno, msgfilename = tempfile.mkstemp(prefix='bzr_log.',
 
207
                                               dir='.',
 
208
                                               text=True)
 
209
    msgfilename = osutils.basename(msgfilename)
 
210
    msgfile = os.fdopen(tmp_fileno, 'w')
 
211
    try:
 
212
        if start_message is not None:
 
213
            msgfile.write("%s\n" % start_message)
 
214
 
 
215
        if infotext is not None and infotext != "":
 
216
            hasinfo = True
 
217
            msgfile.write("\n\n%s\n\n%s" %(ignoreline, infotext))
 
218
        else:
 
219
            hasinfo = False
 
220
    finally:
 
221
        msgfile.close()
 
222
 
 
223
    return (msgfilename, hasinfo)
 
224
 
 
225
 
 
226
def make_commit_message_template(working_tree, specific_files):
 
227
    """Prepare a template file for a commit into a branch.
 
228
 
 
229
    Returns a unicode string containing the template.
 
230
    """
 
231
    # TODO: make provision for this to be overridden or modified by a hook
 
232
    #
 
233
    # TODO: Rather than running the status command, should prepare a draft of
 
234
    # the revision to be committed, then pause and ask the user to
 
235
    # confirm/write a message.
 
236
    from StringIO import StringIO       # must be unicode-safe
 
237
    from bzrlib.status import show_tree_status
 
238
    status_tmp = StringIO()
 
239
    show_tree_status(working_tree, specific_files=specific_files, 
 
240
                     to_file=status_tmp)
 
241
    return status_tmp.getvalue()
 
242
 
 
243
 
 
244
def make_commit_message_template_encoded(working_tree, specific_files,
 
245
                                         diff=None, output_encoding='utf-8'):
 
246
    """Prepare a template file for a commit into a branch.
 
247
 
 
248
    Returns an encoded string.
 
249
    """
 
250
    # TODO: make provision for this to be overridden or modified by a hook
 
251
    #
 
252
    # TODO: Rather than running the status command, should prepare a draft of
 
253
    # the revision to be committed, then pause and ask the user to
 
254
    # confirm/write a message.
 
255
    from StringIO import StringIO       # must be unicode-safe
 
256
    from bzrlib.diff import show_diff_trees
 
257
 
 
258
    template = make_commit_message_template(working_tree, specific_files)
 
259
    template = template.encode(output_encoding, "replace")
 
260
 
 
261
    if diff:
 
262
        stream = StringIO()
 
263
        show_diff_trees(working_tree.basis_tree(),
 
264
                        working_tree, stream, specific_files,
 
265
                        path_encoding=output_encoding)
 
266
        template = template + '\n' + stream.getvalue()
 
267
 
 
268
    return template