blob: 4f22257fd628144b68842d3e61885464b91d814a [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001#
2# Copyright (C) 2008 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import os
17import sys
18import subprocess
19import tempfile
20
21from error import EditorError
22
23class Editor(object):
24 """Manages the user's preferred text editor."""
25
26 _editor = None
27 globalConfig = None
28
29 @classmethod
30 def _GetEditor(cls):
31 if cls._editor is None:
32 cls._editor = cls._SelectEditor()
33 return cls._editor
34
35 @classmethod
36 def _SelectEditor(cls):
37 e = os.getenv('GIT_EDITOR')
38 if e:
39 return e
40
41 e = cls.globalConfig.GetString('core.editor')
42 if e:
43 return e
44
45 e = os.getenv('VISUAL')
46 if e:
47 return e
48
49 e = os.getenv('EDITOR')
50 if e:
51 return e
52
53 if os.getenv('TERM') == 'dumb':
54 print >>sys.stderr,\
55"""No editor specified in GIT_EDITOR, core.editor, VISUAL or EDITOR.
56Tried to fall back to vi but terminal is dumb. Please configure at
57least one of these before using this command."""
58 sys.exit(1)
59
60 return 'vi'
61
62 @classmethod
63 def EditString(cls, data):
64 """Opens an editor to edit the given content.
65
66 Args:
67 data : the text to edit
68
69 Returns:
70 new value of edited text; None if editing did not succeed
71 """
72 editor = cls._GetEditor()
73 fd, path = tempfile.mkstemp()
74 try:
75 os.write(fd, data)
76 os.close(fd)
77 fd = None
78
79 if subprocess.Popen([editor, path]).wait() != 0:
80 raise EditorError()
81 return open(path).read()
82 finally:
83 if fd:
84 os.close(fd)
85 os.remove(path)