git_command.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 repo_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, msg=''):
  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. if msg:
  94. msg = ' for ' + msg
  95. print('fatal: git %s or later required%s' % (need, msg), file=sys.stderr)
  96. sys.exit(1)
  97. return False
  98. def _setenv(env, name, value):
  99. env[name] = value.encode()
  100. class GitCommand(object):
  101. def __init__(self,
  102. project,
  103. cmdv,
  104. bare = False,
  105. provide_stdin = False,
  106. capture_stdout = False,
  107. capture_stderr = False,
  108. disable_editor = False,
  109. ssh_proxy = False,
  110. cwd = None,
  111. gitdir = None):
  112. env = os.environ.copy()
  113. for key in [REPO_TRACE,
  114. GIT_DIR,
  115. 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
  116. 'GIT_OBJECT_DIRECTORY',
  117. 'GIT_WORK_TREE',
  118. 'GIT_GRAFT_FILE',
  119. 'GIT_INDEX_FILE']:
  120. if key in env:
  121. del env[key]
  122. # If we are not capturing std* then need to print it.
  123. self.tee = {'stdout': not capture_stdout, 'stderr': not capture_stderr}
  124. if disable_editor:
  125. _setenv(env, 'GIT_EDITOR', ':')
  126. if ssh_proxy:
  127. _setenv(env, 'REPO_SSH_SOCK', ssh_sock())
  128. _setenv(env, 'GIT_SSH', _ssh_proxy())
  129. _setenv(env, 'GIT_SSH_VARIANT', 'ssh')
  130. if 'http_proxy' in env and 'darwin' == sys.platform:
  131. s = "'http.proxy=%s'" % (env['http_proxy'],)
  132. p = env.get('GIT_CONFIG_PARAMETERS')
  133. if p is not None:
  134. s = p + ' ' + s
  135. _setenv(env, 'GIT_CONFIG_PARAMETERS', s)
  136. if 'GIT_ALLOW_PROTOCOL' not in env:
  137. _setenv(env, 'GIT_ALLOW_PROTOCOL',
  138. 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
  139. if project:
  140. if not cwd:
  141. cwd = project.worktree
  142. if not gitdir:
  143. gitdir = project.gitdir
  144. command = [GIT]
  145. if bare:
  146. if gitdir:
  147. _setenv(env, GIT_DIR, gitdir)
  148. cwd = None
  149. command.append(cmdv[0])
  150. # Need to use the --progress flag for fetch/clone so output will be
  151. # displayed as by default git only does progress output if stderr is a TTY.
  152. if sys.stderr.isatty() and cmdv[0] in ('fetch', 'clone'):
  153. if '--progress' not in cmdv and '--quiet' not in cmdv:
  154. command.append('--progress')
  155. command.extend(cmdv[1:])
  156. if provide_stdin:
  157. stdin = subprocess.PIPE
  158. else:
  159. stdin = None
  160. stdout = subprocess.PIPE
  161. stderr = subprocess.PIPE
  162. if IsTrace():
  163. global LAST_CWD
  164. global LAST_GITDIR
  165. dbg = ''
  166. if cwd and LAST_CWD != cwd:
  167. if LAST_GITDIR or LAST_CWD:
  168. dbg += '\n'
  169. dbg += ': cd %s\n' % cwd
  170. LAST_CWD = cwd
  171. if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
  172. if LAST_GITDIR or LAST_CWD:
  173. dbg += '\n'
  174. dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
  175. LAST_GITDIR = env[GIT_DIR]
  176. dbg += ': '
  177. dbg += ' '.join(command)
  178. if stdin == subprocess.PIPE:
  179. dbg += ' 0<|'
  180. if stdout == subprocess.PIPE:
  181. dbg += ' 1>|'
  182. if stderr == subprocess.PIPE:
  183. dbg += ' 2>|'
  184. Trace('%s', dbg)
  185. try:
  186. p = subprocess.Popen(command,
  187. cwd = cwd,
  188. env = env,
  189. stdin = stdin,
  190. stdout = stdout,
  191. stderr = stderr)
  192. except Exception as e:
  193. raise GitError('%s: %s' % (command[1], e))
  194. if ssh_proxy:
  195. _add_ssh_client(p)
  196. self.process = p
  197. self.stdin = p.stdin
  198. def Wait(self):
  199. try:
  200. p = self.process
  201. rc = self._CaptureOutput()
  202. finally:
  203. _remove_ssh_client(p)
  204. return rc
  205. def _CaptureOutput(self):
  206. p = self.process
  207. s_in = platform_utils.FileDescriptorStreams.create()
  208. s_in.add(p.stdout, sys.stdout, 'stdout')
  209. s_in.add(p.stderr, sys.stderr, 'stderr')
  210. self.stdout = ''
  211. self.stderr = ''
  212. while not s_in.is_done:
  213. in_ready = s_in.select()
  214. for s in in_ready:
  215. buf = s.read()
  216. if not buf:
  217. s_in.remove(s)
  218. continue
  219. if not hasattr(buf, 'encode'):
  220. buf = buf.decode()
  221. if s.std_name == 'stdout':
  222. self.stdout += buf
  223. else:
  224. self.stderr += buf
  225. if self.tee[s.std_name]:
  226. s.dest.write(buf)
  227. s.dest.flush()
  228. return p.wait()