editor.py 2.8 KB

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