blob: d347dd612db17c9aeebdb0a4b0c2031313eefd6d [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:
89 ver_str = git.version()
90 if ver_str.startswith('git version '):
91 _git_version = tuple(
David Pursehouse7e6dd2d2012-10-25 12:40:51 +090092 map(int,
Chad Jones2bc7f5c2012-06-28 13:12:13 -070093 ver_str[len('git version '):].strip().split('-')[0].split('.')[0:3]
Shawn O. Pearce334851e2011-09-19 08:05:31 -070094 ))
95 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -070096 print('fatal: "%s" unsupported' % ver_str, file=sys.stderr)
Shawn O. Pearce334851e2011-09-19 08:05:31 -070097 sys.exit(1)
98 return _git_version
99
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700100 def __getattr__(self, name):
101 name = name.replace('_','-')
102 def fun(*cmdv):
103 command = [name]
104 command.extend(cmdv)
105 return GitCommand(None, command).Wait() == 0
106 return fun
107git = _GitCall()
108
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700109def git_require(min_version, fail=False):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700110 git_version = git.version_tuple()
111 if min_version <= git_version:
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700112 return True
113 if fail:
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900114 need = '.'.join(map(str, min_version))
Sarah Owenscecd1d82012-11-01 22:59:27 -0700115 print('fatal: git %s or later required' % need, file=sys.stderr)
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -0700116 sys.exit(1)
117 return False
118
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800119def _setenv(env, name, value):
120 env[name] = value.encode()
121
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700122class GitCommand(object):
123 def __init__(self,
124 project,
125 cmdv,
126 bare = False,
127 provide_stdin = False,
128 capture_stdout = False,
129 capture_stderr = False,
130 disable_editor = False,
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700131 ssh_proxy = False,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700132 cwd = None,
133 gitdir = None):
Shawn O. Pearce727ee982010-12-07 08:46:14 -0800134 env = os.environ.copy()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700135
David Pursehouse1d947b32012-10-25 12:23:11 +0900136 for key in [REPO_TRACE,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700137 GIT_DIR,
138 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
139 'GIT_OBJECT_DIRECTORY',
140 'GIT_WORK_TREE',
141 'GIT_GRAFT_FILE',
142 'GIT_INDEX_FILE']:
David Pursehouse1d947b32012-10-25 12:23:11 +0900143 if key in env:
144 del env[key]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700145
146 if disable_editor:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800147 _setenv(env, 'GIT_EDITOR', ':')
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700148 if ssh_proxy:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800149 _setenv(env, 'REPO_SSH_SOCK', ssh_sock())
150 _setenv(env, 'GIT_SSH', _ssh_proxy())
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700151 if 'http_proxy' in env and 'darwin' == sys.platform:
Shawn O. Pearce337aee02012-06-13 10:40:46 -0700152 s = "'http.proxy=%s'" % (env['http_proxy'],)
Shawn O. Pearce62d0b102012-06-05 15:11:15 -0700153 p = env.get('GIT_CONFIG_PARAMETERS')
154 if p is not None:
155 s = p + ' ' + s
156 _setenv(env, 'GIT_CONFIG_PARAMETERS', s)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700157
158 if project:
159 if not cwd:
160 cwd = project.worktree
161 if not gitdir:
162 gitdir = project.gitdir
163
164 command = [GIT]
165 if bare:
166 if gitdir:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800167 _setenv(env, GIT_DIR, gitdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700168 cwd = None
169 command.extend(cmdv)
170
171 if provide_stdin:
172 stdin = subprocess.PIPE
173 else:
174 stdin = None
175
176 if capture_stdout:
177 stdout = subprocess.PIPE
178 else:
179 stdout = None
180
181 if capture_stderr:
182 stderr = subprocess.PIPE
183 else:
184 stderr = None
185
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700186 if IsTrace():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700187 global LAST_CWD
188 global LAST_GITDIR
189
190 dbg = ''
191
192 if cwd and LAST_CWD != cwd:
193 if LAST_GITDIR or LAST_CWD:
194 dbg += '\n'
195 dbg += ': cd %s\n' % cwd
196 LAST_CWD = cwd
197
198 if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
199 if LAST_GITDIR or LAST_CWD:
200 dbg += '\n'
201 dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
202 LAST_GITDIR = env[GIT_DIR]
203
204 dbg += ': '
205 dbg += ' '.join(command)
206 if stdin == subprocess.PIPE:
207 dbg += ' 0<|'
208 if stdout == subprocess.PIPE:
209 dbg += ' 1>|'
210 if stderr == subprocess.PIPE:
211 dbg += ' 2>|'
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700212 Trace('%s', dbg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700213
214 try:
215 p = subprocess.Popen(command,
216 cwd = cwd,
217 env = env,
218 stdin = stdin,
219 stdout = stdout,
220 stderr = stderr)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700221 except Exception as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700222 raise GitError('%s: %s' % (command[1], e))
223
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700224 if ssh_proxy:
225 _add_ssh_client(p)
226
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700227 self.process = p
228 self.stdin = p.stdin
229
230 def Wait(self):
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700231 try:
Ulrik Sjölin498fe902011-09-11 22:59:37 +0200232 p = self.process
233 (self.stdout, self.stderr) = p.communicate()
234 rc = p.returncode
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700235 finally:
236 _remove_ssh_client(p)
237 return rc