editor.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. # -*- coding:utf-8 -*-
  2. #
  3. # Copyright (C) 2008 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from __future__ import print_function
  17. import os
  18. import re
  19. import sys
  20. import subprocess
  21. import tempfile
  22. from error import EditorError
  23. import platform_utils
  24. class Editor(object):
  25. """Manages the user's preferred text editor."""
  26. _editor = None
  27. globalConfig = None
  28. @classmethod
  29. def _GetEditor(cls):
  30. if cls._editor is None:
  31. cls._editor = cls._SelectEditor()
  32. return cls._editor
  33. @classmethod
  34. def _SelectEditor(cls):
  35. e = os.getenv('GIT_EDITOR')
  36. if e:
  37. return e
  38. if cls.globalConfig:
  39. e = cls.globalConfig.GetString('core.editor')
  40. if e:
  41. return e
  42. e = os.getenv('VISUAL')
  43. if e:
  44. return e
  45. e = os.getenv('EDITOR')
  46. if e:
  47. return e
  48. if os.getenv('TERM') == 'dumb':
  49. print(
  50. """No editor specified in GIT_EDITOR, core.editor, VISUAL or EDITOR.
  51. Tried to fall back to vi but terminal is dumb. Please configure at
  52. least one of these before using this command.""", file=sys.stderr)
  53. sys.exit(1)
  54. return 'vi'
  55. @classmethod
  56. def EditString(cls, data):
  57. """Opens an editor to edit the given content.
  58. Args:
  59. data: The text to edit.
  60. Returns:
  61. New value of edited text.
  62. Raises:
  63. EditorError: The editor failed to run.
  64. """
  65. editor = cls._GetEditor()
  66. if editor == ':':
  67. return data
  68. fd, path = tempfile.mkstemp()
  69. try:
  70. os.write(fd, data.encode('utf-8'))
  71. os.close(fd)
  72. fd = None
  73. if platform_utils.isWindows():
  74. # Split on spaces, respecting quoted strings
  75. import shlex
  76. args = shlex.split(editor)
  77. shell = False
  78. elif re.compile("^.*[$ \t'].*$").match(editor):
  79. args = [editor + ' "$@"', 'sh']
  80. shell = True
  81. else:
  82. args = [editor]
  83. shell = False
  84. args.append(path)
  85. try:
  86. rc = subprocess.Popen(args, shell=shell).wait()
  87. except OSError as e:
  88. raise EditorError('editor failed, %s: %s %s'
  89. % (str(e), editor, path))
  90. if rc != 0:
  91. raise EditorError('editor failed with exit status %d: %s %s'
  92. % (rc, editor, path))
  93. with open(path, mode='rb') as fd2:
  94. return fd2.read().decode('utf-8')
  95. finally:
  96. if fd:
  97. os.close(fd)
  98. platform_utils.remove(path)