editor.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 sys
  17. import subprocess
  18. import tempfile
  19. from error import EditorError
  20. class Editor(object):
  21. """Manages the user's preferred text editor."""
  22. _editor = None
  23. globalConfig = None
  24. @classmethod
  25. def _GetEditor(cls):
  26. if cls._editor is None:
  27. cls._editor = cls._SelectEditor()
  28. return cls._editor
  29. @classmethod
  30. def _SelectEditor(cls):
  31. e = os.getenv('GIT_EDITOR')
  32. if e:
  33. return e
  34. e = cls.globalConfig.GetString('core.editor')
  35. if e:
  36. return e
  37. e = os.getenv('VISUAL')
  38. if e:
  39. return e
  40. e = os.getenv('EDITOR')
  41. if e:
  42. return e
  43. if os.getenv('TERM') == 'dumb':
  44. print >>sys.stderr,\
  45. """No editor specified in GIT_EDITOR, core.editor, VISUAL or EDITOR.
  46. Tried to fall back to vi but terminal is dumb. Please configure at
  47. least one of these before using this command."""
  48. sys.exit(1)
  49. return 'vi'
  50. @classmethod
  51. def EditString(cls, data):
  52. """Opens an editor to edit the given content.
  53. Args:
  54. data : the text to edit
  55. Returns:
  56. new value of edited text; None if editing did not succeed
  57. """
  58. editor = cls._GetEditor().split()
  59. fd, path = tempfile.mkstemp()
  60. try:
  61. os.write(fd, data)
  62. os.close(fd)
  63. fd = None
  64. if subprocess.Popen(editor + [path]).wait() != 0:
  65. raise EditorError()
  66. fd = open(path)
  67. try:
  68. return read()
  69. finally:
  70. fd.close()
  71. finally:
  72. if fd:
  73. os.close(fd)
  74. os.remove(path)