blob: 34c9ad1f1680134ef698252df61967355aed8dab [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 """
Joe Onorato8c6eef42008-11-14 21:12:44 -050072 editor = cls._GetEditor().split()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070073 fd, path = tempfile.mkstemp()
74 try:
75 os.write(fd, data)
76 os.close(fd)
77 fd = None
78
Joe Onorato8c6eef42008-11-14 21:12:44 -050079 if subprocess.Popen(editor + [path]).wait() != 0:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070080 raise EditorError()
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -070081 fd = open(path)
82 try:
83 return read()
84 finally:
85 fd.close()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070086 finally:
87 if fd:
88 os.close(fd)
89 os.remove(path)