blob: 89b681e1dc661acb6d5c55772ef0ca34baa8b8cd [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001#
2# Copyright (C) 2008 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
Sarah Owenscecd1d82012-11-01 22:59:27 -070016from __future__ import print_function
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070017import os
18import sys
19import subprocess
Shawn O. Pearcefb231612009-04-10 18:53:46 -070020import tempfile
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070021from signal import SIGTERM
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070022from error import GitError
Shawn O. Pearcead3193a2009-04-18 09:54:51 -070023from trace import REPO_TRACE, IsTrace, Trace
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070024
25GIT = 'git'
26MIN_GIT_VERSION = (1, 5, 4)
27GIT_DIR = 'GIT_DIR'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070028
29LAST_GITDIR = None
30LAST_CWD = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070031
Shawn O. Pearcefb231612009-04-10 18:53:46 -070032_ssh_proxy_path = None
33_ssh_sock_path = None
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070034_ssh_clients = []
Shawn O. Pearcefb231612009-04-10 18:53:46 -070035
Nico Sallembien1c85f4e2010-04-27 14:35:27 -070036def ssh_sock(create=True):
Shawn O. Pearcefb231612009-04-10 18:53:46 -070037 global _ssh_sock_path
38 if _ssh_sock_path is None:
39 if not create:
40 return None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +020041 tmp_dir = '/tmp'
42 if not os.path.exists(tmp_dir):
43 tmp_dir = tempfile.gettempdir()
Shawn O. Pearcefb231612009-04-10 18:53:46 -070044 _ssh_sock_path = os.path.join(
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +020045 tempfile.mkdtemp('', 'ssh-', tmp_dir),
Shawn O. Pearcefb231612009-04-10 18:53:46 -070046 'master-%r@%h:%p')
47 return _ssh_sock_path
48
49def _ssh_proxy():
50 global _ssh_proxy_path
51 if _ssh_proxy_path is None:
52 _ssh_proxy_path = os.path.join(
53 os.path.dirname(__file__),
54 'git_ssh')
55 return _ssh_proxy_path
56
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070057def _add_ssh_client(p):
58 _ssh_clients.append(p)
59
60def _remove_ssh_client(p):
61 try:
62 _ssh_clients.remove(p)
63 except ValueError:
64 pass
65
66def terminate_ssh_clients():
67 global _ssh_clients
68 for p in _ssh_clients:
69 try:
70 os.kill(p.pid, SIGTERM)
71 p.wait()
72 except OSError:
73 pass
74 _ssh_clients = []
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070075
Shawn O. Pearce334851e2011-09-19 08:05:31 -070076_git_version = None
77
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070078class _GitCall(object):
79 def version(self):
80 p = GitCommand(None, ['--version'], capture_stdout=True)
81 if p.Wait() == 0:
82 return p.stdout
83 return None
84
Shawn O. Pearce334851e2011-09-19 08:05:31 -070085 def version_tuple(self):
86 global _git_version
87
88 if _git_version is None:
Chirayu Desai0eb35cb2013-11-19 18:46:29 +053089 ver_str = git.version().decode('utf-8')
Shawn O. Pearce334851e2011-09-19 08:05:31 -070090 if ver_str.startswith('git version '):
Conley Owens148a84d2014-01-30 13:53:55 -080091 num_ver_str = ver_str[len('git version '):].strip().split('-')[0]
Conley Owens1c5da492014-01-30 13:09:08 -080092 to_tuple = []
93 for num_str in num_ver_str.split('.')[:3]:
94 if num_str.isdigit():
95 to_tuple.append(int(num_str))
96 else:
97 to_tuple.append(0)
98 _git_version = tuple(to_tuple)
Shawn O. Pearce334851e2011-09-19 08:05:31 -070099 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700100 print('fatal: "%s" unsupported' % ver_str, file=sys.stderr)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700101 sys.exit(1)
102 return _git_version
103
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700104 def __getattr__(self, name):
105 name = name.replace('_','-')
106 def fun(*cmdv):
107 command = [name]
108 command.extend(cmdv)
109 return GitCommand(None, command).Wait() == 0
110 return fun
111git = _GitCall()
112
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700113def git_require(min_version, fail=False):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700114 git_version = git.version_tuple()
115 if min_version <= git_version:
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700116 return True
117 if fail:
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900118 need = '.'.join(map(str, min_version))
Sarah Owenscecd1d82012-11-01 22:59:27 -0700119 print('fatal: git %s or later required' % need, file=sys.stderr)
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700120 sys.exit(1)
121 return False
122
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800123def _setenv(env, name, value):
124 env[name] = value.encode()
125
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700126class GitCommand(object):
127 def __init__(self,
128 project,
129 cmdv,
130 bare = False,
131 provide_stdin = False,
132 capture_stdout = False,
133 capture_stderr = False,
134 disable_editor = False,
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700135 ssh_proxy = False,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700136 cwd = None,
137 gitdir = None):
Shawn O. Pearce727ee982010-12-07 08:46:14 -0800138 env = os.environ.copy()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700139
David Pursehouse1d947b32012-10-25 12:23:11 +0900140 for key in [REPO_TRACE,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700141 GIT_DIR,
142 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
143 'GIT_OBJECT_DIRECTORY',
144 'GIT_WORK_TREE',
145 'GIT_GRAFT_FILE',
146 'GIT_INDEX_FILE']:
David Pursehouse1d947b32012-10-25 12:23:11 +0900147 if key in env:
148 del env[key]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700149
150 if disable_editor:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800151 _setenv(env, 'GIT_EDITOR', ':')
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700152 if ssh_proxy:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800153 _setenv(env, 'REPO_SSH_SOCK', ssh_sock())
154 _setenv(env, 'GIT_SSH', _ssh_proxy())
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700155 if 'http_proxy' in env and 'darwin' == sys.platform:
Shawn O. Pearce337aee02012-06-13 10:40:46 -0700156 s = "'http.proxy=%s'" % (env['http_proxy'],)
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700157 p = env.get('GIT_CONFIG_PARAMETERS')
158 if p is not None:
159 s = p + ' ' + s
160 _setenv(env, 'GIT_CONFIG_PARAMETERS', s)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700161
162 if project:
163 if not cwd:
164 cwd = project.worktree
165 if not gitdir:
166 gitdir = project.gitdir
167
168 command = [GIT]
169 if bare:
170 if gitdir:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800171 _setenv(env, GIT_DIR, gitdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700172 cwd = None
173 command.extend(cmdv)
174
175 if provide_stdin:
176 stdin = subprocess.PIPE
177 else:
178 stdin = None
179
180 if capture_stdout:
181 stdout = subprocess.PIPE
182 else:
183 stdout = None
184
185 if capture_stderr:
186 stderr = subprocess.PIPE
187 else:
188 stderr = None
189
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700190 if IsTrace():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700191 global LAST_CWD
192 global LAST_GITDIR
193
194 dbg = ''
195
196 if cwd and LAST_CWD != cwd:
197 if LAST_GITDIR or LAST_CWD:
198 dbg += '\n'
199 dbg += ': cd %s\n' % cwd
200 LAST_CWD = cwd
201
202 if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
203 if LAST_GITDIR or LAST_CWD:
204 dbg += '\n'
205 dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
206 LAST_GITDIR = env[GIT_DIR]
207
208 dbg += ': '
209 dbg += ' '.join(command)
210 if stdin == subprocess.PIPE:
211 dbg += ' 0<|'
212 if stdout == subprocess.PIPE:
213 dbg += ' 1>|'
214 if stderr == subprocess.PIPE:
215 dbg += ' 2>|'
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700216 Trace('%s', dbg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700217
218 try:
219 p = subprocess.Popen(command,
220 cwd = cwd,
221 env = env,
222 stdin = stdin,
223 stdout = stdout,
224 stderr = stderr)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700225 except Exception as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700226 raise GitError('%s: %s' % (command[1], e))
227
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700228 if ssh_proxy:
229 _add_ssh_client(p)
230
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700231 self.process = p
232 self.stdin = p.stdin
233
234 def Wait(self):
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700235 try:
Ulrik Sjölin498fe902011-09-11 22:59:37 +0200236 p = self.process
237 (self.stdout, self.stderr) = p.communicate()
238 rc = p.returncode
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700239 finally:
240 _remove_ssh_client(p)
241 return rc