git_command.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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 sys
  18. import subprocess
  19. import tempfile
  20. from signal import SIGTERM
  21. from error import GitError
  22. from trace import REPO_TRACE, IsTrace, Trace
  23. GIT = 'git'
  24. MIN_GIT_VERSION = (1, 5, 4)
  25. GIT_DIR = 'GIT_DIR'
  26. LAST_GITDIR = None
  27. LAST_CWD = None
  28. _ssh_proxy_path = None
  29. _ssh_sock_path = None
  30. _ssh_clients = []
  31. def ssh_sock(create=True):
  32. global _ssh_sock_path
  33. if _ssh_sock_path is None:
  34. if not create:
  35. return None
  36. tmp_dir = '/tmp'
  37. if not os.path.exists(tmp_dir):
  38. tmp_dir = tempfile.gettempdir()
  39. _ssh_sock_path = os.path.join(
  40. tempfile.mkdtemp('', 'ssh-', tmp_dir),
  41. 'master-%r@%h:%p')
  42. return _ssh_sock_path
  43. def _ssh_proxy():
  44. global _ssh_proxy_path
  45. if _ssh_proxy_path is None:
  46. _ssh_proxy_path = os.path.join(
  47. os.path.dirname(__file__),
  48. 'git_ssh')
  49. return _ssh_proxy_path
  50. def _add_ssh_client(p):
  51. _ssh_clients.append(p)
  52. def _remove_ssh_client(p):
  53. try:
  54. _ssh_clients.remove(p)
  55. except ValueError:
  56. pass
  57. def terminate_ssh_clients():
  58. global _ssh_clients
  59. for p in _ssh_clients:
  60. try:
  61. os.kill(p.pid, SIGTERM)
  62. p.wait()
  63. except OSError:
  64. pass
  65. _ssh_clients = []
  66. _git_version = None
  67. class _GitCall(object):
  68. def version(self):
  69. p = GitCommand(None, ['--version'], capture_stdout=True)
  70. if p.Wait() == 0:
  71. return p.stdout
  72. return None
  73. def version_tuple(self):
  74. global _git_version
  75. if _git_version is None:
  76. ver_str = git.version().decode('utf-8')
  77. if ver_str.startswith('git version '):
  78. _git_version = tuple(
  79. map(int,
  80. ver_str[len('git version '):].strip().split('-')[0].split('.')[0:3]
  81. ))
  82. else:
  83. print('fatal: "%s" unsupported' % ver_str, file=sys.stderr)
  84. sys.exit(1)
  85. return _git_version
  86. def __getattr__(self, name):
  87. name = name.replace('_','-')
  88. def fun(*cmdv):
  89. command = [name]
  90. command.extend(cmdv)
  91. return GitCommand(None, command).Wait() == 0
  92. return fun
  93. git = _GitCall()
  94. def git_require(min_version, fail=False):
  95. git_version = git.version_tuple()
  96. if min_version <= git_version:
  97. return True
  98. if fail:
  99. need = '.'.join(map(str, min_version))
  100. print('fatal: git %s or later required' % need, file=sys.stderr)
  101. sys.exit(1)
  102. return False
  103. def _setenv(env, name, value):
  104. env[name] = value.encode()
  105. class GitCommand(object):
  106. def __init__(self,
  107. project,
  108. cmdv,
  109. bare = False,
  110. provide_stdin = False,
  111. capture_stdout = False,
  112. capture_stderr = False,
  113. disable_editor = False,
  114. ssh_proxy = False,
  115. cwd = None,
  116. gitdir = None):
  117. env = os.environ.copy()
  118. for key in [REPO_TRACE,
  119. GIT_DIR,
  120. 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
  121. 'GIT_OBJECT_DIRECTORY',
  122. 'GIT_WORK_TREE',
  123. 'GIT_GRAFT_FILE',
  124. 'GIT_INDEX_FILE']:
  125. if key in env:
  126. del env[key]
  127. if disable_editor:
  128. _setenv(env, 'GIT_EDITOR', ':')
  129. if ssh_proxy:
  130. _setenv(env, 'REPO_SSH_SOCK', ssh_sock())
  131. _setenv(env, 'GIT_SSH', _ssh_proxy())
  132. if 'http_proxy' in env and 'darwin' == sys.platform:
  133. s = "'http.proxy=%s'" % (env['http_proxy'],)
  134. p = env.get('GIT_CONFIG_PARAMETERS')
  135. if p is not None:
  136. s = p + ' ' + s
  137. _setenv(env, 'GIT_CONFIG_PARAMETERS', s)
  138. if project:
  139. if not cwd:
  140. cwd = project.worktree
  141. if not gitdir:
  142. gitdir = project.gitdir
  143. command = [GIT]
  144. if bare:
  145. if gitdir:
  146. _setenv(env, GIT_DIR, gitdir)
  147. cwd = None
  148. command.extend(cmdv)
  149. if provide_stdin:
  150. stdin = subprocess.PIPE
  151. else:
  152. stdin = None
  153. if capture_stdout:
  154. stdout = subprocess.PIPE
  155. else:
  156. stdout = None
  157. if capture_stderr:
  158. stderr = subprocess.PIPE
  159. else:
  160. stderr = None
  161. if IsTrace():
  162. global LAST_CWD
  163. global LAST_GITDIR
  164. dbg = ''
  165. if cwd and LAST_CWD != cwd:
  166. if LAST_GITDIR or LAST_CWD:
  167. dbg += '\n'
  168. dbg += ': cd %s\n' % cwd
  169. LAST_CWD = cwd
  170. if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
  171. if LAST_GITDIR or LAST_CWD:
  172. dbg += '\n'
  173. dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
  174. LAST_GITDIR = env[GIT_DIR]
  175. dbg += ': '
  176. dbg += ' '.join(command)
  177. if stdin == subprocess.PIPE:
  178. dbg += ' 0<|'
  179. if stdout == subprocess.PIPE:
  180. dbg += ' 1>|'
  181. if stderr == subprocess.PIPE:
  182. dbg += ' 2>|'
  183. Trace('%s', dbg)
  184. try:
  185. p = subprocess.Popen(command,
  186. cwd = cwd,
  187. env = env,
  188. stdin = stdin,
  189. stdout = stdout,
  190. stderr = stderr)
  191. except Exception as e:
  192. raise GitError('%s: %s' % (command[1], e))
  193. if ssh_proxy:
  194. _add_ssh_client(p)
  195. self.process = p
  196. self.stdin = p.stdin
  197. def Wait(self):
  198. try:
  199. p = self.process
  200. (self.stdout, self.stderr) = p.communicate()
  201. rc = p.returncode
  202. finally:
  203. _remove_ssh_client(p)
  204. return rc