~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/msgeditor.py

  • Committer: Martin Pool
  • Date: 2005-05-09 03:03:55 UTC
  • Revision ID: mbp@sourcefrog.net-20050509030355-ad6ab558d1362959
- Don't give an error if the trace file can't be opened

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Bazaar-NG -- distributed version control
2
 
 
3
 
# Copyright (C) 2005 by Canonical Ltd
4
 
 
5
 
# This program is free software; you can redistribute it and/or modify
6
 
# it under the terms of the GNU General Public License as published by
7
 
# the Free Software Foundation; either version 2 of the License, or
8
 
# (at your option) any later version.
9
 
 
10
 
# This program is distributed in the hope that it will be useful,
11
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 
# GNU General Public License for more details.
14
 
 
15
 
# You should have received a copy of the GNU General Public License
16
 
# along with this program; if not, write to the Free Software
17
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 
 
19
 
 
20
 
"""Commit message editor support."""
21
 
 
22
 
import os
23
 
import errno
24
 
from subprocess import call
25
 
 
26
 
import bzrlib.config as config
27
 
from bzrlib.errors import BzrError
28
 
 
29
 
def _get_editor():
30
 
    """Return a sequence of possible editor binaries for the current platform"""
31
 
    try:
32
 
        yield os.environ["BZR_EDITOR"]
33
 
    except KeyError:
34
 
        pass
35
 
 
36
 
    e = config.GlobalConfig().get_editor()
37
 
    if e is not None:
38
 
        yield e
39
 
        
40
 
    try:
41
 
        yield os.environ["EDITOR"]
42
 
    except KeyError:
43
 
        pass
44
 
 
45
 
    if os.name == "nt":
46
 
        yield "notepad.exe"
47
 
    elif os.name == "posix":
48
 
        yield "/usr/bin/vi"
49
 
 
50
 
 
51
 
def _run_editor(filename):
52
 
    """Try to execute an editor to edit the commit message."""
53
 
    for e in _get_editor():
54
 
        edargs = e.split(' ')
55
 
        try:
56
 
            x = call(edargs + [filename])
57
 
        except OSError, e:
58
 
           # ENOENT means no such editor
59
 
           if e.errno == errno.ENOENT:
60
 
               continue
61
 
           raise
62
 
        if x == 0:
63
 
            return True
64
 
        elif x == 127:
65
 
            continue
66
 
        else:
67
 
            break
68
 
    raise BzrError("Could not start any editor. "
69
 
                   "Please specify $EDITOR or use ~/.bzr.conf/editor")
70
 
 
71
 
 
72
 
DEFAULT_IGNORE_LINE = "%(bar)s %(msg)s %(bar)s" % \
73
 
    { 'bar' : '-' * 14, 'msg' : 'This line and the following will be ignored' }
74
 
 
75
 
 
76
 
def edit_commit_message(infotext, ignoreline=DEFAULT_IGNORE_LINE):
77
 
    """Let the user edit a commit message in a temp file.
78
 
 
79
 
    This is run if they don't give a message or
80
 
    message-containing file on the command line.
81
 
 
82
 
    infotext:
83
 
        Text to be displayed at bottom of message for
84
 
        the user's reference; currently similar to
85
 
        'bzr status'.
86
 
    """
87
 
    import tempfile
88
 
 
89
 
    try:
90
 
        tmp_fileno, msgfilename = tempfile.mkstemp(prefix='bzr_log.', dir=u'.')
91
 
        msgfile = os.close(tmp_fileno)
92
 
        if infotext is not None and infotext != "":
93
 
            hasinfo = True
94
 
            msgfile = file(msgfilename, "w")
95
 
            msgfile.write("\n\n%s\n\n%s" % (ignoreline, infotext))
96
 
            msgfile.close()
97
 
        else:
98
 
            hasinfo = False
99
 
 
100
 
        if not _run_editor(msgfilename):
101
 
            return None
102
 
        
103
 
        started = False
104
 
        msg = []
105
 
        lastline, nlines = 0, 0
106
 
        for line in file(msgfilename, "r"):
107
 
            stripped_line = line.strip()
108
 
            # strip empty line before the log message starts
109
 
            if not started:
110
 
                if stripped_line != "":
111
 
                    started = True
112
 
                else:
113
 
                    continue
114
 
            # check for the ignore line only if there
115
 
            # is additional information at the end
116
 
            if hasinfo and stripped_line == ignoreline:
117
 
                break
118
 
            nlines += 1
119
 
            # keep track of the last line that had some content
120
 
            if stripped_line != "":
121
 
                lastline = nlines
122
 
            msg.append(line)
123
 
            
124
 
        if len(msg) == 0:
125
 
            return ""
126
 
        # delete empty lines at the end
127
 
        del msg[lastline:]
128
 
        # add a newline at the end, if needed
129
 
        if not msg[-1].endswith("\n"):
130
 
            return "%s%s" % ("".join(msg), "\n")
131
 
        else:
132
 
            return "".join(msg)
133
 
    finally:
134
 
        # delete the msg file in any case
135
 
        try: os.unlink(msgfilename)
136
 
        except IOError: pass
137
 
 
138
 
 
139
 
def make_commit_message_template(working_tree, specific_files):
140
 
    """Prepare a template file for a commit into a branch.
141
 
 
142
 
    Returns a unicode string containing the template.
143
 
    """
144
 
    # TODO: Should probably be given the WorkingTree not the branch
145
 
    #
146
 
    # TODO: make provision for this to be overridden or modified by a hook
147
 
    #
148
 
    # TODO: Rather than running the status command, should prepare a draft of
149
 
    # the revision to be committed, then pause and ask the user to
150
 
    # confirm/write a message.
151
 
    from StringIO import StringIO       # must be unicode-safe
152
 
    from bzrlib.status import show_tree_status
153
 
    status_tmp = StringIO()
154
 
    show_tree_status(working_tree, specific_files=specific_files, 
155
 
                     to_file=status_tmp)
156
 
    return status_tmp.getvalue()