editor.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. # Copyright (C) 2008 The Android Open Source Project
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import re
  16. import sys
  17. import subprocess
  18. import tempfile
  19. from error import EditorError
  20. import platform_utils
  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(
  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.""", file=sys.stderr)
  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.
  59. Raises:
  60. EditorError: The editor failed to run.
  61. """
  62. editor = cls._GetEditor()
  63. if editor == ':':
  64. return data
  65. fd, path = tempfile.mkstemp()
  66. try:
  67. os.write(fd, data.encode('utf-8'))
  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. with open(path, mode='rb') as fd2:
  91. return fd2.read().decode('utf-8')
  92. finally:
  93. if fd:
  94. os.close(fd)
  95. platform_utils.remove(path)