blob: f8cb280cbc1d30965c3f059645ea62796a9d792f [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001# Copyright (C) 2008 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Mike Frysinger8e768ea2021-05-06 00:28:32 -040015import functools
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070016import os
Anders Björklund8e0fe192020-02-18 14:08:35 +010017import re
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070018import sys
19import subprocess
Shawn O. Pearcefb231612009-04-10 18:53:46 -070020import tempfile
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070021from signal import SIGTERM
Renaud Paquay2e702912016-11-01 11:23:38 -070022
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070023from error import GitError
Mike Frysinger71b0f312019-09-30 22:39:49 -040024from git_refs import HEAD
Renaud Paquay2e702912016-11-01 11:23:38 -070025import platform_utils
Mike Frysinger8a11f6f2019-08-27 00:26:15 -040026from repo_trace import REPO_TRACE, IsTrace, Trace
Conley Owensff0a3c82014-01-30 14:46:03 -080027from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070028
29GIT = 'git'
Mike Frysinger82caef62020-02-11 18:51:08 -050030# NB: These do not need to be kept in sync with the repo launcher script.
31# These may be much newer as it allows the repo launcher to roll between
32# different repo releases while source versions might require a newer git.
33#
34# The soft version is when we start warning users that the version is old and
35# we'll be dropping support for it. We'll refuse to work with versions older
36# than the hard version.
37#
38# git-1.7 is in (EOL) Ubuntu Precise. git-1.9 is in Ubuntu Trusty.
39MIN_GIT_VERSION_SOFT = (1, 9, 1)
40MIN_GIT_VERSION_HARD = (1, 7, 2)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070041GIT_DIR = 'GIT_DIR'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070042
43LAST_GITDIR = None
44LAST_CWD = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070045
Shawn O. Pearcefb231612009-04-10 18:53:46 -070046_ssh_proxy_path = None
47_ssh_sock_path = None
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070048_ssh_clients = []
Anders Björklund8e0fe192020-02-18 14:08:35 +010049
50
51def _run_ssh_version():
52 """run ssh -V to display the version number"""
53 return subprocess.check_output(['ssh', '-V'], stderr=subprocess.STDOUT).decode()
54
55
56def _parse_ssh_version(ver_str=None):
57 """parse a ssh version string into a tuple"""
58 if ver_str is None:
59 ver_str = _run_ssh_version()
60 m = re.match(r'^OpenSSH_([0-9.]+)(p[0-9]+)?\s', ver_str)
61 if m:
62 return tuple(int(x) for x in m.group(1).split('.'))
63 else:
64 return ()
65
66
Mike Frysinger8e768ea2021-05-06 00:28:32 -040067@functools.lru_cache(maxsize=None)
Anders Björklund8e0fe192020-02-18 14:08:35 +010068def ssh_version():
69 """return ssh version as a tuple"""
Mike Frysinger8e768ea2021-05-06 00:28:32 -040070 try:
71 return _parse_ssh_version()
72 except subprocess.CalledProcessError:
73 print('fatal: unable to detect ssh version', file=sys.stderr)
74 sys.exit(1)
Shawn O. Pearcefb231612009-04-10 18:53:46 -070075
David Pursehouse819827a2020-02-12 15:20:19 +090076
Nico Sallembien1c85f4e2010-04-27 14:35:27 -070077def ssh_sock(create=True):
Shawn O. Pearcefb231612009-04-10 18:53:46 -070078 global _ssh_sock_path
79 if _ssh_sock_path is None:
80 if not create:
81 return None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +020082 tmp_dir = '/tmp'
83 if not os.path.exists(tmp_dir):
84 tmp_dir = tempfile.gettempdir()
Anders Björklund8e0fe192020-02-18 14:08:35 +010085 if ssh_version() < (6, 7):
86 tokens = '%r@%h:%p'
87 else:
88 tokens = '%C' # hash of %l%h%p%r
Shawn O. Pearcefb231612009-04-10 18:53:46 -070089 _ssh_sock_path = os.path.join(
David Pursehouseabdf7502020-02-12 14:58:39 +090090 tempfile.mkdtemp('', 'ssh-', tmp_dir),
Anders Björklund8e0fe192020-02-18 14:08:35 +010091 'master-' + tokens)
Shawn O. Pearcefb231612009-04-10 18:53:46 -070092 return _ssh_sock_path
93
David Pursehouse819827a2020-02-12 15:20:19 +090094
Shawn O. Pearcefb231612009-04-10 18:53:46 -070095def _ssh_proxy():
96 global _ssh_proxy_path
97 if _ssh_proxy_path is None:
98 _ssh_proxy_path = os.path.join(
David Pursehouseabdf7502020-02-12 14:58:39 +090099 os.path.dirname(__file__),
100 'git_ssh')
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700101 return _ssh_proxy_path
102
David Pursehouse819827a2020-02-12 15:20:19 +0900103
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700104def _add_ssh_client(p):
105 _ssh_clients.append(p)
106
David Pursehouse819827a2020-02-12 15:20:19 +0900107
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700108def _remove_ssh_client(p):
109 try:
110 _ssh_clients.remove(p)
111 except ValueError:
112 pass
113
David Pursehouse819827a2020-02-12 15:20:19 +0900114
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700115def terminate_ssh_clients():
116 global _ssh_clients
117 for p in _ssh_clients:
118 try:
119 os.kill(p.pid, SIGTERM)
120 p.wait()
121 except OSError:
122 pass
123 _ssh_clients = []
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124
David Pursehouse819827a2020-02-12 15:20:19 +0900125
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700126class _GitCall(object):
Mike Frysinger8e768ea2021-05-06 00:28:32 -0400127 @functools.lru_cache(maxsize=None)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700128 def version_tuple(self):
Mike Frysinger8e768ea2021-05-06 00:28:32 -0400129 ret = Wrapper().ParseGitVersion()
130 if ret is None:
131 print('fatal: unable to detect git version', file=sys.stderr)
132 sys.exit(1)
133 return ret
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700134
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700135 def __getattr__(self, name):
David Pursehouse54a4e602020-02-12 14:31:05 +0900136 name = name.replace('_', '-')
David Pursehouse819827a2020-02-12 15:20:19 +0900137
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700138 def fun(*cmdv):
139 command = [name]
140 command.extend(cmdv)
141 return GitCommand(None, command).Wait() == 0
142 return fun
David Pursehouse819827a2020-02-12 15:20:19 +0900143
144
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700145git = _GitCall()
146
Mike Frysinger369814b2019-07-10 17:10:07 -0400147
Mike Frysinger71b0f312019-09-30 22:39:49 -0400148def RepoSourceVersion():
149 """Return the version of the repo.git tree."""
150 ver = getattr(RepoSourceVersion, 'version', None)
Mike Frysinger369814b2019-07-10 17:10:07 -0400151
Mike Frysinger71b0f312019-09-30 22:39:49 -0400152 # We avoid GitCommand so we don't run into circular deps -- GitCommand needs
153 # to initialize version info we provide.
154 if ver is None:
155 env = GitCommand._GetBasicEnv()
156
157 proj = os.path.dirname(os.path.abspath(__file__))
158 env[GIT_DIR] = os.path.join(proj, '.git')
Mike Frysingerf3079162021-02-16 02:38:21 -0500159 result = subprocess.run([GIT, 'describe', HEAD], stdout=subprocess.PIPE,
160 encoding='utf-8', env=env, check=False)
161 if result.returncode == 0:
162 ver = result.stdout.strip()
Mike Frysinger71b0f312019-09-30 22:39:49 -0400163 if ver.startswith('v'):
164 ver = ver[1:]
165 else:
166 ver = 'unknown'
167 setattr(RepoSourceVersion, 'version', ver)
168
169 return ver
170
171
172class UserAgent(object):
173 """Mange User-Agent settings when talking to external services
Mike Frysinger369814b2019-07-10 17:10:07 -0400174
175 We follow the style as documented here:
176 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
177 """
Mike Frysinger369814b2019-07-10 17:10:07 -0400178
Mike Frysinger71b0f312019-09-30 22:39:49 -0400179 _os = None
180 _repo_ua = None
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400181 _git_ua = None
Mike Frysinger369814b2019-07-10 17:10:07 -0400182
Mike Frysinger71b0f312019-09-30 22:39:49 -0400183 @property
184 def os(self):
185 """The operating system name."""
186 if self._os is None:
187 os_name = sys.platform
188 if os_name.lower().startswith('linux'):
189 os_name = 'Linux'
190 elif os_name == 'win32':
191 os_name = 'Win32'
192 elif os_name == 'cygwin':
193 os_name = 'Cygwin'
194 elif os_name == 'darwin':
195 os_name = 'Darwin'
196 self._os = os_name
Mike Frysinger369814b2019-07-10 17:10:07 -0400197
Mike Frysinger71b0f312019-09-30 22:39:49 -0400198 return self._os
Mike Frysinger369814b2019-07-10 17:10:07 -0400199
Mike Frysinger71b0f312019-09-30 22:39:49 -0400200 @property
201 def repo(self):
202 """The UA when connecting directly from repo."""
203 if self._repo_ua is None:
204 py_version = sys.version_info
205 self._repo_ua = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
206 RepoSourceVersion(),
207 self.os,
208 git.version_tuple().full,
209 py_version.major, py_version.minor, py_version.micro)
Mike Frysinger369814b2019-07-10 17:10:07 -0400210
Mike Frysinger71b0f312019-09-30 22:39:49 -0400211 return self._repo_ua
Mike Frysinger369814b2019-07-10 17:10:07 -0400212
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400213 @property
214 def git(self):
215 """The UA when running git."""
216 if self._git_ua is None:
217 self._git_ua = 'git/%s (%s) git-repo/%s' % (
218 git.version_tuple().full,
219 self.os,
220 RepoSourceVersion())
221
222 return self._git_ua
223
David Pursehouse819827a2020-02-12 15:20:19 +0900224
Mike Frysinger71b0f312019-09-30 22:39:49 -0400225user_agent = UserAgent()
Mike Frysinger369814b2019-07-10 17:10:07 -0400226
David Pursehouse819827a2020-02-12 15:20:19 +0900227
Xin Li745be2e2019-06-03 11:24:30 -0700228def git_require(min_version, fail=False, msg=''):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700229 git_version = git.version_tuple()
230 if min_version <= git_version:
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700231 return True
232 if fail:
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900233 need = '.'.join(map(str, min_version))
Xin Li745be2e2019-06-03 11:24:30 -0700234 if msg:
235 msg = ' for ' + msg
236 print('fatal: git %s or later required%s' % (need, msg), file=sys.stderr)
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700237 sys.exit(1)
238 return False
239
David Pursehouse819827a2020-02-12 15:20:19 +0900240
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700241class GitCommand(object):
242 def __init__(self,
243 project,
244 cmdv,
David Pursehousee5913ae2020-02-12 13:56:59 +0900245 bare=False,
Mike Frysingerf37b9822021-02-16 15:38:53 -0500246 input=None,
David Pursehousee5913ae2020-02-12 13:56:59 +0900247 capture_stdout=False,
248 capture_stderr=False,
Mike Frysinger31990f02020-02-17 01:35:18 -0500249 merge_output=False,
David Pursehousee5913ae2020-02-12 13:56:59 +0900250 disable_editor=False,
251 ssh_proxy=False,
252 cwd=None,
253 gitdir=None):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400254 env = self._GetBasicEnv()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700255
256 if disable_editor:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500257 env['GIT_EDITOR'] = ':'
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700258 if ssh_proxy:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500259 env['REPO_SSH_SOCK'] = ssh_sock()
260 env['GIT_SSH'] = _ssh_proxy()
261 env['GIT_SSH_VARIANT'] = 'ssh'
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700262 if 'http_proxy' in env and 'darwin' == sys.platform:
Shawn O. Pearce337aee02012-06-13 10:40:46 -0700263 s = "'http.proxy=%s'" % (env['http_proxy'],)
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700264 p = env.get('GIT_CONFIG_PARAMETERS')
265 if p is not None:
266 s = p + ' ' + s
Mike Frysinger56ce3462019-12-04 19:30:48 -0500267 env['GIT_CONFIG_PARAMETERS'] = s
Dan Willemsen466b8c42015-11-25 13:26:39 -0800268 if 'GIT_ALLOW_PROTOCOL' not in env:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500269 env['GIT_ALLOW_PROTOCOL'] = (
270 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
271 env['GIT_HTTP_USER_AGENT'] = user_agent.git
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700272
273 if project:
274 if not cwd:
275 cwd = project.worktree
276 if not gitdir:
277 gitdir = project.gitdir
278
279 command = [GIT]
280 if bare:
281 if gitdir:
Mike Frysinger4510be52021-02-27 13:06:27 -0500282 # Git on Windows wants its paths only using / for reliability.
283 if platform_utils.isWindows():
284 gitdir = gitdir.replace('\\', '/')
Mike Frysinger56ce3462019-12-04 19:30:48 -0500285 env[GIT_DIR] = gitdir
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700286 cwd = None
John L. Villalovos9c76f672015-03-16 20:49:10 -0700287 command.append(cmdv[0])
288 # Need to use the --progress flag for fetch/clone so output will be
289 # displayed as by default git only does progress output if stderr is a TTY.
290 if sys.stderr.isatty() and cmdv[0] in ('fetch', 'clone'):
291 if '--progress' not in cmdv and '--quiet' not in cmdv:
292 command.append('--progress')
293 command.extend(cmdv[1:])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700294
Mike Frysingerf37b9822021-02-16 15:38:53 -0500295 stdin = subprocess.PIPE if input else None
Mike Frysingerc87c1862021-02-16 17:18:12 -0500296 stdout = subprocess.PIPE if capture_stdout else None
297 stderr = (subprocess.STDOUT if merge_output else
298 (subprocess.PIPE if capture_stderr else None))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700299
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700300 if IsTrace():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700301 global LAST_CWD
302 global LAST_GITDIR
303
304 dbg = ''
305
306 if cwd and LAST_CWD != cwd:
307 if LAST_GITDIR or LAST_CWD:
308 dbg += '\n'
309 dbg += ': cd %s\n' % cwd
310 LAST_CWD = cwd
311
312 if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
313 if LAST_GITDIR or LAST_CWD:
314 dbg += '\n'
315 dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
316 LAST_GITDIR = env[GIT_DIR]
317
318 dbg += ': '
319 dbg += ' '.join(command)
320 if stdin == subprocess.PIPE:
321 dbg += ' 0<|'
322 if stdout == subprocess.PIPE:
323 dbg += ' 1>|'
324 if stderr == subprocess.PIPE:
325 dbg += ' 2>|'
Mike Frysinger31990f02020-02-17 01:35:18 -0500326 elif stderr == subprocess.STDOUT:
327 dbg += ' 2>&1'
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700328 Trace('%s', dbg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700329
330 try:
331 p = subprocess.Popen(command,
David Pursehousee5913ae2020-02-12 13:56:59 +0900332 cwd=cwd,
333 env=env,
Mike Frysingerc87c1862021-02-16 17:18:12 -0500334 encoding='utf-8',
335 errors='backslashreplace',
David Pursehousee5913ae2020-02-12 13:56:59 +0900336 stdin=stdin,
337 stdout=stdout,
338 stderr=stderr)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700339 except Exception as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700340 raise GitError('%s: %s' % (command[1], e))
341
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700342 if ssh_proxy:
343 _add_ssh_client(p)
344
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700345 self.process = p
Mike Frysingerf37b9822021-02-16 15:38:53 -0500346 if input:
347 if isinstance(input, str):
348 input = input.encode('utf-8')
349 p.stdin.write(input)
350 p.stdin.close()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700351
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500352 try:
Mike Frysingerc87c1862021-02-16 17:18:12 -0500353 self.stdout, self.stderr = p.communicate()
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500354 finally:
355 _remove_ssh_client(p)
Mike Frysingerc87c1862021-02-16 17:18:12 -0500356 self.rc = p.wait()
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500357
Mike Frysinger71b0f312019-09-30 22:39:49 -0400358 @staticmethod
359 def _GetBasicEnv():
360 """Return a basic env for running git under.
361
362 This is guaranteed to be side-effect free.
363 """
364 env = os.environ.copy()
365 for key in (REPO_TRACE,
366 GIT_DIR,
367 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
368 'GIT_OBJECT_DIRECTORY',
369 'GIT_WORK_TREE',
370 'GIT_GRAFT_FILE',
371 'GIT_INDEX_FILE'):
372 env.pop(key, None)
373 return env
374
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700375 def Wait(self):
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500376 return self.rc