blob: 19100fa96a17b60d113dc69f26e8fc6b12578eea [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
17import sys
18import subprocess
Renaud Paquay2e702912016-11-01 11:23:38 -070019
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070020from error import GitError
Mike Frysinger71b0f312019-09-30 22:39:49 -040021from git_refs import HEAD
Renaud Paquay2e702912016-11-01 11:23:38 -070022import platform_utils
Mike Frysinger8a11f6f2019-08-27 00:26:15 -040023from repo_trace import REPO_TRACE, IsTrace, Trace
Conley Owensff0a3c82014-01-30 14:46:03 -080024from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070025
26GIT = 'git'
Mike Frysinger82caef62020-02-11 18:51:08 -050027# NB: These do not need to be kept in sync with the repo launcher script.
28# These may be much newer as it allows the repo launcher to roll between
29# different repo releases while source versions might require a newer git.
30#
31# The soft version is when we start warning users that the version is old and
32# we'll be dropping support for it. We'll refuse to work with versions older
33# than the hard version.
34#
35# git-1.7 is in (EOL) Ubuntu Precise. git-1.9 is in Ubuntu Trusty.
36MIN_GIT_VERSION_SOFT = (1, 9, 1)
37MIN_GIT_VERSION_HARD = (1, 7, 2)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070038GIT_DIR = 'GIT_DIR'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070039
40LAST_GITDIR = None
41LAST_CWD = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070042
David Pursehouse819827a2020-02-12 15:20:19 +090043
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070044class _GitCall(object):
Mike Frysinger8e768ea2021-05-06 00:28:32 -040045 @functools.lru_cache(maxsize=None)
Shawn O. Pearce334851e2011-09-19 08:05:31 -070046 def version_tuple(self):
Mike Frysinger8e768ea2021-05-06 00:28:32 -040047 ret = Wrapper().ParseGitVersion()
48 if ret is None:
49 print('fatal: unable to detect git version', file=sys.stderr)
50 sys.exit(1)
51 return ret
Shawn O. Pearce334851e2011-09-19 08:05:31 -070052
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070053 def __getattr__(self, name):
David Pursehouse54a4e602020-02-12 14:31:05 +090054 name = name.replace('_', '-')
David Pursehouse819827a2020-02-12 15:20:19 +090055
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070056 def fun(*cmdv):
57 command = [name]
58 command.extend(cmdv)
59 return GitCommand(None, command).Wait() == 0
60 return fun
David Pursehouse819827a2020-02-12 15:20:19 +090061
62
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070063git = _GitCall()
64
Mike Frysinger369814b2019-07-10 17:10:07 -040065
Mike Frysinger71b0f312019-09-30 22:39:49 -040066def RepoSourceVersion():
67 """Return the version of the repo.git tree."""
68 ver = getattr(RepoSourceVersion, 'version', None)
Mike Frysinger369814b2019-07-10 17:10:07 -040069
Mike Frysinger71b0f312019-09-30 22:39:49 -040070 # We avoid GitCommand so we don't run into circular deps -- GitCommand needs
71 # to initialize version info we provide.
72 if ver is None:
73 env = GitCommand._GetBasicEnv()
74
75 proj = os.path.dirname(os.path.abspath(__file__))
76 env[GIT_DIR] = os.path.join(proj, '.git')
Mike Frysingerf3079162021-02-16 02:38:21 -050077 result = subprocess.run([GIT, 'describe', HEAD], stdout=subprocess.PIPE,
Xin Li0cb6e922021-06-16 10:19:00 -070078 stderr=subprocess.DEVNULL, encoding='utf-8',
79 env=env, check=False)
Mike Frysingerf3079162021-02-16 02:38:21 -050080 if result.returncode == 0:
81 ver = result.stdout.strip()
Mike Frysinger71b0f312019-09-30 22:39:49 -040082 if ver.startswith('v'):
83 ver = ver[1:]
84 else:
85 ver = 'unknown'
86 setattr(RepoSourceVersion, 'version', ver)
87
88 return ver
89
90
91class UserAgent(object):
92 """Mange User-Agent settings when talking to external services
Mike Frysinger369814b2019-07-10 17:10:07 -040093
94 We follow the style as documented here:
95 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
96 """
Mike Frysinger369814b2019-07-10 17:10:07 -040097
Mike Frysinger71b0f312019-09-30 22:39:49 -040098 _os = None
99 _repo_ua = None
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400100 _git_ua = None
Mike Frysinger369814b2019-07-10 17:10:07 -0400101
Mike Frysinger71b0f312019-09-30 22:39:49 -0400102 @property
103 def os(self):
104 """The operating system name."""
105 if self._os is None:
106 os_name = sys.platform
107 if os_name.lower().startswith('linux'):
108 os_name = 'Linux'
109 elif os_name == 'win32':
110 os_name = 'Win32'
111 elif os_name == 'cygwin':
112 os_name = 'Cygwin'
113 elif os_name == 'darwin':
114 os_name = 'Darwin'
115 self._os = os_name
Mike Frysinger369814b2019-07-10 17:10:07 -0400116
Mike Frysinger71b0f312019-09-30 22:39:49 -0400117 return self._os
Mike Frysinger369814b2019-07-10 17:10:07 -0400118
Mike Frysinger71b0f312019-09-30 22:39:49 -0400119 @property
120 def repo(self):
121 """The UA when connecting directly from repo."""
122 if self._repo_ua is None:
123 py_version = sys.version_info
124 self._repo_ua = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
125 RepoSourceVersion(),
126 self.os,
127 git.version_tuple().full,
128 py_version.major, py_version.minor, py_version.micro)
Mike Frysinger369814b2019-07-10 17:10:07 -0400129
Mike Frysinger71b0f312019-09-30 22:39:49 -0400130 return self._repo_ua
Mike Frysinger369814b2019-07-10 17:10:07 -0400131
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400132 @property
133 def git(self):
134 """The UA when running git."""
135 if self._git_ua is None:
136 self._git_ua = 'git/%s (%s) git-repo/%s' % (
137 git.version_tuple().full,
138 self.os,
139 RepoSourceVersion())
140
141 return self._git_ua
142
David Pursehouse819827a2020-02-12 15:20:19 +0900143
Mike Frysinger71b0f312019-09-30 22:39:49 -0400144user_agent = UserAgent()
Mike Frysinger369814b2019-07-10 17:10:07 -0400145
David Pursehouse819827a2020-02-12 15:20:19 +0900146
Xin Li745be2e2019-06-03 11:24:30 -0700147def git_require(min_version, fail=False, msg=''):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700148 git_version = git.version_tuple()
149 if min_version <= git_version:
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700150 return True
151 if fail:
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900152 need = '.'.join(map(str, min_version))
Xin Li745be2e2019-06-03 11:24:30 -0700153 if msg:
154 msg = ' for ' + msg
155 print('fatal: git %s or later required%s' % (need, msg), file=sys.stderr)
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700156 sys.exit(1)
157 return False
158
David Pursehouse819827a2020-02-12 15:20:19 +0900159
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700160class GitCommand(object):
Mike Frysinger790f4ce2020-12-07 22:04:55 -0500161 """Wrapper around a single git invocation."""
162
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700163 def __init__(self,
164 project,
165 cmdv,
David Pursehousee5913ae2020-02-12 13:56:59 +0900166 bare=False,
Mike Frysingerf37b9822021-02-16 15:38:53 -0500167 input=None,
David Pursehousee5913ae2020-02-12 13:56:59 +0900168 capture_stdout=False,
169 capture_stderr=False,
Mike Frysinger31990f02020-02-17 01:35:18 -0500170 merge_output=False,
David Pursehousee5913ae2020-02-12 13:56:59 +0900171 disable_editor=False,
Mike Frysinger339f2df2021-05-06 00:44:42 -0400172 ssh_proxy=None,
David Pursehousee5913ae2020-02-12 13:56:59 +0900173 cwd=None,
Mike Frysinger67d6cdf2021-12-23 17:36:09 -0500174 gitdir=None,
175 objdir=None):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400176 env = self._GetBasicEnv()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700177
178 if disable_editor:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500179 env['GIT_EDITOR'] = ':'
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700180 if ssh_proxy:
Mike Frysinger339f2df2021-05-06 00:44:42 -0400181 env['REPO_SSH_SOCK'] = ssh_proxy.sock()
182 env['GIT_SSH'] = ssh_proxy.proxy
Mike Frysinger56ce3462019-12-04 19:30:48 -0500183 env['GIT_SSH_VARIANT'] = 'ssh'
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700184 if 'http_proxy' in env and 'darwin' == sys.platform:
Shawn O. Pearce337aee02012-06-13 10:40:46 -0700185 s = "'http.proxy=%s'" % (env['http_proxy'],)
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700186 p = env.get('GIT_CONFIG_PARAMETERS')
187 if p is not None:
188 s = p + ' ' + s
Mike Frysinger56ce3462019-12-04 19:30:48 -0500189 env['GIT_CONFIG_PARAMETERS'] = s
Dan Willemsen466b8c42015-11-25 13:26:39 -0800190 if 'GIT_ALLOW_PROTOCOL' not in env:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500191 env['GIT_ALLOW_PROTOCOL'] = (
192 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
193 env['GIT_HTTP_USER_AGENT'] = user_agent.git
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700194
195 if project:
196 if not cwd:
197 cwd = project.worktree
198 if not gitdir:
199 gitdir = project.gitdir
Mike Frysinger67d6cdf2021-12-23 17:36:09 -0500200 # Git on Windows wants its paths only using / for reliability.
201 if platform_utils.isWindows():
202 if objdir:
203 objdir = objdir.replace('\\', '/')
204 if gitdir:
205 gitdir = gitdir.replace('\\', '/')
206
207 if objdir:
208 # Set to the place we want to save the objects.
209 env['GIT_OBJECT_DIRECTORY'] = objdir
210 if gitdir:
211 # Allow git to search the original place in case of local or unique refs
212 # that git will attempt to resolve even if we aren't fetching them.
213 env['GIT_ALTERNATE_OBJECT_DIRECTORIES'] = gitdir + '/objects'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700214
215 command = [GIT]
216 if bare:
217 if gitdir:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500218 env[GIT_DIR] = gitdir
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700219 cwd = None
John L. Villalovos9c76f672015-03-16 20:49:10 -0700220 command.append(cmdv[0])
221 # Need to use the --progress flag for fetch/clone so output will be
222 # displayed as by default git only does progress output if stderr is a TTY.
223 if sys.stderr.isatty() and cmdv[0] in ('fetch', 'clone'):
224 if '--progress' not in cmdv and '--quiet' not in cmdv:
225 command.append('--progress')
226 command.extend(cmdv[1:])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700227
Mike Frysingerf37b9822021-02-16 15:38:53 -0500228 stdin = subprocess.PIPE if input else None
Mike Frysingerc87c1862021-02-16 17:18:12 -0500229 stdout = subprocess.PIPE if capture_stdout else None
230 stderr = (subprocess.STDOUT if merge_output else
231 (subprocess.PIPE if capture_stderr else None))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700232
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700233 if IsTrace():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700234 global LAST_CWD
235 global LAST_GITDIR
236
LaMont Jones5fb9c6a2022-11-08 00:54:56 +0000237 dbg = ''
238
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700239 if cwd and LAST_CWD != cwd:
240 if LAST_GITDIR or LAST_CWD:
241 dbg += '\n'
242 dbg += ': cd %s\n' % cwd
243 LAST_CWD = cwd
244
245 if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
246 if LAST_GITDIR or LAST_CWD:
247 dbg += '\n'
248 dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
249 LAST_GITDIR = env[GIT_DIR]
250
Mike Frysinger67d6cdf2021-12-23 17:36:09 -0500251 if 'GIT_OBJECT_DIRECTORY' in env:
252 dbg += ': export GIT_OBJECT_DIRECTORY=%s\n' % env['GIT_OBJECT_DIRECTORY']
253 if 'GIT_ALTERNATE_OBJECT_DIRECTORIES' in env:
254 dbg += ': export GIT_ALTERNATE_OBJECT_DIRECTORIES=%s\n' % env['GIT_ALTERNATE_OBJECT_DIRECTORIES']
255
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700256 dbg += ': '
257 dbg += ' '.join(command)
258 if stdin == subprocess.PIPE:
259 dbg += ' 0<|'
260 if stdout == subprocess.PIPE:
261 dbg += ' 1>|'
262 if stderr == subprocess.PIPE:
263 dbg += ' 2>|'
Mike Frysinger31990f02020-02-17 01:35:18 -0500264 elif stderr == subprocess.STDOUT:
265 dbg += ' 2>&1'
LaMont Jones5fb9c6a2022-11-08 00:54:56 +0000266 Trace('%s', dbg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700267
LaMont Jones5fb9c6a2022-11-08 00:54:56 +0000268 try:
269 p = subprocess.Popen(command,
270 cwd=cwd,
271 env=env,
272 encoding='utf-8',
273 errors='backslashreplace',
274 stdin=stdin,
275 stdout=stdout,
276 stderr=stderr)
277 except Exception as e:
278 raise GitError('%s: %s' % (command[1], e))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700279
LaMont Jones5fb9c6a2022-11-08 00:54:56 +0000280 if ssh_proxy:
281 ssh_proxy.add_client(p)
282
283 self.process = p
284
285 try:
286 self.stdout, self.stderr = p.communicate(input=input)
287 finally:
Mike Frysinger339f2df2021-05-06 00:44:42 -0400288 if ssh_proxy:
LaMont Jones5fb9c6a2022-11-08 00:54:56 +0000289 ssh_proxy.remove_client(p)
290 self.rc = p.wait()
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500291
Mike Frysinger71b0f312019-09-30 22:39:49 -0400292 @staticmethod
293 def _GetBasicEnv():
294 """Return a basic env for running git under.
295
296 This is guaranteed to be side-effect free.
297 """
298 env = os.environ.copy()
299 for key in (REPO_TRACE,
300 GIT_DIR,
301 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
302 'GIT_OBJECT_DIRECTORY',
303 'GIT_WORK_TREE',
304 'GIT_GRAFT_FILE',
305 'GIT_INDEX_FILE'):
306 env.pop(key, None)
307 return env
308
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700309 def Wait(self):
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500310 return self.rc