blob: 95db91f298de033a53c075dbcb5b5b870656d2dc [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):
161 def __init__(self,
162 project,
163 cmdv,
David Pursehousee5913ae2020-02-12 13:56:59 +0900164 bare=False,
Mike Frysingerf37b9822021-02-16 15:38:53 -0500165 input=None,
David Pursehousee5913ae2020-02-12 13:56:59 +0900166 capture_stdout=False,
167 capture_stderr=False,
Mike Frysinger31990f02020-02-17 01:35:18 -0500168 merge_output=False,
David Pursehousee5913ae2020-02-12 13:56:59 +0900169 disable_editor=False,
Mike Frysinger339f2df2021-05-06 00:44:42 -0400170 ssh_proxy=None,
David Pursehousee5913ae2020-02-12 13:56:59 +0900171 cwd=None,
172 gitdir=None):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400173 env = self._GetBasicEnv()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700174
175 if disable_editor:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500176 env['GIT_EDITOR'] = ':'
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700177 if ssh_proxy:
Mike Frysinger339f2df2021-05-06 00:44:42 -0400178 env['REPO_SSH_SOCK'] = ssh_proxy.sock()
179 env['GIT_SSH'] = ssh_proxy.proxy
Mike Frysinger56ce3462019-12-04 19:30:48 -0500180 env['GIT_SSH_VARIANT'] = 'ssh'
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700181 if 'http_proxy' in env and 'darwin' == sys.platform:
Shawn O. Pearce337aee02012-06-13 10:40:46 -0700182 s = "'http.proxy=%s'" % (env['http_proxy'],)
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700183 p = env.get('GIT_CONFIG_PARAMETERS')
184 if p is not None:
185 s = p + ' ' + s
Mike Frysinger56ce3462019-12-04 19:30:48 -0500186 env['GIT_CONFIG_PARAMETERS'] = s
Dan Willemsen466b8c42015-11-25 13:26:39 -0800187 if 'GIT_ALLOW_PROTOCOL' not in env:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500188 env['GIT_ALLOW_PROTOCOL'] = (
189 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
190 env['GIT_HTTP_USER_AGENT'] = user_agent.git
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700191
192 if project:
193 if not cwd:
194 cwd = project.worktree
195 if not gitdir:
196 gitdir = project.gitdir
197
198 command = [GIT]
199 if bare:
200 if gitdir:
Mike Frysinger4510be52021-02-27 13:06:27 -0500201 # Git on Windows wants its paths only using / for reliability.
202 if platform_utils.isWindows():
203 gitdir = gitdir.replace('\\', '/')
Mike Frysinger56ce3462019-12-04 19:30:48 -0500204 env[GIT_DIR] = gitdir
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700205 cwd = None
John L. Villalovos9c76f672015-03-16 20:49:10 -0700206 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:])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700213
Mike Frysingerf37b9822021-02-16 15:38:53 -0500214 stdin = subprocess.PIPE if input else None
Mike Frysingerc87c1862021-02-16 17:18:12 -0500215 stdout = subprocess.PIPE if capture_stdout else None
216 stderr = (subprocess.STDOUT if merge_output else
217 (subprocess.PIPE if capture_stderr else None))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700218
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700219 if IsTrace():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700220 global LAST_CWD
221 global LAST_GITDIR
222
223 dbg = ''
224
225 if cwd and LAST_CWD != cwd:
226 if LAST_GITDIR or LAST_CWD:
227 dbg += '\n'
228 dbg += ': cd %s\n' % cwd
229 LAST_CWD = cwd
230
231 if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
232 if LAST_GITDIR or LAST_CWD:
233 dbg += '\n'
234 dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
235 LAST_GITDIR = env[GIT_DIR]
236
237 dbg += ': '
238 dbg += ' '.join(command)
239 if stdin == subprocess.PIPE:
240 dbg += ' 0<|'
241 if stdout == subprocess.PIPE:
242 dbg += ' 1>|'
243 if stderr == subprocess.PIPE:
244 dbg += ' 2>|'
Mike Frysinger31990f02020-02-17 01:35:18 -0500245 elif stderr == subprocess.STDOUT:
246 dbg += ' 2>&1'
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700247 Trace('%s', dbg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700248
249 try:
250 p = subprocess.Popen(command,
David Pursehousee5913ae2020-02-12 13:56:59 +0900251 cwd=cwd,
252 env=env,
Mike Frysingerc87c1862021-02-16 17:18:12 -0500253 encoding='utf-8',
254 errors='backslashreplace',
David Pursehousee5913ae2020-02-12 13:56:59 +0900255 stdin=stdin,
256 stdout=stdout,
257 stderr=stderr)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700258 except Exception as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700259 raise GitError('%s: %s' % (command[1], e))
260
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700261 if ssh_proxy:
Mike Frysinger339f2df2021-05-06 00:44:42 -0400262 ssh_proxy.add_client(p)
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700263
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700264 self.process = p
Mike Frysingerf37b9822021-02-16 15:38:53 -0500265 if input:
266 if isinstance(input, str):
267 input = input.encode('utf-8')
268 p.stdin.write(input)
269 p.stdin.close()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700270
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500271 try:
Mike Frysingerc87c1862021-02-16 17:18:12 -0500272 self.stdout, self.stderr = p.communicate()
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500273 finally:
Mike Frysinger339f2df2021-05-06 00:44:42 -0400274 if ssh_proxy:
275 ssh_proxy.remove_client(p)
Mike Frysingerc87c1862021-02-16 17:18:12 -0500276 self.rc = p.wait()
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500277
Mike Frysinger71b0f312019-09-30 22:39:49 -0400278 @staticmethod
279 def _GetBasicEnv():
280 """Return a basic env for running git under.
281
282 This is guaranteed to be side-effect free.
283 """
284 env = os.environ.copy()
285 for key in (REPO_TRACE,
286 GIT_DIR,
287 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
288 'GIT_OBJECT_DIRECTORY',
289 'GIT_WORK_TREE',
290 'GIT_GRAFT_FILE',
291 'GIT_INDEX_FILE'):
292 env.pop(key, None)
293 return env
294
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700295 def Wait(self):
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500296 return self.rc