blob: 4868ccdf37b5ddf9ecde12b60cb8b3043fd156a3 [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
19import sys
20import subprocess
Shawn O. Pearcefb231612009-04-10 18:53:46 -070021import tempfile
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070022from signal import SIGTERM
Renaud Paquay2e702912016-11-01 11:23:38 -070023
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070024from error import GitError
Mike Frysinger71b0f312019-09-30 22:39:49 -040025from git_refs import HEAD
Renaud Paquay2e702912016-11-01 11:23:38 -070026import platform_utils
Mike Frysinger8a11f6f2019-08-27 00:26:15 -040027from repo_trace import REPO_TRACE, IsTrace, Trace
Conley Owensff0a3c82014-01-30 14:46:03 -080028from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070029
30GIT = 'git'
Mike Frysinger82caef62020-02-11 18:51:08 -050031# NB: These do not need to be kept in sync with the repo launcher script.
32# These may be much newer as it allows the repo launcher to roll between
33# different repo releases while source versions might require a newer git.
34#
35# The soft version is when we start warning users that the version is old and
36# we'll be dropping support for it. We'll refuse to work with versions older
37# than the hard version.
38#
39# git-1.7 is in (EOL) Ubuntu Precise. git-1.9 is in Ubuntu Trusty.
40MIN_GIT_VERSION_SOFT = (1, 9, 1)
41MIN_GIT_VERSION_HARD = (1, 7, 2)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070042GIT_DIR = 'GIT_DIR'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070043
44LAST_GITDIR = None
45LAST_CWD = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070046
Shawn O. Pearcefb231612009-04-10 18:53:46 -070047_ssh_proxy_path = None
48_ssh_sock_path = None
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070049_ssh_clients = []
Shawn O. Pearcefb231612009-04-10 18:53:46 -070050
Nico Sallembien1c85f4e2010-04-27 14:35:27 -070051def ssh_sock(create=True):
Shawn O. Pearcefb231612009-04-10 18:53:46 -070052 global _ssh_sock_path
53 if _ssh_sock_path is None:
54 if not create:
55 return None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +020056 tmp_dir = '/tmp'
57 if not os.path.exists(tmp_dir):
58 tmp_dir = tempfile.gettempdir()
Shawn O. Pearcefb231612009-04-10 18:53:46 -070059 _ssh_sock_path = os.path.join(
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +020060 tempfile.mkdtemp('', 'ssh-', tmp_dir),
Shawn O. Pearcefb231612009-04-10 18:53:46 -070061 'master-%r@%h:%p')
62 return _ssh_sock_path
63
64def _ssh_proxy():
65 global _ssh_proxy_path
66 if _ssh_proxy_path is None:
67 _ssh_proxy_path = os.path.join(
68 os.path.dirname(__file__),
69 'git_ssh')
70 return _ssh_proxy_path
71
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070072def _add_ssh_client(p):
73 _ssh_clients.append(p)
74
75def _remove_ssh_client(p):
76 try:
77 _ssh_clients.remove(p)
78 except ValueError:
79 pass
80
81def terminate_ssh_clients():
82 global _ssh_clients
83 for p in _ssh_clients:
84 try:
85 os.kill(p.pid, SIGTERM)
86 p.wait()
87 except OSError:
88 pass
89 _ssh_clients = []
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070090
Shawn O. Pearce334851e2011-09-19 08:05:31 -070091_git_version = None
92
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070093class _GitCall(object):
Shawn O. Pearce334851e2011-09-19 08:05:31 -070094 def version_tuple(self):
95 global _git_version
Shawn O. Pearce334851e2011-09-19 08:05:31 -070096 if _git_version is None:
Mike Frysingerca540ae2019-07-10 15:42:30 -040097 _git_version = Wrapper().ParseGitVersion()
Conley Owensff0a3c82014-01-30 14:46:03 -080098 if _git_version is None:
Mike Frysingerca540ae2019-07-10 15:42:30 -040099 print('fatal: unable to detect git version', file=sys.stderr)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700100 sys.exit(1)
101 return _git_version
102
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700103 def __getattr__(self, name):
104 name = name.replace('_','-')
105 def fun(*cmdv):
106 command = [name]
107 command.extend(cmdv)
108 return GitCommand(None, command).Wait() == 0
109 return fun
110git = _GitCall()
111
Mike Frysinger369814b2019-07-10 17:10:07 -0400112
Mike Frysinger71b0f312019-09-30 22:39:49 -0400113def RepoSourceVersion():
114 """Return the version of the repo.git tree."""
115 ver = getattr(RepoSourceVersion, 'version', None)
Mike Frysinger369814b2019-07-10 17:10:07 -0400116
Mike Frysinger71b0f312019-09-30 22:39:49 -0400117 # We avoid GitCommand so we don't run into circular deps -- GitCommand needs
118 # to initialize version info we provide.
119 if ver is None:
120 env = GitCommand._GetBasicEnv()
121
122 proj = os.path.dirname(os.path.abspath(__file__))
123 env[GIT_DIR] = os.path.join(proj, '.git')
124
125 p = subprocess.Popen([GIT, 'describe', HEAD], stdout=subprocess.PIPE,
126 env=env)
127 if p.wait() == 0:
128 ver = p.stdout.read().strip().decode('utf-8')
129 if ver.startswith('v'):
130 ver = ver[1:]
131 else:
132 ver = 'unknown'
133 setattr(RepoSourceVersion, 'version', ver)
134
135 return ver
136
137
138class UserAgent(object):
139 """Mange User-Agent settings when talking to external services
Mike Frysinger369814b2019-07-10 17:10:07 -0400140
141 We follow the style as documented here:
142 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
143 """
Mike Frysinger369814b2019-07-10 17:10:07 -0400144
Mike Frysinger71b0f312019-09-30 22:39:49 -0400145 _os = None
146 _repo_ua = None
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400147 _git_ua = None
Mike Frysinger369814b2019-07-10 17:10:07 -0400148
Mike Frysinger71b0f312019-09-30 22:39:49 -0400149 @property
150 def os(self):
151 """The operating system name."""
152 if self._os is None:
153 os_name = sys.platform
154 if os_name.lower().startswith('linux'):
155 os_name = 'Linux'
156 elif os_name == 'win32':
157 os_name = 'Win32'
158 elif os_name == 'cygwin':
159 os_name = 'Cygwin'
160 elif os_name == 'darwin':
161 os_name = 'Darwin'
162 self._os = os_name
Mike Frysinger369814b2019-07-10 17:10:07 -0400163
Mike Frysinger71b0f312019-09-30 22:39:49 -0400164 return self._os
Mike Frysinger369814b2019-07-10 17:10:07 -0400165
Mike Frysinger71b0f312019-09-30 22:39:49 -0400166 @property
167 def repo(self):
168 """The UA when connecting directly from repo."""
169 if self._repo_ua is None:
170 py_version = sys.version_info
171 self._repo_ua = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
172 RepoSourceVersion(),
173 self.os,
174 git.version_tuple().full,
175 py_version.major, py_version.minor, py_version.micro)
Mike Frysinger369814b2019-07-10 17:10:07 -0400176
Mike Frysinger71b0f312019-09-30 22:39:49 -0400177 return self._repo_ua
Mike Frysinger369814b2019-07-10 17:10:07 -0400178
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400179 @property
180 def git(self):
181 """The UA when running git."""
182 if self._git_ua is None:
183 self._git_ua = 'git/%s (%s) git-repo/%s' % (
184 git.version_tuple().full,
185 self.os,
186 RepoSourceVersion())
187
188 return self._git_ua
189
Mike Frysinger71b0f312019-09-30 22:39:49 -0400190user_agent = UserAgent()
Mike Frysinger369814b2019-07-10 17:10:07 -0400191
Xin Li745be2e2019-06-03 11:24:30 -0700192def git_require(min_version, fail=False, msg=''):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700193 git_version = git.version_tuple()
194 if min_version <= git_version:
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700195 return True
196 if fail:
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900197 need = '.'.join(map(str, min_version))
Xin Li745be2e2019-06-03 11:24:30 -0700198 if msg:
199 msg = ' for ' + msg
200 print('fatal: git %s or later required%s' % (need, msg), file=sys.stderr)
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700201 sys.exit(1)
202 return False
203
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800204def _setenv(env, name, value):
205 env[name] = value.encode()
206
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700207class GitCommand(object):
208 def __init__(self,
209 project,
210 cmdv,
211 bare = False,
212 provide_stdin = False,
213 capture_stdout = False,
214 capture_stderr = False,
215 disable_editor = False,
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700216 ssh_proxy = False,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700217 cwd = None,
218 gitdir = None):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400219 env = self._GetBasicEnv()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700220
John L. Villalovos9c76f672015-03-16 20:49:10 -0700221 # If we are not capturing std* then need to print it.
222 self.tee = {'stdout': not capture_stdout, 'stderr': not capture_stderr}
223
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700224 if disable_editor:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800225 _setenv(env, 'GIT_EDITOR', ':')
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700226 if ssh_proxy:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800227 _setenv(env, 'REPO_SSH_SOCK', ssh_sock())
228 _setenv(env, 'GIT_SSH', _ssh_proxy())
Jonathan Niederc00d28b2017-10-19 14:23:10 -0700229 _setenv(env, 'GIT_SSH_VARIANT', 'ssh')
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700230 if 'http_proxy' in env and 'darwin' == sys.platform:
Shawn O. Pearce337aee02012-06-13 10:40:46 -0700231 s = "'http.proxy=%s'" % (env['http_proxy'],)
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700232 p = env.get('GIT_CONFIG_PARAMETERS')
233 if p is not None:
234 s = p + ' ' + s
235 _setenv(env, 'GIT_CONFIG_PARAMETERS', s)
Dan Willemsen466b8c42015-11-25 13:26:39 -0800236 if 'GIT_ALLOW_PROTOCOL' not in env:
237 _setenv(env, 'GIT_ALLOW_PROTOCOL',
Jonathan Nieder203153e2016-02-26 18:53:54 -0800238 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400239 _setenv(env, 'GIT_HTTP_USER_AGENT', user_agent.git)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700240
241 if project:
242 if not cwd:
243 cwd = project.worktree
244 if not gitdir:
245 gitdir = project.gitdir
246
247 command = [GIT]
248 if bare:
249 if gitdir:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800250 _setenv(env, GIT_DIR, gitdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700251 cwd = None
John L. Villalovos9c76f672015-03-16 20:49:10 -0700252 command.append(cmdv[0])
253 # Need to use the --progress flag for fetch/clone so output will be
254 # displayed as by default git only does progress output if stderr is a TTY.
255 if sys.stderr.isatty() and cmdv[0] in ('fetch', 'clone'):
256 if '--progress' not in cmdv and '--quiet' not in cmdv:
257 command.append('--progress')
258 command.extend(cmdv[1:])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700259
260 if provide_stdin:
261 stdin = subprocess.PIPE
262 else:
263 stdin = None
264
John L. Villalovos9c76f672015-03-16 20:49:10 -0700265 stdout = subprocess.PIPE
266 stderr = subprocess.PIPE
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700267
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700268 if IsTrace():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700269 global LAST_CWD
270 global LAST_GITDIR
271
272 dbg = ''
273
274 if cwd and LAST_CWD != cwd:
275 if LAST_GITDIR or LAST_CWD:
276 dbg += '\n'
277 dbg += ': cd %s\n' % cwd
278 LAST_CWD = cwd
279
280 if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
281 if LAST_GITDIR or LAST_CWD:
282 dbg += '\n'
283 dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
284 LAST_GITDIR = env[GIT_DIR]
285
286 dbg += ': '
287 dbg += ' '.join(command)
288 if stdin == subprocess.PIPE:
289 dbg += ' 0<|'
290 if stdout == subprocess.PIPE:
291 dbg += ' 1>|'
292 if stderr == subprocess.PIPE:
293 dbg += ' 2>|'
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700294 Trace('%s', dbg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700295
296 try:
297 p = subprocess.Popen(command,
298 cwd = cwd,
299 env = env,
300 stdin = stdin,
301 stdout = stdout,
302 stderr = stderr)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700303 except Exception as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700304 raise GitError('%s: %s' % (command[1], e))
305
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700306 if ssh_proxy:
307 _add_ssh_client(p)
308
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700309 self.process = p
310 self.stdin = p.stdin
311
Mike Frysinger71b0f312019-09-30 22:39:49 -0400312 @staticmethod
313 def _GetBasicEnv():
314 """Return a basic env for running git under.
315
316 This is guaranteed to be side-effect free.
317 """
318 env = os.environ.copy()
319 for key in (REPO_TRACE,
320 GIT_DIR,
321 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
322 'GIT_OBJECT_DIRECTORY',
323 'GIT_WORK_TREE',
324 'GIT_GRAFT_FILE',
325 'GIT_INDEX_FILE'):
326 env.pop(key, None)
327 return env
328
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700329 def Wait(self):
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700330 try:
Ulrik Sjölin498fe902011-09-11 22:59:37 +0200331 p = self.process
John L. Villalovos9c76f672015-03-16 20:49:10 -0700332 rc = self._CaptureOutput()
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700333 finally:
334 _remove_ssh_client(p)
335 return rc
John L. Villalovos9c76f672015-03-16 20:49:10 -0700336
337 def _CaptureOutput(self):
338 p = self.process
Renaud Paquay2e702912016-11-01 11:23:38 -0700339 s_in = platform_utils.FileDescriptorStreams.create()
340 s_in.add(p.stdout, sys.stdout, 'stdout')
341 s_in.add(p.stderr, sys.stderr, 'stderr')
John L. Villalovos9c76f672015-03-16 20:49:10 -0700342 self.stdout = ''
343 self.stderr = ''
344
Renaud Paquay2e702912016-11-01 11:23:38 -0700345 while not s_in.is_done:
346 in_ready = s_in.select()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700347 for s in in_ready:
Renaud Paquay2e702912016-11-01 11:23:38 -0700348 buf = s.read()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700349 if not buf:
350 s_in.remove(s)
351 continue
Anthony King6cfc68e2015-06-03 16:39:32 +0100352 if not hasattr(buf, 'encode'):
353 buf = buf.decode()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700354 if s.std_name == 'stdout':
355 self.stdout += buf
356 else:
357 self.stderr += buf
358 if self.tee[s.std_name]:
359 s.dest.write(buf)
360 s.dest.flush()
361 return p.wait()