blob: 5017ea9bcdc6639df66371a0576d8ebddef479fd [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 Frysinger655aedd2020-02-04 00:02:18 -050031# Should keep in sync with the "repo" launcher file.
32MIN_GIT_VERSION = (2, 10, 2)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070033GIT_DIR = 'GIT_DIR'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070034
35LAST_GITDIR = None
36LAST_CWD = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070037
Shawn O. Pearcefb231612009-04-10 18:53:46 -070038_ssh_proxy_path = None
39_ssh_sock_path = None
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070040_ssh_clients = []
Shawn O. Pearcefb231612009-04-10 18:53:46 -070041
Nico Sallembien1c85f4e2010-04-27 14:35:27 -070042def ssh_sock(create=True):
Shawn O. Pearcefb231612009-04-10 18:53:46 -070043 global _ssh_sock_path
44 if _ssh_sock_path is None:
45 if not create:
46 return None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +020047 tmp_dir = '/tmp'
48 if not os.path.exists(tmp_dir):
49 tmp_dir = tempfile.gettempdir()
Shawn O. Pearcefb231612009-04-10 18:53:46 -070050 _ssh_sock_path = os.path.join(
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +020051 tempfile.mkdtemp('', 'ssh-', tmp_dir),
Shawn O. Pearcefb231612009-04-10 18:53:46 -070052 'master-%r@%h:%p')
53 return _ssh_sock_path
54
55def _ssh_proxy():
56 global _ssh_proxy_path
57 if _ssh_proxy_path is None:
58 _ssh_proxy_path = os.path.join(
59 os.path.dirname(__file__),
60 'git_ssh')
61 return _ssh_proxy_path
62
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070063def _add_ssh_client(p):
64 _ssh_clients.append(p)
65
66def _remove_ssh_client(p):
67 try:
68 _ssh_clients.remove(p)
69 except ValueError:
70 pass
71
72def terminate_ssh_clients():
73 global _ssh_clients
74 for p in _ssh_clients:
75 try:
76 os.kill(p.pid, SIGTERM)
77 p.wait()
78 except OSError:
79 pass
80 _ssh_clients = []
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070081
Shawn O. Pearce334851e2011-09-19 08:05:31 -070082_git_version = None
83
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070084class _GitCall(object):
Shawn O. Pearce334851e2011-09-19 08:05:31 -070085 def version_tuple(self):
86 global _git_version
Shawn O. Pearce334851e2011-09-19 08:05:31 -070087 if _git_version is None:
Mike Frysingerca540ae2019-07-10 15:42:30 -040088 _git_version = Wrapper().ParseGitVersion()
Conley Owensff0a3c82014-01-30 14:46:03 -080089 if _git_version is None:
Mike Frysingerca540ae2019-07-10 15:42:30 -040090 print('fatal: unable to detect git version', file=sys.stderr)
Shawn O. Pearce334851e2011-09-19 08:05:31 -070091 sys.exit(1)
92 return _git_version
93
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070094 def __getattr__(self, name):
95 name = name.replace('_','-')
96 def fun(*cmdv):
97 command = [name]
98 command.extend(cmdv)
99 return GitCommand(None, command).Wait() == 0
100 return fun
101git = _GitCall()
102
Mike Frysinger369814b2019-07-10 17:10:07 -0400103
Mike Frysinger71b0f312019-09-30 22:39:49 -0400104def RepoSourceVersion():
105 """Return the version of the repo.git tree."""
106 ver = getattr(RepoSourceVersion, 'version', None)
Mike Frysinger369814b2019-07-10 17:10:07 -0400107
Mike Frysinger71b0f312019-09-30 22:39:49 -0400108 # We avoid GitCommand so we don't run into circular deps -- GitCommand needs
109 # to initialize version info we provide.
110 if ver is None:
111 env = GitCommand._GetBasicEnv()
112
113 proj = os.path.dirname(os.path.abspath(__file__))
114 env[GIT_DIR] = os.path.join(proj, '.git')
115
116 p = subprocess.Popen([GIT, 'describe', HEAD], stdout=subprocess.PIPE,
117 env=env)
118 if p.wait() == 0:
119 ver = p.stdout.read().strip().decode('utf-8')
120 if ver.startswith('v'):
121 ver = ver[1:]
122 else:
123 ver = 'unknown'
124 setattr(RepoSourceVersion, 'version', ver)
125
126 return ver
127
128
129class UserAgent(object):
130 """Mange User-Agent settings when talking to external services
Mike Frysinger369814b2019-07-10 17:10:07 -0400131
132 We follow the style as documented here:
133 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
134 """
Mike Frysinger369814b2019-07-10 17:10:07 -0400135
Mike Frysinger71b0f312019-09-30 22:39:49 -0400136 _os = None
137 _repo_ua = None
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400138 _git_ua = None
Mike Frysinger369814b2019-07-10 17:10:07 -0400139
Mike Frysinger71b0f312019-09-30 22:39:49 -0400140 @property
141 def os(self):
142 """The operating system name."""
143 if self._os is None:
144 os_name = sys.platform
145 if os_name.lower().startswith('linux'):
146 os_name = 'Linux'
147 elif os_name == 'win32':
148 os_name = 'Win32'
149 elif os_name == 'cygwin':
150 os_name = 'Cygwin'
151 elif os_name == 'darwin':
152 os_name = 'Darwin'
153 self._os = os_name
Mike Frysinger369814b2019-07-10 17:10:07 -0400154
Mike Frysinger71b0f312019-09-30 22:39:49 -0400155 return self._os
Mike Frysinger369814b2019-07-10 17:10:07 -0400156
Mike Frysinger71b0f312019-09-30 22:39:49 -0400157 @property
158 def repo(self):
159 """The UA when connecting directly from repo."""
160 if self._repo_ua is None:
161 py_version = sys.version_info
162 self._repo_ua = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
163 RepoSourceVersion(),
164 self.os,
165 git.version_tuple().full,
166 py_version.major, py_version.minor, py_version.micro)
Mike Frysinger369814b2019-07-10 17:10:07 -0400167
Mike Frysinger71b0f312019-09-30 22:39:49 -0400168 return self._repo_ua
Mike Frysinger369814b2019-07-10 17:10:07 -0400169
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400170 @property
171 def git(self):
172 """The UA when running git."""
173 if self._git_ua is None:
174 self._git_ua = 'git/%s (%s) git-repo/%s' % (
175 git.version_tuple().full,
176 self.os,
177 RepoSourceVersion())
178
179 return self._git_ua
180
Mike Frysinger71b0f312019-09-30 22:39:49 -0400181user_agent = UserAgent()
Mike Frysinger369814b2019-07-10 17:10:07 -0400182
Xin Li745be2e2019-06-03 11:24:30 -0700183def git_require(min_version, fail=False, msg=''):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700184 git_version = git.version_tuple()
185 if min_version <= git_version:
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700186 return True
187 if fail:
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900188 need = '.'.join(map(str, min_version))
Xin Li745be2e2019-06-03 11:24:30 -0700189 if msg:
190 msg = ' for ' + msg
191 print('fatal: git %s or later required%s' % (need, msg), file=sys.stderr)
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700192 sys.exit(1)
193 return False
194
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800195def _setenv(env, name, value):
196 env[name] = value.encode()
197
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700198class GitCommand(object):
199 def __init__(self,
200 project,
201 cmdv,
202 bare = False,
203 provide_stdin = False,
204 capture_stdout = False,
205 capture_stderr = False,
206 disable_editor = False,
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700207 ssh_proxy = False,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700208 cwd = None,
209 gitdir = None):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400210 env = self._GetBasicEnv()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700211
John L. Villalovos9c76f672015-03-16 20:49:10 -0700212 # If we are not capturing std* then need to print it.
213 self.tee = {'stdout': not capture_stdout, 'stderr': not capture_stderr}
214
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700215 if disable_editor:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800216 _setenv(env, 'GIT_EDITOR', ':')
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700217 if ssh_proxy:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800218 _setenv(env, 'REPO_SSH_SOCK', ssh_sock())
219 _setenv(env, 'GIT_SSH', _ssh_proxy())
Jonathan Niederc00d28b2017-10-19 14:23:10 -0700220 _setenv(env, 'GIT_SSH_VARIANT', 'ssh')
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700221 if 'http_proxy' in env and 'darwin' == sys.platform:
Shawn O. Pearce337aee02012-06-13 10:40:46 -0700222 s = "'http.proxy=%s'" % (env['http_proxy'],)
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700223 p = env.get('GIT_CONFIG_PARAMETERS')
224 if p is not None:
225 s = p + ' ' + s
226 _setenv(env, 'GIT_CONFIG_PARAMETERS', s)
Dan Willemsen466b8c42015-11-25 13:26:39 -0800227 if 'GIT_ALLOW_PROTOCOL' not in env:
228 _setenv(env, 'GIT_ALLOW_PROTOCOL',
Jonathan Nieder203153e2016-02-26 18:53:54 -0800229 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
Mike Frysinger2f0951b2019-07-10 17:13:46 -0400230 _setenv(env, 'GIT_HTTP_USER_AGENT', user_agent.git)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700231
232 if project:
233 if not cwd:
234 cwd = project.worktree
235 if not gitdir:
236 gitdir = project.gitdir
237
238 command = [GIT]
239 if bare:
240 if gitdir:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800241 _setenv(env, GIT_DIR, gitdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700242 cwd = None
John L. Villalovos9c76f672015-03-16 20:49:10 -0700243 command.append(cmdv[0])
244 # Need to use the --progress flag for fetch/clone so output will be
245 # displayed as by default git only does progress output if stderr is a TTY.
246 if sys.stderr.isatty() and cmdv[0] in ('fetch', 'clone'):
247 if '--progress' not in cmdv and '--quiet' not in cmdv:
248 command.append('--progress')
249 command.extend(cmdv[1:])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700250
251 if provide_stdin:
252 stdin = subprocess.PIPE
253 else:
254 stdin = None
255
John L. Villalovos9c76f672015-03-16 20:49:10 -0700256 stdout = subprocess.PIPE
257 stderr = subprocess.PIPE
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700258
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700259 if IsTrace():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700260 global LAST_CWD
261 global LAST_GITDIR
262
263 dbg = ''
264
265 if cwd and LAST_CWD != cwd:
266 if LAST_GITDIR or LAST_CWD:
267 dbg += '\n'
268 dbg += ': cd %s\n' % cwd
269 LAST_CWD = cwd
270
271 if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
272 if LAST_GITDIR or LAST_CWD:
273 dbg += '\n'
274 dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
275 LAST_GITDIR = env[GIT_DIR]
276
277 dbg += ': '
278 dbg += ' '.join(command)
279 if stdin == subprocess.PIPE:
280 dbg += ' 0<|'
281 if stdout == subprocess.PIPE:
282 dbg += ' 1>|'
283 if stderr == subprocess.PIPE:
284 dbg += ' 2>|'
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700285 Trace('%s', dbg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700286
287 try:
288 p = subprocess.Popen(command,
289 cwd = cwd,
290 env = env,
291 stdin = stdin,
292 stdout = stdout,
293 stderr = stderr)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700294 except Exception as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700295 raise GitError('%s: %s' % (command[1], e))
296
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700297 if ssh_proxy:
298 _add_ssh_client(p)
299
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700300 self.process = p
301 self.stdin = p.stdin
302
Mike Frysinger71b0f312019-09-30 22:39:49 -0400303 @staticmethod
304 def _GetBasicEnv():
305 """Return a basic env for running git under.
306
307 This is guaranteed to be side-effect free.
308 """
309 env = os.environ.copy()
310 for key in (REPO_TRACE,
311 GIT_DIR,
312 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
313 'GIT_OBJECT_DIRECTORY',
314 'GIT_WORK_TREE',
315 'GIT_GRAFT_FILE',
316 'GIT_INDEX_FILE'):
317 env.pop(key, None)
318 return env
319
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700320 def Wait(self):
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700321 try:
Ulrik Sjölin498fe902011-09-11 22:59:37 +0200322 p = self.process
John L. Villalovos9c76f672015-03-16 20:49:10 -0700323 rc = self._CaptureOutput()
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700324 finally:
325 _remove_ssh_client(p)
326 return rc
John L. Villalovos9c76f672015-03-16 20:49:10 -0700327
328 def _CaptureOutput(self):
329 p = self.process
Renaud Paquay2e702912016-11-01 11:23:38 -0700330 s_in = platform_utils.FileDescriptorStreams.create()
331 s_in.add(p.stdout, sys.stdout, 'stdout')
332 s_in.add(p.stderr, sys.stderr, 'stderr')
John L. Villalovos9c76f672015-03-16 20:49:10 -0700333 self.stdout = ''
334 self.stderr = ''
335
Renaud Paquay2e702912016-11-01 11:23:38 -0700336 while not s_in.is_done:
337 in_ready = s_in.select()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700338 for s in in_ready:
Renaud Paquay2e702912016-11-01 11:23:38 -0700339 buf = s.read()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700340 if not buf:
341 s_in.remove(s)
342 continue
Anthony King6cfc68e2015-06-03 16:39:32 +0100343 if not hasattr(buf, 'encode'):
344 buf = buf.decode()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700345 if s.std_name == 'stdout':
346 self.stdout += buf
347 else:
348 self.stderr += buf
349 if self.tee[s.std_name]:
350 s.dest.write(buf)
351 s.dest.flush()
352 return p.wait()