blob: cf0a5ee53b62ac3fcc3558f586fe155d5b1e598f [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
Shawn O. Pearce54fccd72009-06-24 07:09:51 -070079 try:
80 rc = subprocess.Popen(editor + [path]).wait()
81 except OSError, e:
82 raise EditorError('editor failed, %s: %s %s'
83 % (str(e), cls._GetEditor(), path))
84 if rc != 0:
85 raise EditorError('editor failed with exit status %d: %s %s'
86 % (rc, cls._GetEditor(), path))
87
Shawn O. Pearcea8421a12009-04-18 16:57:46 -070088 fd2 = open(path)
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -070089 try:
Shawn O. Pearcea8421a12009-04-18 16:57:46 -070090 return fd2.read()
Shawn O. Pearce76ca9f82009-04-18 14:48:03 -070091 finally:
Shawn O. Pearcea8421a12009-04-18 16:57:46 -070092 fd2.close()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070093 finally:
94 if fd:
95 os.close(fd)
96 os.remove(path)