git_command.py 9.6 KB

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