git_command.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. from git_refs import HEAD
  24. import platform_utils
  25. from repo_trace import REPO_TRACE, IsTrace, Trace
  26. from wrapper import Wrapper
  27. GIT = 'git'
  28. # Should keep in sync with the "repo" launcher file.
  29. MIN_GIT_VERSION = (2, 10, 2)
  30. GIT_DIR = 'GIT_DIR'
  31. LAST_GITDIR = None
  32. LAST_CWD = None
  33. _ssh_proxy_path = None
  34. _ssh_sock_path = None
  35. _ssh_clients = []
  36. def ssh_sock(create=True):
  37. global _ssh_sock_path
  38. if _ssh_sock_path is None:
  39. if not create:
  40. return None
  41. tmp_dir = '/tmp'
  42. if not os.path.exists(tmp_dir):
  43. tmp_dir = tempfile.gettempdir()
  44. _ssh_sock_path = os.path.join(
  45. tempfile.mkdtemp('', 'ssh-', tmp_dir),
  46. 'master-%r@%h:%p')
  47. return _ssh_sock_path
  48. def _ssh_proxy():
  49. global _ssh_proxy_path
  50. if _ssh_proxy_path is None:
  51. _ssh_proxy_path = os.path.join(
  52. os.path.dirname(__file__),
  53. 'git_ssh')
  54. return _ssh_proxy_path
  55. def _add_ssh_client(p):
  56. _ssh_clients.append(p)
  57. def _remove_ssh_client(p):
  58. try:
  59. _ssh_clients.remove(p)
  60. except ValueError:
  61. pass
  62. def terminate_ssh_clients():
  63. global _ssh_clients
  64. for p in _ssh_clients:
  65. try:
  66. os.kill(p.pid, SIGTERM)
  67. p.wait()
  68. except OSError:
  69. pass
  70. _ssh_clients = []
  71. _git_version = None
  72. class _GitCall(object):
  73. def version_tuple(self):
  74. global _git_version
  75. if _git_version is None:
  76. _git_version = Wrapper().ParseGitVersion()
  77. if _git_version is None:
  78. print('fatal: unable to detect git version', file=sys.stderr)
  79. sys.exit(1)
  80. return _git_version
  81. def __getattr__(self, name):
  82. name = name.replace('_','-')
  83. def fun(*cmdv):
  84. command = [name]
  85. command.extend(cmdv)
  86. return GitCommand(None, command).Wait() == 0
  87. return fun
  88. git = _GitCall()
  89. def RepoSourceVersion():
  90. """Return the version of the repo.git tree."""
  91. ver = getattr(RepoSourceVersion, 'version', None)
  92. # We avoid GitCommand so we don't run into circular deps -- GitCommand needs
  93. # to initialize version info we provide.
  94. if ver is None:
  95. env = GitCommand._GetBasicEnv()
  96. proj = os.path.dirname(os.path.abspath(__file__))
  97. env[GIT_DIR] = os.path.join(proj, '.git')
  98. p = subprocess.Popen([GIT, 'describe', HEAD], stdout=subprocess.PIPE,
  99. env=env)
  100. if p.wait() == 0:
  101. ver = p.stdout.read().strip().decode('utf-8')
  102. if ver.startswith('v'):
  103. ver = ver[1:]
  104. else:
  105. ver = 'unknown'
  106. setattr(RepoSourceVersion, 'version', ver)
  107. return ver
  108. class UserAgent(object):
  109. """Mange User-Agent settings when talking to external services
  110. We follow the style as documented here:
  111. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
  112. """
  113. _os = None
  114. _repo_ua = None
  115. _git_ua = None
  116. @property
  117. def os(self):
  118. """The operating system name."""
  119. if self._os is None:
  120. os_name = sys.platform
  121. if os_name.lower().startswith('linux'):
  122. os_name = 'Linux'
  123. elif os_name == 'win32':
  124. os_name = 'Win32'
  125. elif os_name == 'cygwin':
  126. os_name = 'Cygwin'
  127. elif os_name == 'darwin':
  128. os_name = 'Darwin'
  129. self._os = os_name
  130. return self._os
  131. @property
  132. def repo(self):
  133. """The UA when connecting directly from repo."""
  134. if self._repo_ua is None:
  135. py_version = sys.version_info
  136. self._repo_ua = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
  137. RepoSourceVersion(),
  138. self.os,
  139. git.version_tuple().full,
  140. py_version.major, py_version.minor, py_version.micro)
  141. return self._repo_ua
  142. @property
  143. def git(self):
  144. """The UA when running git."""
  145. if self._git_ua is None:
  146. self._git_ua = 'git/%s (%s) git-repo/%s' % (
  147. git.version_tuple().full,
  148. self.os,
  149. RepoSourceVersion())
  150. return self._git_ua
  151. user_agent = UserAgent()
  152. def git_require(min_version, fail=False, msg=''):
  153. git_version = git.version_tuple()
  154. if min_version <= git_version:
  155. return True
  156. if fail:
  157. need = '.'.join(map(str, min_version))
  158. if msg:
  159. msg = ' for ' + msg
  160. print('fatal: git %s or later required%s' % (need, msg), file=sys.stderr)
  161. sys.exit(1)
  162. return False
  163. def _setenv(env, name, value):
  164. env[name] = value.encode()
  165. class GitCommand(object):
  166. def __init__(self,
  167. project,
  168. cmdv,
  169. bare = False,
  170. provide_stdin = False,
  171. capture_stdout = False,
  172. capture_stderr = False,
  173. disable_editor = False,
  174. ssh_proxy = False,
  175. cwd = None,
  176. gitdir = None):
  177. env = self._GetBasicEnv()
  178. # If we are not capturing std* then need to print it.
  179. self.tee = {'stdout': not capture_stdout, 'stderr': not capture_stderr}
  180. if disable_editor:
  181. _setenv(env, 'GIT_EDITOR', ':')
  182. if ssh_proxy:
  183. _setenv(env, 'REPO_SSH_SOCK', ssh_sock())
  184. _setenv(env, 'GIT_SSH', _ssh_proxy())
  185. _setenv(env, 'GIT_SSH_VARIANT', 'ssh')
  186. if 'http_proxy' in env and 'darwin' == sys.platform:
  187. s = "'http.proxy=%s'" % (env['http_proxy'],)
  188. p = env.get('GIT_CONFIG_PARAMETERS')
  189. if p is not None:
  190. s = p + ' ' + s
  191. _setenv(env, 'GIT_CONFIG_PARAMETERS', s)
  192. if 'GIT_ALLOW_PROTOCOL' not in env:
  193. _setenv(env, 'GIT_ALLOW_PROTOCOL',
  194. 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
  195. _setenv(env, 'GIT_HTTP_USER_AGENT', user_agent.git)
  196. if project:
  197. if not cwd:
  198. cwd = project.worktree
  199. if not gitdir:
  200. gitdir = project.gitdir
  201. command = [GIT]
  202. if bare:
  203. if gitdir:
  204. _setenv(env, GIT_DIR, gitdir)
  205. cwd = None
  206. command.append(cmdv[0])
  207. # Need to use the --progress flag for fetch/clone so output will be
  208. # displayed as by default git only does progress output if stderr is a TTY.
  209. if sys.stderr.isatty() and cmdv[0] in ('fetch', 'clone'):
  210. if '--progress' not in cmdv and '--quiet' not in cmdv:
  211. command.append('--progress')
  212. command.extend(cmdv[1:])
  213. if provide_stdin:
  214. stdin = subprocess.PIPE
  215. else:
  216. stdin = None
  217. stdout = subprocess.PIPE
  218. stderr = subprocess.PIPE
  219. if IsTrace():
  220. global LAST_CWD
  221. global LAST_GITDIR
  222. dbg = ''
  223. if cwd and LAST_CWD != cwd:
  224. if LAST_GITDIR or LAST_CWD:
  225. dbg += '\n'
  226. dbg += ': cd %s\n' % cwd
  227. LAST_CWD = cwd
  228. if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
  229. if LAST_GITDIR or LAST_CWD:
  230. dbg += '\n'
  231. dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
  232. LAST_GITDIR = env[GIT_DIR]
  233. dbg += ': '
  234. dbg += ' '.join(command)
  235. if stdin == subprocess.PIPE:
  236. dbg += ' 0<|'
  237. if stdout == subprocess.PIPE:
  238. dbg += ' 1>|'
  239. if stderr == subprocess.PIPE:
  240. dbg += ' 2>|'
  241. Trace('%s', dbg)
  242. try:
  243. p = subprocess.Popen(command,
  244. cwd = cwd,
  245. env = env,
  246. stdin = stdin,
  247. stdout = stdout,
  248. stderr = stderr)
  249. except Exception as e:
  250. raise GitError('%s: %s' % (command[1], e))
  251. if ssh_proxy:
  252. _add_ssh_client(p)
  253. self.process = p
  254. self.stdin = p.stdin
  255. @staticmethod
  256. def _GetBasicEnv():
  257. """Return a basic env for running git under.
  258. This is guaranteed to be side-effect free.
  259. """
  260. env = os.environ.copy()
  261. for key in (REPO_TRACE,
  262. GIT_DIR,
  263. 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
  264. 'GIT_OBJECT_DIRECTORY',
  265. 'GIT_WORK_TREE',
  266. 'GIT_GRAFT_FILE',
  267. 'GIT_INDEX_FILE'):
  268. env.pop(key, None)
  269. return env
  270. def Wait(self):
  271. try:
  272. p = self.process
  273. rc = self._CaptureOutput()
  274. finally:
  275. _remove_ssh_client(p)
  276. return rc
  277. def _CaptureOutput(self):
  278. p = self.process
  279. s_in = platform_utils.FileDescriptorStreams.create()
  280. s_in.add(p.stdout, sys.stdout, 'stdout')
  281. s_in.add(p.stderr, sys.stderr, 'stderr')
  282. self.stdout = ''
  283. self.stderr = ''
  284. while not s_in.is_done:
  285. in_ready = s_in.select()
  286. for s in in_ready:
  287. buf = s.read()
  288. if not buf:
  289. s_in.remove(s)
  290. continue
  291. if not hasattr(buf, 'encode'):
  292. buf = buf.decode()
  293. if s.std_name == 'stdout':
  294. self.stdout += buf
  295. else:
  296. self.stderr += buf
  297. if self.tee[s.std_name]:
  298. s.dest.write(buf)
  299. s.dest.flush()
  300. return p.wait()