git_command.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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 sys
  19. import subprocess
  20. import tempfile
  21. from signal import SIGTERM
  22. from error import GitError
  23. import platform_utils
  24. from trace import REPO_TRACE, IsTrace, Trace
  25. from wrapper import Wrapper
  26. GIT = 'git'
  27. MIN_GIT_VERSION = (1, 5, 4)
  28. GIT_DIR = 'GIT_DIR'
  29. LAST_GITDIR = None
  30. LAST_CWD = None
  31. _ssh_proxy_path = None
  32. _ssh_sock_path = None
  33. _ssh_clients = []
  34. def ssh_sock(create=True):
  35. global _ssh_sock_path
  36. if _ssh_sock_path is None:
  37. if not create:
  38. return None
  39. tmp_dir = '/tmp'
  40. if not os.path.exists(tmp_dir):
  41. tmp_dir = tempfile.gettempdir()
  42. _ssh_sock_path = os.path.join(
  43. tempfile.mkdtemp('', 'ssh-', tmp_dir),
  44. 'master-%r@%h:%p')
  45. return _ssh_sock_path
  46. def _ssh_proxy():
  47. global _ssh_proxy_path
  48. if _ssh_proxy_path is None:
  49. _ssh_proxy_path = os.path.join(
  50. os.path.dirname(__file__),
  51. 'git_ssh')
  52. return _ssh_proxy_path
  53. def _add_ssh_client(p):
  54. _ssh_clients.append(p)
  55. def _remove_ssh_client(p):
  56. try:
  57. _ssh_clients.remove(p)
  58. except ValueError:
  59. pass
  60. def terminate_ssh_clients():
  61. global _ssh_clients
  62. for p in _ssh_clients:
  63. try:
  64. os.kill(p.pid, SIGTERM)
  65. p.wait()
  66. except OSError:
  67. pass
  68. _ssh_clients = []
  69. _git_version = None
  70. class _GitCall(object):
  71. def version_tuple(self):
  72. global _git_version
  73. if _git_version is None:
  74. _git_version = Wrapper().ParseGitVersion()
  75. if _git_version is None:
  76. print('fatal: unable to detect git version', file=sys.stderr)
  77. sys.exit(1)
  78. return _git_version
  79. def __getattr__(self, name):
  80. name = name.replace('_','-')
  81. def fun(*cmdv):
  82. command = [name]
  83. command.extend(cmdv)
  84. return GitCommand(None, command).Wait() == 0
  85. return fun
  86. git = _GitCall()
  87. def git_require(min_version, fail=False):
  88. git_version = git.version_tuple()
  89. if min_version <= git_version:
  90. return True
  91. if fail:
  92. need = '.'.join(map(str, min_version))
  93. print('fatal: git %s or later required' % need, file=sys.stderr)
  94. sys.exit(1)
  95. return False
  96. def _setenv(env, name, value):
  97. env[name] = value.encode()
  98. class GitCommand(object):
  99. def __init__(self,
  100. project,
  101. cmdv,
  102. bare = False,
  103. provide_stdin = False,
  104. capture_stdout = False,
  105. capture_stderr = False,
  106. disable_editor = False,
  107. ssh_proxy = False,
  108. cwd = None,
  109. gitdir = None):
  110. env = os.environ.copy()
  111. for key in [REPO_TRACE,
  112. GIT_DIR,
  113. 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
  114. 'GIT_OBJECT_DIRECTORY',
  115. 'GIT_WORK_TREE',
  116. 'GIT_GRAFT_FILE',
  117. 'GIT_INDEX_FILE']:
  118. if key in env:
  119. del env[key]
  120. # If we are not capturing std* then need to print it.
  121. self.tee = {'stdout': not capture_stdout, 'stderr': not capture_stderr}
  122. if disable_editor:
  123. _setenv(env, 'GIT_EDITOR', ':')
  124. if ssh_proxy:
  125. _setenv(env, 'REPO_SSH_SOCK', ssh_sock())
  126. _setenv(env, 'GIT_SSH', _ssh_proxy())
  127. _setenv(env, 'GIT_SSH_VARIANT', 'ssh')
  128. if 'http_proxy' in env and 'darwin' == sys.platform:
  129. s = "'http.proxy=%s'" % (env['http_proxy'],)
  130. p = env.get('GIT_CONFIG_PARAMETERS')
  131. if p is not None:
  132. s = p + ' ' + s
  133. _setenv(env, 'GIT_CONFIG_PARAMETERS', s)
  134. if 'GIT_ALLOW_PROTOCOL' not in env:
  135. _setenv(env, 'GIT_ALLOW_PROTOCOL',
  136. 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
  137. if project:
  138. if not cwd:
  139. cwd = project.worktree
  140. if not gitdir:
  141. gitdir = project.gitdir
  142. command = [GIT]
  143. if bare:
  144. if gitdir:
  145. _setenv(env, GIT_DIR, gitdir)
  146. cwd = None
  147. command.append(cmdv[0])
  148. # Need to use the --progress flag for fetch/clone so output will be
  149. # displayed as by default git only does progress output if stderr is a TTY.
  150. if sys.stderr.isatty() and cmdv[0] in ('fetch', 'clone'):
  151. if '--progress' not in cmdv and '--quiet' not in cmdv:
  152. command.append('--progress')
  153. command.extend(cmdv[1:])
  154. if provide_stdin:
  155. stdin = subprocess.PIPE
  156. else:
  157. stdin = None
  158. stdout = subprocess.PIPE
  159. stderr = subprocess.PIPE
  160. if IsTrace():
  161. global LAST_CWD
  162. global LAST_GITDIR
  163. dbg = ''
  164. if cwd and LAST_CWD != cwd:
  165. if LAST_GITDIR or LAST_CWD:
  166. dbg += '\n'
  167. dbg += ': cd %s\n' % cwd
  168. LAST_CWD = cwd
  169. if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
  170. if LAST_GITDIR or LAST_CWD:
  171. dbg += '\n'
  172. dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
  173. LAST_GITDIR = env[GIT_DIR]
  174. dbg += ': '
  175. dbg += ' '.join(command)
  176. if stdin == subprocess.PIPE:
  177. dbg += ' 0<|'
  178. if stdout == subprocess.PIPE:
  179. dbg += ' 1>|'
  180. if stderr == subprocess.PIPE:
  181. dbg += ' 2>|'
  182. Trace('%s', dbg)
  183. try:
  184. p = subprocess.Popen(command,
  185. cwd = cwd,
  186. env = env,
  187. stdin = stdin,
  188. stdout = stdout,
  189. stderr = stderr)
  190. except Exception as e:
  191. raise GitError('%s: %s' % (command[1], e))
  192. if ssh_proxy:
  193. _add_ssh_client(p)
  194. self.process = p
  195. self.stdin = p.stdin
  196. def Wait(self):
  197. try:
  198. p = self.process
  199. rc = self._CaptureOutput()
  200. finally:
  201. _remove_ssh_client(p)
  202. return rc
  203. def _CaptureOutput(self):
  204. p = self.process
  205. s_in = platform_utils.FileDescriptorStreams.create()
  206. s_in.add(p.stdout, sys.stdout, 'stdout')
  207. s_in.add(p.stderr, sys.stderr, 'stderr')
  208. self.stdout = ''
  209. self.stderr = ''
  210. while not s_in.is_done:
  211. in_ready = s_in.select()
  212. for s in in_ready:
  213. buf = s.read()
  214. if not buf:
  215. s_in.remove(s)
  216. continue
  217. if not hasattr(buf, 'encode'):
  218. buf = buf.decode()
  219. if s.std_name == 'stdout':
  220. self.stdout += buf
  221. else:
  222. self.stderr += buf
  223. if self.tee[s.std_name]:
  224. s.dest.write(buf)
  225. s.dest.flush()
  226. return p.wait()