blob: a4081f452f839e3b95ac1a82a77bd52d4f41d11e [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'
31MIN_GIT_VERSION = (1, 5, 4)
32GIT_DIR = 'GIT_DIR'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070033
34LAST_GITDIR = None
35LAST_CWD = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070036
Shawn O. Pearcefb231612009-04-10 18:53:46 -070037_ssh_proxy_path = None
38_ssh_sock_path = None
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070039_ssh_clients = []
Shawn O. Pearcefb231612009-04-10 18:53:46 -070040
Nico Sallembien1c85f4e2010-04-27 14:35:27 -070041def ssh_sock(create=True):
Shawn O. Pearcefb231612009-04-10 18:53:46 -070042 global _ssh_sock_path
43 if _ssh_sock_path is None:
44 if not create:
45 return None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +020046 tmp_dir = '/tmp'
47 if not os.path.exists(tmp_dir):
48 tmp_dir = tempfile.gettempdir()
Shawn O. Pearcefb231612009-04-10 18:53:46 -070049 _ssh_sock_path = os.path.join(
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +020050 tempfile.mkdtemp('', 'ssh-', tmp_dir),
Shawn O. Pearcefb231612009-04-10 18:53:46 -070051 'master-%r@%h:%p')
52 return _ssh_sock_path
53
54def _ssh_proxy():
55 global _ssh_proxy_path
56 if _ssh_proxy_path is None:
57 _ssh_proxy_path = os.path.join(
58 os.path.dirname(__file__),
59 'git_ssh')
60 return _ssh_proxy_path
61
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070062def _add_ssh_client(p):
63 _ssh_clients.append(p)
64
65def _remove_ssh_client(p):
66 try:
67 _ssh_clients.remove(p)
68 except ValueError:
69 pass
70
71def terminate_ssh_clients():
72 global _ssh_clients
73 for p in _ssh_clients:
74 try:
75 os.kill(p.pid, SIGTERM)
76 p.wait()
77 except OSError:
78 pass
79 _ssh_clients = []
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070080
Shawn O. Pearce334851e2011-09-19 08:05:31 -070081_git_version = None
82
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070083class _GitCall(object):
Shawn O. Pearce334851e2011-09-19 08:05:31 -070084 def version_tuple(self):
85 global _git_version
Shawn O. Pearce334851e2011-09-19 08:05:31 -070086 if _git_version is None:
Mike Frysingerca540ae2019-07-10 15:42:30 -040087 _git_version = Wrapper().ParseGitVersion()
Conley Owensff0a3c82014-01-30 14:46:03 -080088 if _git_version is None:
Mike Frysingerca540ae2019-07-10 15:42:30 -040089 print('fatal: unable to detect git version', file=sys.stderr)
Shawn O. Pearce334851e2011-09-19 08:05:31 -070090 sys.exit(1)
91 return _git_version
92
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070093 def __getattr__(self, name):
94 name = name.replace('_','-')
95 def fun(*cmdv):
96 command = [name]
97 command.extend(cmdv)
98 return GitCommand(None, command).Wait() == 0
99 return fun
100git = _GitCall()
101
Mike Frysinger369814b2019-07-10 17:10:07 -0400102
Mike Frysinger71b0f312019-09-30 22:39:49 -0400103def RepoSourceVersion():
104 """Return the version of the repo.git tree."""
105 ver = getattr(RepoSourceVersion, 'version', None)
Mike Frysinger369814b2019-07-10 17:10:07 -0400106
Mike Frysinger71b0f312019-09-30 22:39:49 -0400107 # We avoid GitCommand so we don't run into circular deps -- GitCommand needs
108 # to initialize version info we provide.
109 if ver is None:
110 env = GitCommand._GetBasicEnv()
111
112 proj = os.path.dirname(os.path.abspath(__file__))
113 env[GIT_DIR] = os.path.join(proj, '.git')
114
115 p = subprocess.Popen([GIT, 'describe', HEAD], stdout=subprocess.PIPE,
116 env=env)
117 if p.wait() == 0:
118 ver = p.stdout.read().strip().decode('utf-8')
119 if ver.startswith('v'):
120 ver = ver[1:]
121 else:
122 ver = 'unknown'
123 setattr(RepoSourceVersion, 'version', ver)
124
125 return ver
126
127
128class UserAgent(object):
129 """Mange User-Agent settings when talking to external services
Mike Frysinger369814b2019-07-10 17:10:07 -0400130
131 We follow the style as documented here:
132 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
133 """
Mike Frysinger369814b2019-07-10 17:10:07 -0400134
Mike Frysinger71b0f312019-09-30 22:39:49 -0400135 _os = None
136 _repo_ua = None
Mike Frysinger369814b2019-07-10 17:10:07 -0400137
Mike Frysinger71b0f312019-09-30 22:39:49 -0400138 @property
139 def os(self):
140 """The operating system name."""
141 if self._os is None:
142 os_name = sys.platform
143 if os_name.lower().startswith('linux'):
144 os_name = 'Linux'
145 elif os_name == 'win32':
146 os_name = 'Win32'
147 elif os_name == 'cygwin':
148 os_name = 'Cygwin'
149 elif os_name == 'darwin':
150 os_name = 'Darwin'
151 self._os = os_name
Mike Frysinger369814b2019-07-10 17:10:07 -0400152
Mike Frysinger71b0f312019-09-30 22:39:49 -0400153 return self._os
Mike Frysinger369814b2019-07-10 17:10:07 -0400154
Mike Frysinger71b0f312019-09-30 22:39:49 -0400155 @property
156 def repo(self):
157 """The UA when connecting directly from repo."""
158 if self._repo_ua is None:
159 py_version = sys.version_info
160 self._repo_ua = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
161 RepoSourceVersion(),
162 self.os,
163 git.version_tuple().full,
164 py_version.major, py_version.minor, py_version.micro)
Mike Frysinger369814b2019-07-10 17:10:07 -0400165
Mike Frysinger71b0f312019-09-30 22:39:49 -0400166 return self._repo_ua
Mike Frysinger369814b2019-07-10 17:10:07 -0400167
Mike Frysinger71b0f312019-09-30 22:39:49 -0400168user_agent = UserAgent()
Mike Frysinger369814b2019-07-10 17:10:07 -0400169
Xin Li745be2e2019-06-03 11:24:30 -0700170def git_require(min_version, fail=False, msg=''):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700171 git_version = git.version_tuple()
172 if min_version <= git_version:
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700173 return True
174 if fail:
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900175 need = '.'.join(map(str, min_version))
Xin Li745be2e2019-06-03 11:24:30 -0700176 if msg:
177 msg = ' for ' + msg
178 print('fatal: git %s or later required%s' % (need, msg), file=sys.stderr)
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700179 sys.exit(1)
180 return False
181
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800182def _setenv(env, name, value):
183 env[name] = value.encode()
184
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700185class GitCommand(object):
186 def __init__(self,
187 project,
188 cmdv,
189 bare = False,
190 provide_stdin = False,
191 capture_stdout = False,
192 capture_stderr = False,
193 disable_editor = False,
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700194 ssh_proxy = False,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700195 cwd = None,
196 gitdir = None):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400197 env = self._GetBasicEnv()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700198
John L. Villalovos9c76f672015-03-16 20:49:10 -0700199 # If we are not capturing std* then need to print it.
200 self.tee = {'stdout': not capture_stdout, 'stderr': not capture_stderr}
201
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700202 if disable_editor:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800203 _setenv(env, 'GIT_EDITOR', ':')
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700204 if ssh_proxy:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800205 _setenv(env, 'REPO_SSH_SOCK', ssh_sock())
206 _setenv(env, 'GIT_SSH', _ssh_proxy())
Jonathan Niederc00d28b2017-10-19 14:23:10 -0700207 _setenv(env, 'GIT_SSH_VARIANT', 'ssh')
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700208 if 'http_proxy' in env and 'darwin' == sys.platform:
Shawn O. Pearce337aee02012-06-13 10:40:46 -0700209 s = "'http.proxy=%s'" % (env['http_proxy'],)
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700210 p = env.get('GIT_CONFIG_PARAMETERS')
211 if p is not None:
212 s = p + ' ' + s
213 _setenv(env, 'GIT_CONFIG_PARAMETERS', s)
Dan Willemsen466b8c42015-11-25 13:26:39 -0800214 if 'GIT_ALLOW_PROTOCOL' not in env:
215 _setenv(env, 'GIT_ALLOW_PROTOCOL',
Jonathan Nieder203153e2016-02-26 18:53:54 -0800216 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700217
218 if project:
219 if not cwd:
220 cwd = project.worktree
221 if not gitdir:
222 gitdir = project.gitdir
223
224 command = [GIT]
225 if bare:
226 if gitdir:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800227 _setenv(env, GIT_DIR, gitdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700228 cwd = None
John L. Villalovos9c76f672015-03-16 20:49:10 -0700229 command.append(cmdv[0])
230 # Need to use the --progress flag for fetch/clone so output will be
231 # displayed as by default git only does progress output if stderr is a TTY.
232 if sys.stderr.isatty() and cmdv[0] in ('fetch', 'clone'):
233 if '--progress' not in cmdv and '--quiet' not in cmdv:
234 command.append('--progress')
235 command.extend(cmdv[1:])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700236
237 if provide_stdin:
238 stdin = subprocess.PIPE
239 else:
240 stdin = None
241
John L. Villalovos9c76f672015-03-16 20:49:10 -0700242 stdout = subprocess.PIPE
243 stderr = subprocess.PIPE
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700244
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700245 if IsTrace():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700246 global LAST_CWD
247 global LAST_GITDIR
248
249 dbg = ''
250
251 if cwd and LAST_CWD != cwd:
252 if LAST_GITDIR or LAST_CWD:
253 dbg += '\n'
254 dbg += ': cd %s\n' % cwd
255 LAST_CWD = cwd
256
257 if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
258 if LAST_GITDIR or LAST_CWD:
259 dbg += '\n'
260 dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
261 LAST_GITDIR = env[GIT_DIR]
262
263 dbg += ': '
264 dbg += ' '.join(command)
265 if stdin == subprocess.PIPE:
266 dbg += ' 0<|'
267 if stdout == subprocess.PIPE:
268 dbg += ' 1>|'
269 if stderr == subprocess.PIPE:
270 dbg += ' 2>|'
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700271 Trace('%s', dbg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700272
273 try:
274 p = subprocess.Popen(command,
275 cwd = cwd,
276 env = env,
277 stdin = stdin,
278 stdout = stdout,
279 stderr = stderr)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700280 except Exception as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700281 raise GitError('%s: %s' % (command[1], e))
282
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700283 if ssh_proxy:
284 _add_ssh_client(p)
285
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700286 self.process = p
287 self.stdin = p.stdin
288
Mike Frysinger71b0f312019-09-30 22:39:49 -0400289 @staticmethod
290 def _GetBasicEnv():
291 """Return a basic env for running git under.
292
293 This is guaranteed to be side-effect free.
294 """
295 env = os.environ.copy()
296 for key in (REPO_TRACE,
297 GIT_DIR,
298 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
299 'GIT_OBJECT_DIRECTORY',
300 'GIT_WORK_TREE',
301 'GIT_GRAFT_FILE',
302 'GIT_INDEX_FILE'):
303 env.pop(key, None)
304 return env
305
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700306 def Wait(self):
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700307 try:
Ulrik Sjölin498fe902011-09-11 22:59:37 +0200308 p = self.process
John L. Villalovos9c76f672015-03-16 20:49:10 -0700309 rc = self._CaptureOutput()
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700310 finally:
311 _remove_ssh_client(p)
312 return rc
John L. Villalovos9c76f672015-03-16 20:49:10 -0700313
314 def _CaptureOutput(self):
315 p = self.process
Renaud Paquay2e702912016-11-01 11:23:38 -0700316 s_in = platform_utils.FileDescriptorStreams.create()
317 s_in.add(p.stdout, sys.stdout, 'stdout')
318 s_in.add(p.stderr, sys.stderr, 'stderr')
John L. Villalovos9c76f672015-03-16 20:49:10 -0700319 self.stdout = ''
320 self.stderr = ''
321
Renaud Paquay2e702912016-11-01 11:23:38 -0700322 while not s_in.is_done:
323 in_ready = s_in.select()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700324 for s in in_ready:
Renaud Paquay2e702912016-11-01 11:23:38 -0700325 buf = s.read()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700326 if not buf:
327 s_in.remove(s)
328 continue
Anthony King6cfc68e2015-06-03 16:39:32 +0100329 if not hasattr(buf, 'encode'):
330 buf = buf.decode()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700331 if s.std_name == 'stdout':
332 self.stdout += buf
333 else:
334 self.stderr += buf
335 if self.tee[s.std_name]:
336 s.dest.write(buf)
337 s.dest.flush()
338 return p.wait()