blob: 1807b55e4f60d5348f90b6776174a3e585b6a5bd [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
Renaud Paquay2e702912016-11-01 11:23:38 -070025import platform_utils
Shawn O. Pearcead3193a2009-04-18 09:54:51 -070026from trace import REPO_TRACE, IsTrace, Trace
Conley Owensff0a3c82014-01-30 14:46:03 -080027from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070028
29GIT = 'git'
30MIN_GIT_VERSION = (1, 5, 4)
31GIT_DIR = 'GIT_DIR'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070032
33LAST_GITDIR = None
34LAST_CWD = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070035
Shawn O. Pearcefb231612009-04-10 18:53:46 -070036_ssh_proxy_path = None
37_ssh_sock_path = None
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070038_ssh_clients = []
Shawn O. Pearcefb231612009-04-10 18:53:46 -070039
Nico Sallembien1c85f4e2010-04-27 14:35:27 -070040def ssh_sock(create=True):
Shawn O. Pearcefb231612009-04-10 18:53:46 -070041 global _ssh_sock_path
42 if _ssh_sock_path is None:
43 if not create:
44 return None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +020045 tmp_dir = '/tmp'
46 if not os.path.exists(tmp_dir):
47 tmp_dir = tempfile.gettempdir()
Shawn O. Pearcefb231612009-04-10 18:53:46 -070048 _ssh_sock_path = os.path.join(
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +020049 tempfile.mkdtemp('', 'ssh-', tmp_dir),
Shawn O. Pearcefb231612009-04-10 18:53:46 -070050 'master-%r@%h:%p')
51 return _ssh_sock_path
52
53def _ssh_proxy():
54 global _ssh_proxy_path
55 if _ssh_proxy_path is None:
56 _ssh_proxy_path = os.path.join(
57 os.path.dirname(__file__),
58 'git_ssh')
59 return _ssh_proxy_path
60
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070061def _add_ssh_client(p):
62 _ssh_clients.append(p)
63
64def _remove_ssh_client(p):
65 try:
66 _ssh_clients.remove(p)
67 except ValueError:
68 pass
69
70def terminate_ssh_clients():
71 global _ssh_clients
72 for p in _ssh_clients:
73 try:
74 os.kill(p.pid, SIGTERM)
75 p.wait()
76 except OSError:
77 pass
78 _ssh_clients = []
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070079
Shawn O. Pearce334851e2011-09-19 08:05:31 -070080_git_version = None
81
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070082class _GitCall(object):
83 def version(self):
84 p = GitCommand(None, ['--version'], capture_stdout=True)
85 if p.Wait() == 0:
Anthony Kingcf738ed2015-06-03 16:50:39 +010086 if hasattr(p.stdout, 'decode'):
87 return p.stdout.decode('utf-8')
88 else:
89 return p.stdout
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070090 return None
91
Shawn O. Pearce334851e2011-09-19 08:05:31 -070092 def version_tuple(self):
93 global _git_version
Shawn O. Pearce334851e2011-09-19 08:05:31 -070094 if _git_version is None:
Chirayu Desaic46de692014-08-20 09:34:10 +053095 ver_str = git.version()
Conley Owensff0a3c82014-01-30 14:46:03 -080096 _git_version = Wrapper().ParseGitVersion(ver_str)
97 if _git_version is None:
Sarah Owenscecd1d82012-11-01 22:59:27 -070098 print('fatal: "%s" unsupported' % ver_str, file=sys.stderr)
Shawn O. Pearce334851e2011-09-19 08:05:31 -070099 sys.exit(1)
100 return _git_version
101
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700102 def __getattr__(self, name):
103 name = name.replace('_','-')
104 def fun(*cmdv):
105 command = [name]
106 command.extend(cmdv)
107 return GitCommand(None, command).Wait() == 0
108 return fun
109git = _GitCall()
110
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700111def git_require(min_version, fail=False):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700112 git_version = git.version_tuple()
113 if min_version <= git_version:
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700114 return True
115 if fail:
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900116 need = '.'.join(map(str, min_version))
Sarah Owenscecd1d82012-11-01 22:59:27 -0700117 print('fatal: git %s or later required' % need, file=sys.stderr)
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700118 sys.exit(1)
119 return False
120
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800121def _setenv(env, name, value):
122 env[name] = value.encode()
123
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124class GitCommand(object):
125 def __init__(self,
126 project,
127 cmdv,
128 bare = False,
129 provide_stdin = False,
130 capture_stdout = False,
131 capture_stderr = False,
132 disable_editor = False,
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700133 ssh_proxy = False,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700134 cwd = None,
135 gitdir = None):
Shawn O. Pearce727ee982010-12-07 08:46:14 -0800136 env = os.environ.copy()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700137
David Pursehouse1d947b32012-10-25 12:23:11 +0900138 for key in [REPO_TRACE,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700139 GIT_DIR,
140 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
141 'GIT_OBJECT_DIRECTORY',
142 'GIT_WORK_TREE',
143 'GIT_GRAFT_FILE',
144 'GIT_INDEX_FILE']:
David Pursehouse1d947b32012-10-25 12:23:11 +0900145 if key in env:
146 del env[key]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700147
John L. Villalovos9c76f672015-03-16 20:49:10 -0700148 # If we are not capturing std* then need to print it.
149 self.tee = {'stdout': not capture_stdout, 'stderr': not capture_stderr}
150
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700151 if disable_editor:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800152 _setenv(env, 'GIT_EDITOR', ':')
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700153 if ssh_proxy:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800154 _setenv(env, 'REPO_SSH_SOCK', ssh_sock())
155 _setenv(env, 'GIT_SSH', _ssh_proxy())
Jonathan Niederc00d28b2017-10-19 14:23:10 -0700156 _setenv(env, 'GIT_SSH_VARIANT', 'ssh')
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700157 if 'http_proxy' in env and 'darwin' == sys.platform:
Shawn O. Pearce337aee02012-06-13 10:40:46 -0700158 s = "'http.proxy=%s'" % (env['http_proxy'],)
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700159 p = env.get('GIT_CONFIG_PARAMETERS')
160 if p is not None:
161 s = p + ' ' + s
162 _setenv(env, 'GIT_CONFIG_PARAMETERS', s)
Dan Willemsen466b8c42015-11-25 13:26:39 -0800163 if 'GIT_ALLOW_PROTOCOL' not in env:
164 _setenv(env, 'GIT_ALLOW_PROTOCOL',
Jonathan Nieder203153e2016-02-26 18:53:54 -0800165 'file:git:http:https:ssh:persistent-http:persistent-https:sso:rpc')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700166
167 if project:
168 if not cwd:
169 cwd = project.worktree
170 if not gitdir:
171 gitdir = project.gitdir
172
173 command = [GIT]
174 if bare:
175 if gitdir:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800176 _setenv(env, GIT_DIR, gitdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700177 cwd = None
John L. Villalovos9c76f672015-03-16 20:49:10 -0700178 command.append(cmdv[0])
179 # Need to use the --progress flag for fetch/clone so output will be
180 # displayed as by default git only does progress output if stderr is a TTY.
181 if sys.stderr.isatty() and cmdv[0] in ('fetch', 'clone'):
182 if '--progress' not in cmdv and '--quiet' not in cmdv:
183 command.append('--progress')
184 command.extend(cmdv[1:])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700185
186 if provide_stdin:
187 stdin = subprocess.PIPE
188 else:
189 stdin = None
190
John L. Villalovos9c76f672015-03-16 20:49:10 -0700191 stdout = subprocess.PIPE
192 stderr = subprocess.PIPE
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700193
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700194 if IsTrace():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700195 global LAST_CWD
196 global LAST_GITDIR
197
198 dbg = ''
199
200 if cwd and LAST_CWD != cwd:
201 if LAST_GITDIR or LAST_CWD:
202 dbg += '\n'
203 dbg += ': cd %s\n' % cwd
204 LAST_CWD = cwd
205
206 if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
207 if LAST_GITDIR or LAST_CWD:
208 dbg += '\n'
209 dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
210 LAST_GITDIR = env[GIT_DIR]
211
212 dbg += ': '
213 dbg += ' '.join(command)
214 if stdin == subprocess.PIPE:
215 dbg += ' 0<|'
216 if stdout == subprocess.PIPE:
217 dbg += ' 1>|'
218 if stderr == subprocess.PIPE:
219 dbg += ' 2>|'
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700220 Trace('%s', dbg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700221
222 try:
223 p = subprocess.Popen(command,
224 cwd = cwd,
225 env = env,
226 stdin = stdin,
227 stdout = stdout,
228 stderr = stderr)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700229 except Exception as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700230 raise GitError('%s: %s' % (command[1], e))
231
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700232 if ssh_proxy:
233 _add_ssh_client(p)
234
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700235 self.process = p
236 self.stdin = p.stdin
237
238 def Wait(self):
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700239 try:
Ulrik Sjölin498fe902011-09-11 22:59:37 +0200240 p = self.process
John L. Villalovos9c76f672015-03-16 20:49:10 -0700241 rc = self._CaptureOutput()
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700242 finally:
243 _remove_ssh_client(p)
244 return rc
John L. Villalovos9c76f672015-03-16 20:49:10 -0700245
246 def _CaptureOutput(self):
247 p = self.process
Renaud Paquay2e702912016-11-01 11:23:38 -0700248 s_in = platform_utils.FileDescriptorStreams.create()
249 s_in.add(p.stdout, sys.stdout, 'stdout')
250 s_in.add(p.stderr, sys.stderr, 'stderr')
John L. Villalovos9c76f672015-03-16 20:49:10 -0700251 self.stdout = ''
252 self.stderr = ''
253
Renaud Paquay2e702912016-11-01 11:23:38 -0700254 while not s_in.is_done:
255 in_ready = s_in.select()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700256 for s in in_ready:
Renaud Paquay2e702912016-11-01 11:23:38 -0700257 buf = s.read()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700258 if not buf:
259 s_in.remove(s)
260 continue
Anthony King6cfc68e2015-06-03 16:39:32 +0100261 if not hasattr(buf, 'encode'):
262 buf = buf.decode()
John L. Villalovos9c76f672015-03-16 20:49:10 -0700263 if s.std_name == 'stdout':
264 self.stdout += buf
265 else:
266 self.stderr += buf
267 if self.tee[s.std_name]:
268 s.dest.write(buf)
269 s.dest.flush()
270 return p.wait()