blob: 1cb8f1aaff684d001eaeb9caae6c0b3460d3cb46 [file] [log] [blame]
Mike Frysingerf6013762019-06-13 02:30:51 -04001# -*- coding:utf-8 -*-
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07002#
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
Sarah Owenscecd1d82012-11-01 22:59:27 -070017from __future__ import print_function
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070018import os
Anders Björklund8e0fe192020-02-18 14:08:35 +010019import re
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070020import sys
21import subprocess
Shawn O. Pearcefb231612009-04-10 18:53:46 -070022import tempfile
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070023from signal import SIGTERM
Renaud Paquay2e702912016-11-01 11:23:38 -070024
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070025from error import GitError
Mike Frysinger71b0f312019-09-30 22:39:49 -040026from git_refs import HEAD
Renaud Paquay2e702912016-11-01 11:23:38 -070027import platform_utils
Mike Frysinger8a11f6f2019-08-27 00:26:15 -040028from repo_trace import REPO_TRACE, IsTrace, Trace
Conley Owensff0a3c82014-01-30 14:46:03 -080029from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070030
31GIT = 'git'
Mike Frysinger82caef62020-02-11 18:51:08 -050032# NB: These do not need to be kept in sync with the repo launcher script.
33# These may be much newer as it allows the repo launcher to roll between
34# different repo releases while source versions might require a newer git.
35#
36# The soft version is when we start warning users that the version is old and
37# we'll be dropping support for it. We'll refuse to work with versions older
38# than the hard version.
39#
40# git-1.7 is in (EOL) Ubuntu Precise. git-1.9 is in Ubuntu Trusty.
41MIN_GIT_VERSION_SOFT = (1, 9, 1)
42MIN_GIT_VERSION_HARD = (1, 7, 2)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070043GIT_DIR = 'GIT_DIR'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070044
45LAST_GITDIR = None
46LAST_CWD = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070047
Shawn O. Pearcefb231612009-04-10 18:53:46 -070048_ssh_proxy_path = None
49_ssh_sock_path = None
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070050_ssh_clients = []
Anders Björklund8e0fe192020-02-18 14:08:35 +010051_ssh_version = None
52
53
54def _run_ssh_version():
55 """run ssh -V to display the version number"""
56 return subprocess.check_output(['ssh', '-V'], stderr=subprocess.STDOUT).decode()
57
58
59def _parse_ssh_version(ver_str=None):
60 """parse a ssh version string into a tuple"""
61 if ver_str is None:
62 ver_str = _run_ssh_version()
63 m = re.match(r'^OpenSSH_([0-9.]+)(p[0-9]+)?\s', ver_str)
64 if m:
65 return tuple(int(x) for x in m.group(1).split('.'))
66 else:
67 return ()
68
69
70def ssh_version():
71 """return ssh version as a tuple"""
72 global _ssh_version
73 if _ssh_version is None:
74 try:
75 _ssh_version = _parse_ssh_version()
76 except subprocess.CalledProcessError:
77 print('fatal: unable to detect ssh version', file=sys.stderr)
78 sys.exit(1)
79 return _ssh_version
Shawn O. Pearcefb231612009-04-10 18:53:46 -070080
David Pursehouse819827a2020-02-12 15:20:19 +090081
Nico Sallembien1c85f4e2010-04-27 14:35:27 -070082def ssh_sock(create=True):
Shawn O. Pearcefb231612009-04-10 18:53:46 -070083 global _ssh_sock_path
84 if _ssh_sock_path is None:
85 if not create:
86 return None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +020087 tmp_dir = '/tmp'
88 if not os.path.exists(tmp_dir):
89 tmp_dir = tempfile.gettempdir()
Anders Björklund8e0fe192020-02-18 14:08:35 +010090 if ssh_version() < (6, 7):
91 tokens = '%r@%h:%p'
92 else:
93 tokens = '%C' # hash of %l%h%p%r
Shawn O. Pearcefb231612009-04-10 18:53:46 -070094 _ssh_sock_path = os.path.join(
David Pursehouseabdf7502020-02-12 14:58:39 +090095 tempfile.mkdtemp('', 'ssh-', tmp_dir),
Anders Björklund8e0fe192020-02-18 14:08:35 +010096 'master-' + tokens)
Shawn O. Pearcefb231612009-04-10 18:53:46 -070097 return _ssh_sock_path
98
David Pursehouse819827a2020-02-12 15:20:19 +090099
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700100def _ssh_proxy():
101 global _ssh_proxy_path
102 if _ssh_proxy_path is None:
103 _ssh_proxy_path = os.path.join(
David Pursehouseabdf7502020-02-12 14:58:39 +0900104 os.path.dirname(__file__),
105 'git_ssh')
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700106 return _ssh_proxy_path
107
David Pursehouse819827a2020-02-12 15:20:19 +0900108
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700109def _add_ssh_client(p):
110 _ssh_clients.append(p)
111
David Pursehouse819827a2020-02-12 15:20:19 +0900112
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700113def _remove_ssh_client(p):
114 try:
115 _ssh_clients.remove(p)
116 except ValueError:
117 pass
118
David Pursehouse819827a2020-02-12 15:20:19 +0900119
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700120def terminate_ssh_clients():
121 global _ssh_clients
122 for p in _ssh_clients:
123 try:
124 os.kill(p.pid, SIGTERM)
125 p.wait()
126 except OSError:
127 pass
128 _ssh_clients = []
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700129
David Pursehouse819827a2020-02-12 15:20:19 +0900130
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700131_git_version = None
132
David Pursehouse819827a2020-02-12 15:20:19 +0900133
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700134class _GitCall(object):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700135 def version_tuple(self):
136 global _git_version
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700137 if _git_version is None:
Mike Frysingerca540ae2019-07-10 15:42:30 -0400138 _git_version = Wrapper().ParseGitVersion()
Conley Owensff0a3c82014-01-30 14:46:03 -0800139 if _git_version is None:
Mike Frysingerca540ae2019-07-10 15:42:30 -0400140 print('fatal: unable to detect git version', file=sys.stderr)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700141 sys.exit(1)
142 return _git_version
143
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700144 def __getattr__(self, name):
David Pursehouse54a4e602020-02-12 14:31:05 +0900145 name = name.replace('_', '-')
David Pursehouse819827a2020-02-12 15:20:19 +0900146
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700147 def fun(*cmdv):
148 command = [name]
149 command.extend(cmdv)
150 return GitCommand(None, command).Wait() == 0
151 return fun
David Pursehouse819827a2020-02-12 15:20:19 +0900152
153
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700154git = _GitCall()
155
Mike Frysinger369814b2019-07-10 17:10:07 -0400156
Mike Frysinger71b0f312019-09-30 22:39:49 -0400157def RepoSourceVersion():
158 """Return the version of the repo.git tree."""
159 ver = getattr(RepoSourceVersion, 'version', None)
Mike Frysinger369814b2019-07-10 17:10:07 -0400160
Mike Frysinger71b0f312019-09-30 22:39:49 -0400161 # We avoid GitCommand so we don't run into circular deps -- GitCommand needs
162 # to initialize version info we provide.
163 if ver is None:
164 env = GitCommand._GetBasicEnv()
165
166 proj = os.path.dirname(os.path.abspath(__file__))
167 env[GIT_DIR] = os.path.join(proj, '.git')
168
169 p = subprocess.Popen([GIT, 'describe', HEAD], stdout=subprocess.PIPE,
170 env=env)
171 if p.wait() == 0:
172 ver = p.stdout.read().strip().decode('utf-8')
173 if ver.startswith('v'):
174 ver = ver[1:]
175 else:
176 ver = 'unknown'
177 setattr(RepoSourceVersion, 'version', ver)
178
179 return ver
180
181
182class UserAgent(object):
183 """Mange User-Agent settings when talking to external services
Mike Frysinger369814b2019-07-10 17:10:07 -0400184
185 We follow the style as documented here:
186 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
187 """
Mike Frysinger369814b2019-07-10 17:10:07 -0400188
Mike Frysinger71b0f312019-09-30 22:39:49 -0400189 _os = None
190 _repo_ua = None
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400191 _git_ua = None
Mike Frysinger369814b2019-07-10 17:10:07 -0400192
Mike Frysinger71b0f312019-09-30 22:39:49 -0400193 @property
194 def os(self):
195 """The operating system name."""
196 if self._os is None:
197 os_name = sys.platform
198 if os_name.lower().startswith('linux'):
199 os_name = 'Linux'
200 elif os_name == 'win32':
201 os_name = 'Win32'
202 elif os_name == 'cygwin':
203 os_name = 'Cygwin'
204 elif os_name == 'darwin':
205 os_name = 'Darwin'
206 self._os = os_name
Mike Frysinger369814b2019-07-10 17:10:07 -0400207
Mike Frysinger71b0f312019-09-30 22:39:49 -0400208 return self._os
Mike Frysinger369814b2019-07-10 17:10:07 -0400209
Mike Frysinger71b0f312019-09-30 22:39:49 -0400210 @property
211 def repo(self):
212 """The UA when connecting directly from repo."""
213 if self._repo_ua is None:
214 py_version = sys.version_info
215 self._repo_ua = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
216 RepoSourceVersion(),
217 self.os,
218 git.version_tuple().full,
219 py_version.major, py_version.minor, py_version.micro)
Mike Frysinger369814b2019-07-10 17:10:07 -0400220
Mike Frysinger71b0f312019-09-30 22:39:49 -0400221 return self._repo_ua
Mike Frysinger369814b2019-07-10 17:10:07 -0400222
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400223 @property
224 def git(self):
225 """The UA when running git."""
226 if self._git_ua is None:
227 self._git_ua = 'git/%s (%s) git-repo/%s' % (
228 git.version_tuple().full,
229 self.os,
230 RepoSourceVersion())
231
232 return self._git_ua
233
David Pursehouse819827a2020-02-12 15:20:19 +0900234
Mike Frysinger71b0f312019-09-30 22:39:49 -0400235user_agent = UserAgent()
Mike Frysinger369814b2019-07-10 17:10:07 -0400236
David Pursehouse819827a2020-02-12 15:20:19 +0900237
Xin Li745be2e2019-06-03 11:24:30 -0700238def git_require(min_version, fail=False, msg=''):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700239 git_version = git.version_tuple()
240 if min_version <= git_version:
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700241 return True
242 if fail:
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900243 need = '.'.join(map(str, min_version))
Xin Li745be2e2019-06-03 11:24:30 -0700244 if msg:
245 msg = ' for ' + msg
246 print('fatal: git %s or later required%s' % (need, msg), file=sys.stderr)
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700247 sys.exit(1)
248 return False
249
David Pursehouse819827a2020-02-12 15:20:19 +0900250
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700251class GitCommand(object):
252 def __init__(self,
253 project,
254 cmdv,
David Pursehousee5913ae2020-02-12 13:56:59 +0900255 bare=False,
256 provide_stdin=False,
257 capture_stdout=False,
258 capture_stderr=False,
Mike Frysinger31990f02020-02-17 01:35:18 -0500259 merge_output=False,
David Pursehousee5913ae2020-02-12 13:56:59 +0900260 disable_editor=False,
261 ssh_proxy=False,
262 cwd=None,
263 gitdir=None):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400264 env = self._GetBasicEnv()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700265
John L. Villalovos9c76f672015-03-16 20:49:10 -0700266 # If we are not capturing std* then need to print it.
267 self.tee = {'stdout': not capture_stdout, 'stderr': not capture_stderr}
268
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700269 if disable_editor:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500270 env['GIT_EDITOR'] = ':'
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700271 if ssh_proxy:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500272 env['REPO_SSH_SOCK'] = ssh_sock()
273 env['GIT_SSH'] = _ssh_proxy()
274 env['GIT_SSH_VARIANT'] = 'ssh'
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700275 if 'http_proxy' in env and 'darwin' == sys.platform:
Shawn O. Pearce337aee02012-06-13 10:40:46 -0700276 s = "'http.proxy=%s'" % (env['http_proxy'],)
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700277 p = env.get('GIT_CONFIG_PARAMETERS')
278 if p is not None:
279 s = p + ' ' + s
Mike Frysinger56ce3462019-12-04 19:30:48 -0500280 env['GIT_CONFIG_PARAMETERS'] = s
Dan Willemsen466b8c42015-11-25 13:26:39 -0800281 if 'GIT_ALLOW_PROTOCOL' not in env:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500282 env['GIT_ALLOW_PROTOCOL'] = (
283 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
284 env['GIT_HTTP_USER_AGENT'] = user_agent.git
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700285
286 if project:
287 if not cwd:
288 cwd = project.worktree
289 if not gitdir:
290 gitdir = project.gitdir
291
292 command = [GIT]
293 if bare:
294 if gitdir:
Mike Frysinger56ce3462019-12-04 19:30:48 -0500295 env[GIT_DIR] = gitdir
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700296 cwd = None
John L. Villalovos9c76f672015-03-16 20:49:10 -0700297 command.append(cmdv[0])
298 # Need to use the --progress flag for fetch/clone so output will be
299 # displayed as by default git only does progress output if stderr is a TTY.
300 if sys.stderr.isatty() and cmdv[0] in ('fetch', 'clone'):
301 if '--progress' not in cmdv and '--quiet' not in cmdv:
302 command.append('--progress')
303 command.extend(cmdv[1:])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700304
305 if provide_stdin:
306 stdin = subprocess.PIPE
307 else:
308 stdin = None
309
John L. Villalovos9c76f672015-03-16 20:49:10 -0700310 stdout = subprocess.PIPE
Mike Frysinger31990f02020-02-17 01:35:18 -0500311 stderr = subprocess.STDOUT if merge_output else subprocess.PIPE
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700312
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700313 if IsTrace():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700314 global LAST_CWD
315 global LAST_GITDIR
316
317 dbg = ''
318
319 if cwd and LAST_CWD != cwd:
320 if LAST_GITDIR or LAST_CWD:
321 dbg += '\n'
322 dbg += ': cd %s\n' % cwd
323 LAST_CWD = cwd
324
325 if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
326 if LAST_GITDIR or LAST_CWD:
327 dbg += '\n'
328 dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
329 LAST_GITDIR = env[GIT_DIR]
330
331 dbg += ': '
332 dbg += ' '.join(command)
333 if stdin == subprocess.PIPE:
334 dbg += ' 0<|'
335 if stdout == subprocess.PIPE:
336 dbg += ' 1>|'
337 if stderr == subprocess.PIPE:
338 dbg += ' 2>|'
Mike Frysinger31990f02020-02-17 01:35:18 -0500339 elif stderr == subprocess.STDOUT:
340 dbg += ' 2>&1'
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700341 Trace('%s', dbg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700342
343 try:
344 p = subprocess.Popen(command,
David Pursehousee5913ae2020-02-12 13:56:59 +0900345 cwd=cwd,
346 env=env,
347 stdin=stdin,
348 stdout=stdout,
349 stderr=stderr)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700350 except Exception as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700351 raise GitError('%s: %s' % (command[1], e))
352
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700353 if ssh_proxy:
354 _add_ssh_client(p)
355
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700356 self.process = p
357 self.stdin = p.stdin
358
Mike Frysinger71b0f312019-09-30 22:39:49 -0400359 @staticmethod
360 def _GetBasicEnv():
361 """Return a basic env for running git under.
362
363 This is guaranteed to be side-effect free.
364 """
365 env = os.environ.copy()
366 for key in (REPO_TRACE,
367 GIT_DIR,
368 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
369 'GIT_OBJECT_DIRECTORY',
370 'GIT_WORK_TREE',
371 'GIT_GRAFT_FILE',
372 'GIT_INDEX_FILE'):
373 env.pop(key, None)
374 return env
375
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700376 def Wait(self):
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700377 try:
Ulrik Sjölin498fe902011-09-11 22:59:37 +0200378 p = self.process
John L. Villalovos9c76f672015-03-16 20:49:10 -0700379 rc = self._CaptureOutput()
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700380 finally:
381 _remove_ssh_client(p)
382 return rc
John L. Villalovos9c76f672015-03-16 20:49:10 -0700383
384 def _CaptureOutput(self):
385 p = self.process
Renaud Paquay2e702912016-11-01 11:23:38 -0700386 s_in = platform_utils.FileDescriptorStreams.create()
387 s_in.add(p.stdout, sys.stdout, 'stdout')
Mike Frysinger31990f02020-02-17 01:35:18 -0500388 if p.stderr is not None:
389 s_in.add(p.stderr, sys.stderr, 'stderr')
John L. Villalovos9c76f672015-03-16 20:49:10 -0700390 self.stdout = ''
391 self.stderr = ''
392
Renaud Paquay2e702912016-11-01 11:23:38 -0700393 while not s_in.is_done:
394 in_ready = s_in.select()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700395 for s in in_ready:
Renaud Paquay2e702912016-11-01 11:23:38 -0700396 buf = s.read()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700397 if not buf:
398 s_in.remove(s)
399 continue
Anthony King6cfc68e2015-06-03 16:39:32 +0100400 if not hasattr(buf, 'encode'):
401 buf = buf.decode()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700402 if s.std_name == 'stdout':
403 self.stdout += buf
404 else:
405 self.stderr += buf
406 if self.tee[s.std_name]:
407 s.dest.write(buf)
408 s.dest.flush()
409 return p.wait()