blob: 513b9ebf7f52c3d450cba101ef97533ac9678175 [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
16import os
17import sys
18import subprocess
Shawn O. Pearcefb231612009-04-10 18:53:46 -070019import tempfile
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070020from signal import SIGTERM
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070021from error import GitError
Shawn O. Pearcead3193a2009-04-18 09:54:51 -070022from trace import REPO_TRACE, IsTrace, Trace
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070023
24GIT = 'git'
25MIN_GIT_VERSION = (1, 5, 4)
26GIT_DIR = 'GIT_DIR'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070027
28LAST_GITDIR = None
29LAST_CWD = None
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070030
Shawn O. Pearcefb231612009-04-10 18:53:46 -070031_ssh_proxy_path = None
32_ssh_sock_path = None
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070033_ssh_clients = []
Shawn O. Pearcefb231612009-04-10 18:53:46 -070034
Nico Sallembien1c85f4e2010-04-27 14:35:27 -070035def ssh_sock(create=True):
Shawn O. Pearcefb231612009-04-10 18:53:46 -070036 global _ssh_sock_path
37 if _ssh_sock_path is None:
38 if not create:
39 return None
Shawn O. Pearced63bbf42009-04-21 08:05:27 -070040 dir = '/tmp'
41 if not os.path.exists(dir):
42 dir = tempfile.gettempdir()
Shawn O. Pearcefb231612009-04-10 18:53:46 -070043 _ssh_sock_path = os.path.join(
Shawn O. Pearced63bbf42009-04-21 08:05:27 -070044 tempfile.mkdtemp('', 'ssh-', dir),
Shawn O. Pearcefb231612009-04-10 18:53:46 -070045 'master-%r@%h:%p')
46 return _ssh_sock_path
47
48def _ssh_proxy():
49 global _ssh_proxy_path
50 if _ssh_proxy_path is None:
51 _ssh_proxy_path = os.path.join(
52 os.path.dirname(__file__),
53 'git_ssh')
54 return _ssh_proxy_path
55
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -070056def _add_ssh_client(p):
57 _ssh_clients.append(p)
58
59def _remove_ssh_client(p):
60 try:
61 _ssh_clients.remove(p)
62 except ValueError:
63 pass
64
65def terminate_ssh_clients():
66 global _ssh_clients
67 for p in _ssh_clients:
68 try:
69 os.kill(p.pid, SIGTERM)
70 p.wait()
71 except OSError:
72 pass
73 _ssh_clients = []
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070074
75class _GitCall(object):
76 def version(self):
77 p = GitCommand(None, ['--version'], capture_stdout=True)
78 if p.Wait() == 0:
79 return p.stdout
80 return None
81
82 def __getattr__(self, name):
83 name = name.replace('_','-')
84 def fun(*cmdv):
85 command = [name]
86 command.extend(cmdv)
87 return GitCommand(None, command).Wait() == 0
88 return fun
89git = _GitCall()
90
Shawn O. Pearce2ec00b92009-06-12 09:32:50 -070091_git_version = None
92
93def git_require(min_version, fail=False):
94 global _git_version
95
96 if _git_version is None:
97 ver_str = git.version()
98 if ver_str.startswith('git version '):
99 _git_version = tuple(
100 map(lambda x: int(x),
101 ver_str[len('git version '):].strip().split('.')[0:3]
102 ))
103 else:
104 print >>sys.stderr, 'fatal: "%s" unsupported' % ver_str
105 sys.exit(1)
106
107 if min_version <= _git_version:
108 return True
109 if fail:
110 need = '.'.join(map(lambda x: str(x), min_version))
111 print >>sys.stderr, 'fatal: git %s or later required' % need
112 sys.exit(1)
113 return False
114
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800115def _setenv(env, name, value):
116 env[name] = value.encode()
117
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700118class GitCommand(object):
119 def __init__(self,
120 project,
121 cmdv,
122 bare = False,
123 provide_stdin = False,
124 capture_stdout = False,
125 capture_stderr = False,
126 disable_editor = False,
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700127 ssh_proxy = False,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700128 cwd = None,
129 gitdir = None):
Shawn O. Pearce727ee982010-12-07 08:46:14 -0800130 env = os.environ.copy()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700131
132 for e in [REPO_TRACE,
133 GIT_DIR,
134 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
135 'GIT_OBJECT_DIRECTORY',
136 'GIT_WORK_TREE',
137 'GIT_GRAFT_FILE',
138 'GIT_INDEX_FILE']:
139 if e in env:
140 del env[e]
141
142 if disable_editor:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800143 _setenv(env, 'GIT_EDITOR', ':')
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700144 if ssh_proxy:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800145 _setenv(env, 'REPO_SSH_SOCK', ssh_sock())
146 _setenv(env, 'GIT_SSH', _ssh_proxy())
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700147
148 if project:
149 if not cwd:
150 cwd = project.worktree
151 if not gitdir:
152 gitdir = project.gitdir
153
154 command = [GIT]
155 if bare:
156 if gitdir:
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800157 _setenv(env, GIT_DIR, gitdir)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700158 cwd = None
159 command.extend(cmdv)
160
161 if provide_stdin:
162 stdin = subprocess.PIPE
163 else:
164 stdin = None
165
166 if capture_stdout:
167 stdout = subprocess.PIPE
168 else:
169 stdout = None
170
171 if capture_stderr:
172 stderr = subprocess.PIPE
173 else:
174 stderr = None
175
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700176 if IsTrace():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700177 global LAST_CWD
178 global LAST_GITDIR
179
180 dbg = ''
181
182 if cwd and LAST_CWD != cwd:
183 if LAST_GITDIR or LAST_CWD:
184 dbg += '\n'
185 dbg += ': cd %s\n' % cwd
186 LAST_CWD = cwd
187
188 if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
189 if LAST_GITDIR or LAST_CWD:
190 dbg += '\n'
191 dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
192 LAST_GITDIR = env[GIT_DIR]
193
194 dbg += ': '
195 dbg += ' '.join(command)
196 if stdin == subprocess.PIPE:
197 dbg += ' 0<|'
198 if stdout == subprocess.PIPE:
199 dbg += ' 1>|'
200 if stderr == subprocess.PIPE:
201 dbg += ' 2>|'
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700202 Trace('%s', dbg)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700203
204 try:
205 p = subprocess.Popen(command,
206 cwd = cwd,
207 env = env,
208 stdin = stdin,
209 stdout = stdout,
210 stderr = stderr)
211 except Exception, e:
212 raise GitError('%s: %s' % (command[1], e))
213
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700214 if ssh_proxy:
215 _add_ssh_client(p)
216
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700217 self.process = p
218 self.stdin = p.stdin
219
220 def Wait(self):
221 p = self.process
222
223 if p.stdin:
224 p.stdin.close()
225 self.stdin = None
226
227 if p.stdout:
228 self.stdout = p.stdout.read()
229 p.stdout.close()
230 else:
231 p.stdout = None
232
233 if p.stderr:
234 self.stderr = p.stderr.read()
235 p.stderr.close()
236 else:
237 p.stderr = None
238
Shawn O. Pearceca8c32c2010-05-11 18:21:33 -0700239 try:
240 rc = p.wait()
241 finally:
242 _remove_ssh_client(p)
243 return rc