editor.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #
  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. import os
  16. import re
  17. import sys
  18. import subprocess
  19. import tempfile
  20. from error import EditorError
  21. class Editor(object):
  22. """Manages the user's preferred text editor."""
  23. _editor = None
  24. globalConfig = None
  25. @classmethod
  26. def _GetEditor(cls):
  27. if cls._editor is None:
  28. cls._editor = cls._SelectEditor()
  29. return cls._editor
  30. @classmethod
  31. def _SelectEditor(cls):
  32. e = os.getenv('GIT_EDITOR')
  33. if e:
  34. return e
  35. if cls.globalConfig:
  36. e = cls.globalConfig.GetString('core.editor')
  37. if e:
  38. return e
  39. e = os.getenv('VISUAL')
  40. if e:
  41. return e
  42. e = os.getenv('EDITOR')
  43. if e:
  44. return e
  45. if os.getenv('TERM') == 'dumb':
  46. print >>sys.stderr,\
  47. """No editor specified in GIT_EDITOR, core.editor, VISUAL or EDITOR.
  48. Tried to fall back to vi but terminal is dumb. Please configure at
  49. least one of these before using this command."""
  50. sys.exit(1)
  51. return 'vi'
  52. @classmethod
  53. def EditString(cls, data):
  54. """Opens an editor to edit the given content.
  55. Args:
  56. data : the text to edit
  57. Returns:
  58. new value of edited text; None if editing did not succeed
  59. """
  60. editor = cls._GetEditor()
  61. if editor == ':':
  62. return data
  63. fd, path = tempfile.mkstemp()
  64. try:
  65. os.write(fd, data)
  66. os.close(fd)
  67. fd = None
  68. if re.compile("^.*[$ \t'].*$").match(editor):
  69. args = [editor + ' "$@"']
  70. shell = True
  71. else:
  72. args = [editor]
  73. shell = False
  74. args.append(path)
  75. try:
  76. rc = subprocess.Popen(args, shell=shell).wait()
  77. except OSError, e:
  78. raise EditorError('editor failed, %s: %s %s'
  79. % (str(e), editor, path))
  80. if rc != 0:
  81. raise EditorError('editor failed with exit status %d: %s %s'
  82. % (rc, editor, path))
  83. fd2 = open(path)
  84. try:
  85. return fd2.read()
  86. finally:
  87. fd2.close()
  88. finally:
  89. if fd:
  90. os.close(fd)
  91. os.remove(path)