editor.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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; None if editing did not succeed
  62. """
  63. editor = cls._GetEditor()
  64. if editor == ':':
  65. return data
  66. fd, path = tempfile.mkstemp()
  67. try:
  68. os.write(fd, data)
  69. os.close(fd)
  70. fd = None
  71. if platform_utils.isWindows():
  72. # Split on spaces, respecting quoted strings
  73. import shlex
  74. args = shlex.split(editor)
  75. shell = False
  76. elif re.compile("^.*[$ \t'].*$").match(editor):
  77. args = [editor + ' "$@"', 'sh']
  78. shell = True
  79. else:
  80. args = [editor]
  81. shell = False
  82. args.append(path)
  83. try:
  84. rc = subprocess.Popen(args, shell=shell).wait()
  85. except OSError as e:
  86. raise EditorError('editor failed, %s: %s %s'
  87. % (str(e), editor, path))
  88. if rc != 0:
  89. raise EditorError('editor failed with exit status %d: %s %s'
  90. % (rc, editor, path))
  91. with open(path) as fd2:
  92. return fd2.read()
  93. finally:
  94. if fd:
  95. os.close(fd)
  96. platform_utils.remove(path)