blob: 04953f38db39e45225d652cc4344aa9d3117efda [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,
78 encoding='utf-8', env=env, check=False)
79 if result.returncode == 0:
80 ver = result.stdout.strip()
Mike Frysinger71b0f312019-09-30 22:39:49 -040081 if ver.startswith('v'):
82 ver = ver[1:]
83 else:
84 ver = 'unknown'
85 setattr(RepoSourceVersion, 'version', ver)
86
87 return ver
88
89
90class UserAgent(object):
91 """Mange User-Agent settings when talking to external services
Mike Frysinger369814b2019-07-10 17:10:07 -040092
93 We follow the style as documented here:
94 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
95 """
Mike Frysinger369814b2019-07-10 17:10:07 -040096
Mike Frysinger71b0f312019-09-30 22:39:49 -040097 _os = None
98 _repo_ua = None
Mike Frysinger2f0951b2019-07-10 17:13:46 -040099 _git_ua = None
Mike Frysinger369814b2019-07-10 17:10:07 -0400100
Mike Frysinger71b0f312019-09-30 22:39:49 -0400101 @property
102 def os(self):
103 """The operating system name."""
104 if self._os is None:
105 os_name = sys.platform
106 if os_name.lower().startswith('linux'):
107 os_name = 'Linux'
108 elif os_name == 'win32':
109 os_name = 'Win32'
110 elif os_name == 'cygwin':
111 os_name = 'Cygwin'
112 elif os_name == 'darwin':
113 os_name = 'Darwin'
114 self._os = os_name
Mike Frysinger369814b2019-07-10 17:10:07 -0400115
Mike Frysinger71b0f312019-09-30 22:39:49 -0400116 return self._os
Mike Frysinger369814b2019-07-10 17:10:07 -0400117
Mike Frysinger71b0f312019-09-30 22:39:49 -0400118 @property
119 def repo(self):
120 """The UA when connecting directly from repo."""
121 if self._repo_ua is None:
122 py_version = sys.version_info
123 self._repo_ua = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
124 RepoSourceVersion(),
125 self.os,
126 git.version_tuple().full,
127 py_version.major, py_version.minor, py_version.micro)
Mike Frysinger369814b2019-07-10 17:10:07 -0400128
Mike Frysinger71b0f312019-09-30 22:39:49 -0400129 return self._repo_ua
Mike Frysinger369814b2019-07-10 17:10:07 -0400130
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400131 @property
132 def git(self):
133 """The UA when running git."""
134 if self._git_ua is None:
135 self._git_ua = 'git/%s (%s) git-repo/%s' % (
136 git.version_tuple().full,
137 self.os,
138 RepoSourceVersion())
139
140 return self._git_ua
141
David Pursehouse819827a2020-02-12 15:20:19 +0900142
Mike Frysinger71b0f312019-09-30 22:39:49 -0400143user_agent = UserAgent()
Mike Frysinger369814b2019-07-10 17:10:07 -0400144
David Pursehouse819827a2020-02-12 15:20:19 +0900145
Xin Li745be2e2019-06-03 11:24:30 -0700146def git_require(min_version, fail=False, msg=''):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700147 git_version = git.version_tuple()
148 if min_version <= git_version:
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700149 return True
150 if fail:
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900151 need = '.'.join(map(str, min_version))
Xin Li745be2e2019-06-03 11:24:30 -0700152 if msg:
153 msg = ' for ' + msg
154 print('fatal: git %s or later required%s' % (need, msg), file=sys.stderr)
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700155 sys.exit(1)
156 return False
157
David Pursehouse819827a2020-02-12 15:20:19 +0900158
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700159class GitCommand(object):
160 def __init__(self,
161 project,
162 cmdv,
David Pursehousee5913ae2020-02-12 13:56:59 +0900163 bare=False,
Mike Frysingerf37b9822021-02-16 15:38:53 -0500164 input=None,
David Pursehousee5913ae2020-02-12 13:56:59 +0900165 capture_stdout=False,
166 capture_stderr=False,
Mike Frysinger31990f02020-02-17 01:35:18 -0500167 merge_output=False,
David Pursehousee5913ae2020-02-12 13:56:59 +0900168 disable_editor=False,
Mike Frysinger339f2df2021-05-06 00:44:42 -0400169 ssh_proxy=None,
David Pursehousee5913ae2020-02-12 13:56:59 +0900170 cwd=None,
171 gitdir=None):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400172 env = self._GetBasicEnv()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700173
174 if disable_editor:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500175 env['GIT_EDITOR'] = ':'
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700176 if ssh_proxy:
Mike Frysinger339f2df2021-05-06 00:44:42 -0400177 env['REPO_SSH_SOCK'] = ssh_proxy.sock()
178 env['GIT_SSH'] = ssh_proxy.proxy
Mike Frysinger56ce3462019-12-04 19:30:48 -0500179 env['GIT_SSH_VARIANT'] = 'ssh'
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700180 if 'http_proxy' in env and 'darwin' == sys.platform:
Shawn O. Pearce337aee02012-06-13 10:40:46 -0700181 s = "'http.proxy=%s'" % (env['http_proxy'],)
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700182 p = env.get('GIT_CONFIG_PARAMETERS')
183 if p is not None:
184 s = p + ' ' + s
Mike Frysinger56ce3462019-12-04 19:30:48 -0500185 env['GIT_CONFIG_PARAMETERS'] = s
Dan Willemsen466b8c42015-11-25 13:26:39 -0800186 if 'GIT_ALLOW_PROTOCOL' not in env:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500187 env['GIT_ALLOW_PROTOCOL'] = (
188 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
189 env['GIT_HTTP_USER_AGENT'] = user_agent.git
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700190
191 if project:
192 if not cwd:
193 cwd = project.worktree
194 if not gitdir:
195 gitdir = project.gitdir
196
197 command = [GIT]
198 if bare:
199 if gitdir:
Mike Frysinger4510be52021-02-27 13:06:27 -0500200 # Git on Windows wants its paths only using / for reliability.
201 if platform_utils.isWindows():
202 gitdir = gitdir.replace('\\', '/')
Mike Frysinger56ce3462019-12-04 19:30:48 -0500203 env[GIT_DIR] = gitdir
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700204 cwd = None
John L. Villalovos9c76f672015-03-16 20:49:10 -0700205 command.append(cmdv[0])
206 # Need to use the --progress flag for fetch/clone so output will be
207 # displayed as by default git only does progress output if stderr is a TTY.
208 if sys.stderr.isatty() and cmdv[0] in ('fetch', 'clone'):
209 if '--progress' not in cmdv and '--quiet' not in cmdv:
210 command.append('--progress')
211 command.extend(cmdv[1:])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700212
Mike Frysingerf37b9822021-02-16 15:38:53 -0500213 stdin = subprocess.PIPE if input else None
Mike Frysingerc87c1862021-02-16 17:18:12 -0500214 stdout = subprocess.PIPE if capture_stdout else None
215 stderr = (subprocess.STDOUT if merge_output else
216 (subprocess.PIPE if capture_stderr else None))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700217
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700218 if IsTrace():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700219 global LAST_CWD
220 global LAST_GITDIR
221
222 dbg = ''
223
224 if cwd and LAST_CWD != cwd:
225 if LAST_GITDIR or LAST_CWD:
226 dbg += '\n'
227 dbg += ': cd %s\n' % cwd
228 LAST_CWD = cwd
229
230 if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
231 if LAST_GITDIR or LAST_CWD:
232 dbg += '\n'
233 dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
234 LAST_GITDIR = env[GIT_DIR]
235
236 dbg += ': '
237 dbg += ' '.join(command)
238 if stdin == subprocess.PIPE:
239 dbg += ' 0<|'
240 if stdout == subprocess.PIPE:
241 dbg += ' 1>|'
242 if stderr == subprocess.PIPE:
243 dbg += ' 2>|'
Mike Frysinger31990f02020-02-17 01:35:18 -0500244 elif stderr == subprocess.STDOUT:
245 dbg += ' 2>&1'
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700246 Trace('%s', dbg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700247
248 try:
249 p = subprocess.Popen(command,
David Pursehousee5913ae2020-02-12 13:56:59 +0900250 cwd=cwd,
251 env=env,
Mike Frysingerc87c1862021-02-16 17:18:12 -0500252 encoding='utf-8',
253 errors='backslashreplace',
David Pursehousee5913ae2020-02-12 13:56:59 +0900254 stdin=stdin,
255 stdout=stdout,
256 stderr=stderr)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700257 except Exception as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700258 raise GitError('%s: %s' % (command[1], e))
259
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700260 if ssh_proxy:
Mike Frysinger339f2df2021-05-06 00:44:42 -0400261 ssh_proxy.add_client(p)
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700262
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700263 self.process = p
Mike Frysingerf37b9822021-02-16 15:38:53 -0500264 if input:
265 if isinstance(input, str):
266 input = input.encode('utf-8')
267 p.stdin.write(input)
268 p.stdin.close()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700269
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500270 try:
Mike Frysingerc87c1862021-02-16 17:18:12 -0500271 self.stdout, self.stderr = p.communicate()
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500272 finally:
Mike Frysinger339f2df2021-05-06 00:44:42 -0400273 if ssh_proxy:
274 ssh_proxy.remove_client(p)
Mike Frysingerc87c1862021-02-16 17:18:12 -0500275 self.rc = p.wait()
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500276
Mike Frysinger71b0f312019-09-30 22:39:49 -0400277 @staticmethod
278 def _GetBasicEnv():
279 """Return a basic env for running git under.
280
281 This is guaranteed to be side-effect free.
282 """
283 env = os.environ.copy()
284 for key in (REPO_TRACE,
285 GIT_DIR,
286 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
287 'GIT_OBJECT_DIRECTORY',
288 'GIT_WORK_TREE',
289 'GIT_GRAFT_FILE',
290 'GIT_INDEX_FILE'):
291 env.pop(key, None)
292 return env
293
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700294 def Wait(self):
Mike Frysingerc5bbea82021-02-16 15:45:19 -0500295 return self.rc