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. class GitCommand(object):
  173. def __init__(self,
  174. project,
  175. cmdv,
  176. bare=False,
  177. provide_stdin=False,
  178. capture_stdout=False,
  179. capture_stderr=False,
  180. merge_output=False,
  181. disable_editor=False,
  182. ssh_proxy=False,
  183. cwd=None,
  184. gitdir=None):
  185. env = self._GetBasicEnv()
  186. # If we are not capturing std* then need to print it.
  187. self.tee = {'stdout': not capture_stdout, 'stderr': not capture_stderr}
  188. if disable_editor:
  189. env['GIT_EDITOR'] = ':'
  190. if ssh_proxy:
  191. env['REPO_SSH_SOCK'] = ssh_sock()
  192. env['GIT_SSH'] = _ssh_proxy()
  193. env['GIT_SSH_VARIANT'] = 'ssh'
  194. if 'http_proxy' in env and 'darwin' == sys.platform:
  195. s = "'http.proxy=%s'" % (env['http_proxy'],)
  196. p = env.get('GIT_CONFIG_PARAMETERS')
  197. if p is not None:
  198. s = p + ' ' + s
  199. env['GIT_CONFIG_PARAMETERS'] = s
  200. if 'GIT_ALLOW_PROTOCOL' not in env:
  201. env['GIT_ALLOW_PROTOCOL'] = (
  202. 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
  203. env['GIT_HTTP_USER_AGENT'] = user_agent.git
  204. if project:
  205. if not cwd:
  206. cwd = project.worktree
  207. if not gitdir:
  208. gitdir = project.gitdir
  209. command = [GIT]
  210. if bare:
  211. if gitdir:
  212. env[GIT_DIR] = gitdir
  213. cwd = None
  214. command.append(cmdv[0])
  215. # Need to use the --progress flag for fetch/clone so output will be
  216. # displayed as by default git only does progress output if stderr is a TTY.
  217. if sys.stderr.isatty() and cmdv[0] in ('fetch', 'clone'):
  218. if '--progress' not in cmdv and '--quiet' not in cmdv:
  219. command.append('--progress')
  220. command.extend(cmdv[1:])
  221. if provide_stdin:
  222. stdin = subprocess.PIPE
  223. else:
  224. stdin = None
  225. stdout = subprocess.PIPE
  226. stderr = subprocess.STDOUT if merge_output else subprocess.PIPE
  227. if IsTrace():
  228. global LAST_CWD
  229. global LAST_GITDIR
  230. dbg = ''
  231. if cwd and LAST_CWD != cwd:
  232. if LAST_GITDIR or LAST_CWD:
  233. dbg += '\n'
  234. dbg += ': cd %s\n' % cwd
  235. LAST_CWD = cwd
  236. if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
  237. if LAST_GITDIR or LAST_CWD:
  238. dbg += '\n'
  239. dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
  240. LAST_GITDIR = env[GIT_DIR]
  241. dbg += ': '
  242. dbg += ' '.join(command)
  243. if stdin == subprocess.PIPE:
  244. dbg += ' 0<|'
  245. if stdout == subprocess.PIPE:
  246. dbg += ' 1>|'
  247. if stderr == subprocess.PIPE:
  248. dbg += ' 2>|'
  249. elif stderr == subprocess.STDOUT:
  250. dbg += ' 2>&1'
  251. Trace('%s', dbg)
  252. try:
  253. p = subprocess.Popen(command,
  254. cwd=cwd,
  255. env=env,
  256. stdin=stdin,
  257. stdout=stdout,
  258. stderr=stderr)
  259. except Exception as e:
  260. raise GitError('%s: %s' % (command[1], e))
  261. if ssh_proxy:
  262. _add_ssh_client(p)
  263. self.process = p
  264. self.stdin = p.stdin
  265. @staticmethod
  266. def _GetBasicEnv():
  267. """Return a basic env for running git under.
  268. This is guaranteed to be side-effect free.
  269. """
  270. env = os.environ.copy()
  271. for key in (REPO_TRACE,
  272. GIT_DIR,
  273. 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
  274. 'GIT_OBJECT_DIRECTORY',
  275. 'GIT_WORK_TREE',
  276. 'GIT_GRAFT_FILE',
  277. 'GIT_INDEX_FILE'):
  278. env.pop(key, None)
  279. return env
  280. def Wait(self):
  281. try:
  282. p = self.process
  283. rc = self._CaptureOutput()
  284. finally:
  285. _remove_ssh_client(p)
  286. return rc
  287. def _CaptureOutput(self):
  288. p = self.process
  289. s_in = platform_utils.FileDescriptorStreams.create()
  290. s_in.add(p.stdout, sys.stdout, 'stdout')
  291. if p.stderr is not None:
  292. s_in.add(p.stderr, sys.stderr, 'stderr')
  293. self.stdout = ''
  294. self.stderr = ''
  295. while not s_in.is_done:
  296. in_ready = s_in.select()
  297. for s in in_ready:
  298. buf = s.read()
  299. if not buf:
  300. s_in.remove(s)
  301. continue
  302. if not hasattr(buf, 'encode'):
  303. buf = buf.decode()
  304. if s.std_name == 'stdout':
  305. self.stdout += buf
  306. else:
  307. self.stderr += buf
  308. if self.tee[s.std_name]:
  309. s.dest.write(buf)
  310. s.dest.flush()
  311. return p.wait()