blob: d6b46c873e88b33d400cce3f3cbc86ea6a478358 [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001#!/bin/sh
2
3## repo default configuration
4##
Shawn O. Pearce3f619502012-06-05 07:57:24 -07005REPO_URL='https://gerrit.googlesource.com/git-repo'
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07006REPO_REV='stable'
7
8# Copyright (C) 2008 Google Inc.
9#
10# Licensed under the Apache License, Version 2.0 (the "License");
11# you may not use this file except in compliance with the License.
12# You may obtain a copy of the License at
13#
14# http://www.apache.org/licenses/LICENSE-2.0
15#
16# Unless required by applicable law or agreed to in writing, software
17# distributed under the License is distributed on an "AS IS" BASIS,
18# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19# See the License for the specific language governing permissions and
20# limitations under the License.
21
22magic='--calling-python-from-/bin/sh--'
Shawn O. Pearce7542d662008-10-21 07:11:36 -070023"""exec" python -E "$0" "$@" """#$magic"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070024if __name__ == '__main__':
25 import sys
26 if sys.argv[-1] == '#%s' % magic:
27 del sys.argv[-1]
28del magic
29
30# increment this whenever we make important changes to this script
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -070031VERSION = (1, 17)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070032
33# increment this if the MAINTAINER_KEYS block is modified
34KEYRING_VERSION = (1,0)
35MAINTAINER_KEYS = """
36
37 Repo Maintainer <repo@android.kernel.org>
38-----BEGIN PGP PUBLIC KEY BLOCK-----
39Version: GnuPG v1.4.2.2 (GNU/Linux)
40
41mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
42WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+IXJDF5MJYcB8f22wAy15lUqPWi
43VCkk1l8qqLiuW0fo+ZkPY5qOgrvc0HW1SmdH649uNwqCbcKb6CxaTxzhOwCgj3AP
44xI1WfzLqdJjsm1Nq98L0cLcD/iNsILCuw44PRds3J75YP0pze7YF/6WFMB6QSFGu
45aUX1FsTTztKNXGms8i5b2l1B8JaLRWq/jOnZzyl1zrUJhkc0JgyZW5oNLGyWGhKD
46Fxp5YpHuIuMImopWEMFIRQNrvlg+YVK8t3FpdI1RY0LYqha8pPzANhEYgSfoVzOb
47fbfbA/4ioOrxy8ifSoga7ITyZMA+XbW8bx33WXutO9N7SPKS/AK2JpasSEVLZcON
48ae5hvAEGVXKxVPDjJBmIc2cOe7kOKSi3OxLzBqrjS2rnjiP4o0ekhZIe4+ocwVOg
49e0PLlH5avCqihGRhpoqDRsmpzSHzJIxtoeb+GgGEX8KkUsVAhbQpUmVwbyBNYWlu
50dGFpbmVyIDxyZXBvQGFuZHJvaWQua2VybmVsLm9yZz6IYAQTEQIAIAUCSPe6AQIb
51AwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEBZTDV6SD1xl1GEAn0x/OKQpy7qI
526G73NJviU0IUMtftAKCFMUhGb/0bZvQ8Rm3QCUpWHyEIu7kEDQRI97ogEBAA2wI6
535fs9y/rMwD6dkD/vK9v4C9mOn1IL5JCPYMJBVSci+9ED4ChzYvfq7wOcj9qIvaE0
54GwCt2ar7Q56me5J+byhSb32Rqsw/r3Vo5cZMH80N4cjesGuSXOGyEWTe4HYoxnHv
55gF4EKI2LK7xfTUcxMtlyn52sUpkfKsCpUhFvdmbAiJE+jCkQZr1Z8u2KphV79Ou+
56P1N5IXY/XWOlq48Qf4MWCYlJFrB07xjUjLKMPDNDnm58L5byDrP/eHysKexpbakL
57xCmYyfT6DV1SWLblpd2hie0sL3YejdtuBMYMS2rI7Yxb8kGuqkz+9l1qhwJtei94
585MaretDy/d/JH/pRYkRf7L+ke7dpzrP+aJmcz9P1e6gq4NJsWejaALVASBiioqNf
59QmtqSVzF1wkR5avZkFHuYvj6V/t1RrOZTXxkSk18KFMJRBZrdHFCWbc5qrVxUB6e
60N5pja0NFIUCigLBV1c6I2DwiuboMNh18VtJJh+nwWeez/RueN4ig59gRTtkcc0PR
6135tX2DR8+xCCFVW/NcJ4PSePYzCuuLvp1vEDHnj41R52Fz51hgddT4rBsp0nL+5I
62socSOIIezw8T9vVzMY4ArCKFAVu2IVyBcahTfBS8q5EM63mONU6UVJEozfGljiMw
63xuQ7JwKcw0AUEKTKG7aBgBaTAgT8TOevpvlw91cAAwUP/jRkyVi/0WAb0qlEaq/S
64ouWxX1faR+vU3b+Y2/DGjtXQMzG0qpetaTHC/AxxHpgt/dCkWI6ljYDnxgPLwG0a
65Oasm94BjZc6vZwf1opFZUKsjOAAxRxNZyjUJKe4UZVuMTk6zo27Nt3LMnc0FO47v
66FcOjRyquvgNOS818irVHUf12waDx8gszKxQTTtFxU5/ePB2jZmhP6oXSe4K/LG5T
67+WBRPDrHiGPhCzJRzm9BP0lTnGCAj3o9W90STZa65RK7IaYpC8TB35JTBEbrrNCp
68w6lzd74LnNEp5eMlKDnXzUAgAH0yzCQeMl7t33QCdYx2hRs2wtTQSjGfAiNmj/WW
69Vl5Jn+2jCDnRLenKHwVRFsBX2e0BiRWt/i9Y8fjorLCXVj4z+7yW6DawdLkJorEo
70p3v5ILwfC7hVx4jHSnOgZ65L9s8EQdVr1ckN9243yta7rNgwfcqb60ILMFF1BRk/
710V7wCL+68UwwiQDvyMOQuqkysKLSDCLb7BFcyA7j6KG+5hpsREstFX2wK1yKeraz
725xGrFy8tfAaeBMIQ17gvFSp/suc9DYO0ICK2BISzq+F+ZiAKsjMYOBNdH/h0zobQ
73HTHs37+/QLMomGEGKZMWi0dShU2J5mNRQu3Hhxl3hHDVbt5CeJBb26aQcQrFz69W
74zE3GNvmJosh6leayjtI9P2A6iEkEGBECAAkFAkj3uiACGwwACgkQFlMNXpIPXGWp
75TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2
76=CMiZ
77-----END PGP PUBLIC KEY BLOCK-----
78"""
79
80GIT = 'git' # our git command
81MIN_GIT_VERSION = (1, 5, 4) # minimum supported git version
82repodir = '.repo' # name of repo's private directory
83S_repo = 'repo' # special repo reposiory
84S_manifests = 'manifests' # special manifest repository
85REPO_MAIN = S_repo + '/main.py' # main script
86
87
88import optparse
89import os
90import re
91import readline
92import subprocess
93import sys
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070094import urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070095
96home_dot_repo = os.path.expanduser('~/.repoconfig')
97gpg_dir = os.path.join(home_dot_repo, 'gnupg')
98
99extra_args = []
100init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
101
102# Logging
103group = init_optparse.add_option_group('Logging options')
104group.add_option('-q', '--quiet',
105 dest="quiet", action="store_true", default=False,
106 help="be quiet")
107
108# Manifest
109group = init_optparse.add_option_group('Manifest options')
110group.add_option('-u', '--manifest-url',
111 dest='manifest_url',
112 help='manifest repository location', metavar='URL')
113group.add_option('-b', '--manifest-branch',
114 dest='manifest_branch',
115 help='manifest branch or revision', metavar='REVISION')
116group.add_option('-m', '--manifest-name',
117 dest='manifest_name',
118 help='initial manifest file', metavar='NAME.xml')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800119group.add_option('--mirror',
120 dest='mirror', action='store_true',
121 help='mirror the forrest')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200122group.add_option('--reference',
123 dest='reference',
124 help='location of mirror directory', metavar='DIR')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700125group.add_option('--depth', type='int', default=None,
126 dest='depth',
127 help='create a shallow clone with given depth; see git clone')
Colin Cross5acde752012-03-28 20:15:45 -0700128group.add_option('-g', '--groups',
Conley Owens971de8e2012-04-16 10:36:08 -0700129 dest='groups', default='default',
Colin Cross5acde752012-03-28 20:15:45 -0700130 help='restrict manifest projects to ones with a specified group',
131 metavar='GROUP')
Conley Owensd21720d2012-04-16 11:02:21 -0700132group.add_option('-p', '--platform',
133 dest='platform', default="auto",
134 help='restrict manifest projects to ones with a specified'
135 'platform group [auto|all|none|linux|darwin|...]',
136 metavar='PLATFORM')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700137
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700138
139# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700140group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700141group.add_option('--repo-url',
142 dest='repo_url',
143 help='repo repository location', metavar='URL')
144group.add_option('--repo-branch',
145 dest='repo_branch',
146 help='repo branch or revision', metavar='REVISION')
147group.add_option('--no-repo-verify',
148 dest='no_repo_verify', action='store_true',
149 help='do not verify repo source code')
150
Victor Boivie841be342011-04-05 11:31:10 +0200151# Other
152group = init_optparse.add_option_group('Other options')
153group.add_option('--config-name',
154 dest='config_name', action="store_true", default=False,
155 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700156
157class CloneFailure(Exception):
158 """Indicate the remote clone of repo itself failed.
159 """
160
161
162def _Init(args):
163 """Installs repo by cloning it over the network.
164 """
165 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800166 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700167 init_optparse.print_usage()
168 sys.exit(1)
169
170 url = opt.repo_url
171 if not url:
172 url = REPO_URL
173 extra_args.append('--repo-url=%s' % url)
174
175 branch = opt.repo_branch
176 if not branch:
177 branch = REPO_REV
178 extra_args.append('--repo-branch=%s' % branch)
179
180 if branch.startswith('refs/heads/'):
181 branch = branch[len('refs/heads/'):]
182 if branch.startswith('refs/'):
183 print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
184 raise CloneFailure()
185
186 if not os.path.isdir(repodir):
187 try:
188 os.mkdir(repodir)
189 except OSError, e:
190 print >>sys.stderr, \
191 'fatal: cannot make %s directory: %s' % (
192 repodir, e.strerror)
193 # Don't faise CloneFailure; that would delete the
194 # name. Instead exit immediately.
195 #
196 sys.exit(1)
197
198 _CheckGitVersion()
199 try:
200 if _NeedSetupGnuPG():
201 can_verify = _SetupGnuPG(opt.quiet)
202 else:
203 can_verify = True
204
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700205 dst = os.path.abspath(os.path.join(repodir, S_repo))
206 _Clone(url, dst, opt.quiet)
207
208 if can_verify and not opt.no_repo_verify:
209 rev = _Verify(dst, branch, opt.quiet)
210 else:
211 rev = 'refs/remotes/origin/%s^0' % branch
212
213 _Checkout(dst, branch, rev, opt.quiet)
214 except CloneFailure:
215 if opt.quiet:
216 print >>sys.stderr, \
217 'fatal: repo init failed; run without --quiet to see why'
218 raise
219
220
221def _CheckGitVersion():
222 cmd = [GIT, '--version']
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700223 try:
224 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
225 except OSError, e:
226 print >>sys.stderr
227 print >>sys.stderr, "fatal: '%s' is not available" % GIT
228 print >>sys.stderr, 'fatal: %s' % e
229 print >>sys.stderr
230 print >>sys.stderr, 'Please make sure %s is installed'\
231 ' and in your path.' % GIT
232 raise CloneFailure()
233
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700234 ver_str = proc.stdout.read().strip()
235 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700236 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700237
238 if not ver_str.startswith('git version '):
239 print >>sys.stderr, 'error: "%s" unsupported' % ver_str
240 raise CloneFailure()
241
242 ver_str = ver_str[len('git version '):].strip()
243 ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
244 if ver_act < MIN_GIT_VERSION:
245 need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
246 print >>sys.stderr, 'fatal: git %s or later required' % need
247 raise CloneFailure()
248
249
250def _NeedSetupGnuPG():
251 if not os.path.isdir(home_dot_repo):
252 return True
253
254 kv = os.path.join(home_dot_repo, 'keyring-version')
255 if not os.path.exists(kv):
256 return True
257
258 kv = open(kv).read()
259 if not kv:
260 return True
261
262 kv = tuple(map(lambda x: int(x), kv.split('.')))
263 if kv < KEYRING_VERSION:
264 return True
265 return False
266
267
268def _SetupGnuPG(quiet):
269 if not os.path.isdir(home_dot_repo):
270 try:
271 os.mkdir(home_dot_repo)
272 except OSError, e:
273 print >>sys.stderr, \
274 'fatal: cannot make %s directory: %s' % (
275 home_dot_repo, e.strerror)
276 sys.exit(1)
277
278 if not os.path.isdir(gpg_dir):
279 try:
280 os.mkdir(gpg_dir, 0700)
281 except OSError, e:
282 print >>sys.stderr, \
283 'fatal: cannot make %s directory: %s' % (
284 gpg_dir, e.strerror)
285 sys.exit(1)
286
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800287 env = os.environ.copy()
288 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700289
290 cmd = ['gpg', '--import']
291 try:
292 proc = subprocess.Popen(cmd,
293 env = env,
294 stdin = subprocess.PIPE)
295 except OSError, e:
296 if not quiet:
297 print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
298 print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
299 print >>sys.stderr
300 return False
301
302 proc.stdin.write(MAINTAINER_KEYS)
303 proc.stdin.close()
304
305 if proc.wait() != 0:
306 print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
307 sys.exit(1)
308 print
309
310 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
311 fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
312 fd.close()
313 return True
314
315
316def _SetConfig(local, name, value):
317 """Set a git configuration option to the specified value.
318 """
319 cmd = [GIT, 'config', name, value]
320 if subprocess.Popen(cmd, cwd = local).wait() != 0:
321 raise CloneFailure()
322
323
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700324def _InitHttp():
325 handlers = []
326
327 mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
328 try:
329 import netrc
330 n = netrc.netrc()
331 for host in n.hosts:
332 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800333 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
334 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700335 except:
336 pass
337 handlers.append(urllib2.HTTPBasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800338 handlers.append(urllib2.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700339
340 if 'http_proxy' in os.environ:
341 url = os.environ['http_proxy']
342 handlers.append(urllib2.ProxyHandler({'http': url, 'https': url}))
343 if 'REPO_CURL_VERBOSE' in os.environ:
344 handlers.append(urllib2.HTTPHandler(debuglevel=1))
345 handlers.append(urllib2.HTTPSHandler(debuglevel=1))
346 urllib2.install_opener(urllib2.build_opener(*handlers))
347
348def _Fetch(url, local, src, quiet):
349 if not quiet:
350 print >>sys.stderr, 'Get %s' % url
351
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700352 cmd = [GIT, 'fetch']
353 if quiet:
354 cmd.append('--quiet')
355 err = subprocess.PIPE
356 else:
357 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700358 cmd.append(src)
359 cmd.append('+refs/heads/*:refs/remotes/origin/*')
360 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700361
362 proc = subprocess.Popen(cmd, cwd = local, stderr = err)
363 if err:
364 proc.stderr.read()
365 proc.stderr.close()
366 if proc.wait() != 0:
367 raise CloneFailure()
368
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700369def _DownloadBundle(url, local, quiet):
370 if not url.endswith('/'):
371 url += '/'
372 url += 'clone.bundle'
373
374 proc = subprocess.Popen(
375 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
376 cwd = local,
377 stdout = subprocess.PIPE)
378 for line in proc.stdout:
379 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
380 if m:
381 new_url = m.group(1)
382 old_url = m.group(2)
383 if url.startswith(old_url):
384 url = new_url + url[len(old_url):]
385 break
386 proc.stdout.close()
387 proc.wait()
388
389 if not url.startswith('http:') and not url.startswith('https:'):
390 return False
391
392 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
393 try:
394 try:
395 r = urllib2.urlopen(url)
396 except urllib2.HTTPError, e:
397 if e.code == 404:
398 return False
399 print >>sys.stderr, 'fatal: Cannot get %s' % url
400 print >>sys.stderr, 'fatal: HTTP error %s' % e.code
401 raise CloneFailure()
402 except urllib2.URLError, e:
403 print >>sys.stderr, 'fatal: Cannot get %s' % url
404 print >>sys.stderr, 'fatal: error %s' % e.reason
405 raise CloneFailure()
406 try:
407 if not quiet:
408 print >>sys.stderr, 'Get %s' % url
409 while True:
410 buf = r.read(8192)
411 if buf == '':
412 return True
413 dest.write(buf)
414 finally:
415 r.close()
416 finally:
417 dest.close()
418
419def _ImportBundle(local):
420 path = os.path.join(local, '.git', 'clone.bundle')
421 try:
422 _Fetch(local, local, path, True)
423 finally:
424 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700425
426def _Clone(url, local, quiet):
427 """Clones a git repository to a new subdirectory of repodir
428 """
429 try:
430 os.mkdir(local)
431 except OSError, e:
432 print >>sys.stderr, \
433 'fatal: cannot make %s directory: %s' \
434 % (local, e.strerror)
435 raise CloneFailure()
436
437 cmd = [GIT, 'init', '--quiet']
438 try:
439 proc = subprocess.Popen(cmd, cwd = local)
440 except OSError, e:
441 print >>sys.stderr
442 print >>sys.stderr, "fatal: '%s' is not available" % GIT
443 print >>sys.stderr, 'fatal: %s' % e
444 print >>sys.stderr
445 print >>sys.stderr, 'Please make sure %s is installed'\
446 ' and in your path.' % GIT
447 raise CloneFailure()
448 if proc.wait() != 0:
449 print >>sys.stderr, 'fatal: could not create %s' % local
450 raise CloneFailure()
451
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700452 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700453 _SetConfig(local, 'remote.origin.url', url)
454 _SetConfig(local, 'remote.origin.fetch',
455 '+refs/heads/*:refs/remotes/origin/*')
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700456 if _DownloadBundle(url, local, quiet):
457 _ImportBundle(local)
458 else:
459 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700460
461
462def _Verify(cwd, branch, quiet):
463 """Verify the branch has been signed by a tag.
464 """
465 cmd = [GIT, 'describe', 'origin/%s' % branch]
466 proc = subprocess.Popen(cmd,
467 stdout=subprocess.PIPE,
468 stderr=subprocess.PIPE,
469 cwd = cwd)
470 cur = proc.stdout.read().strip()
471 proc.stdout.close()
472
473 proc.stderr.read()
474 proc.stderr.close()
475
476 if proc.wait() != 0 or not cur:
477 print >>sys.stderr
478 print >>sys.stderr,\
479 "fatal: branch '%s' has not been signed" \
480 % branch
481 raise CloneFailure()
482
483 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
484 if m:
485 cur = m.group(1)
486 if not quiet:
487 print >>sys.stderr
488 print >>sys.stderr, \
489 "info: Ignoring branch '%s'; using tagged release '%s'" \
490 % (branch, cur)
491 print >>sys.stderr
492
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800493 env = os.environ.copy()
494 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700495
496 cmd = [GIT, 'tag', '-v', cur]
497 proc = subprocess.Popen(cmd,
498 stdout = subprocess.PIPE,
499 stderr = subprocess.PIPE,
500 cwd = cwd,
501 env = env)
502 out = proc.stdout.read()
503 proc.stdout.close()
504
505 err = proc.stderr.read()
506 proc.stderr.close()
507
508 if proc.wait() != 0:
509 print >>sys.stderr
510 print >>sys.stderr, out
511 print >>sys.stderr, err
512 print >>sys.stderr
513 raise CloneFailure()
514 return '%s^0' % cur
515
516
517def _Checkout(cwd, branch, rev, quiet):
518 """Checkout an upstream branch into the repository and track it.
519 """
520 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
521 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
522 raise CloneFailure()
523
524 _SetConfig(cwd, 'branch.default.remote', 'origin')
525 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
526
527 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
528 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
529 raise CloneFailure()
530
531 cmd = [GIT, 'read-tree', '--reset', '-u']
532 if not quiet:
533 cmd.append('-v')
534 cmd.append('HEAD')
535 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
536 raise CloneFailure()
537
538
539def _FindRepo():
540 """Look for a repo installation, starting at the current directory.
541 """
542 dir = os.getcwd()
543 repo = None
544
Anthony Newnamdf14a702011-01-09 17:31:57 -0800545 olddir = None
546 while dir != '/' \
547 and dir != olddir \
548 and not repo:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700549 repo = os.path.join(dir, repodir, REPO_MAIN)
550 if not os.path.isfile(repo):
551 repo = None
Anthony Newnamdf14a702011-01-09 17:31:57 -0800552 olddir = dir
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700553 dir = os.path.dirname(dir)
554 return (repo, os.path.join(dir, repodir))
555
556
557class _Options:
558 help = False
559
560
561def _ParseArguments(args):
562 cmd = None
563 opt = _Options()
564 arg = []
565
566 for i in xrange(0, len(args)):
567 a = args[i]
568 if a == '-h' or a == '--help':
569 opt.help = True
570
571 elif not a.startswith('-'):
572 cmd = a
573 arg = args[i + 1:]
574 break
575 return cmd, opt, arg
576
577
578def _Usage():
579 print >>sys.stderr,\
580"""usage: repo COMMAND [ARGS]
581
582repo is not yet installed. Use "repo init" to install it here.
583
584The most commonly used repo commands are:
585
586 init Install repo in the current working directory
587 help Display detailed help on a command
588
589For access to the full online help, install repo ("repo init").
590"""
591 sys.exit(1)
592
593
594def _Help(args):
595 if args:
596 if args[0] == 'init':
597 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100598 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700599 else:
600 print >>sys.stderr,\
601 "error: '%s' is not a bootstrap command.\n"\
602 ' For access to online help, install repo ("repo init").'\
603 % args[0]
604 else:
605 _Usage()
606 sys.exit(1)
607
608
609def _NotInstalled():
610 print >>sys.stderr,\
611'error: repo is not installed. Use "repo init" to install it here.'
612 sys.exit(1)
613
614
615def _NoCommands(cmd):
616 print >>sys.stderr,\
617"""error: command '%s' requires repo to be installed first.
618 Use "repo init" to install it here.""" % cmd
619 sys.exit(1)
620
621
622def _RunSelf(wrapper_path):
623 my_dir = os.path.dirname(wrapper_path)
624 my_main = os.path.join(my_dir, 'main.py')
625 my_git = os.path.join(my_dir, '.git')
626
627 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700628 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700629 'project.py',
630 'subcmds']:
631 if not os.path.exists(os.path.join(my_dir, name)):
632 return None, None
633 return my_main, my_git
634 return None, None
635
636
637def _SetDefaultsTo(gitdir):
638 global REPO_URL
639 global REPO_REV
640
641 REPO_URL = gitdir
642 proc = subprocess.Popen([GIT,
643 '--git-dir=%s' % gitdir,
644 'symbolic-ref',
645 'HEAD'],
646 stdout = subprocess.PIPE,
647 stderr = subprocess.PIPE)
648 REPO_REV = proc.stdout.read().strip()
649 proc.stdout.close()
650
651 proc.stderr.read()
652 proc.stderr.close()
653
654 if proc.wait() != 0:
655 print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
656 sys.exit(1)
657
658
659def main(orig_args):
660 main, dir = _FindRepo()
661 cmd, opt, args = _ParseArguments(orig_args)
662
663 wrapper_path = os.path.abspath(__file__)
664 my_main, my_git = _RunSelf(wrapper_path)
665
666 if not main:
667 if opt.help:
668 _Usage()
669 if cmd == 'help':
670 _Help(args)
671 if not cmd:
672 _NotInstalled()
673 if cmd == 'init':
674 if my_git:
675 _SetDefaultsTo(my_git)
676 try:
677 _Init(args)
678 except CloneFailure:
679 for root, dirs, files in os.walk(repodir, topdown=False):
680 for name in files:
681 os.remove(os.path.join(root, name))
682 for name in dirs:
683 os.rmdir(os.path.join(root, name))
684 os.rmdir(repodir)
685 sys.exit(1)
686 main, dir = _FindRepo()
687 else:
688 _NoCommands(cmd)
689
690 if my_main:
691 main = my_main
692
693 ver_str = '.'.join(map(lambda x: str(x), VERSION))
694 me = [main,
695 '--repo-dir=%s' % dir,
696 '--wrapper-version=%s' % ver_str,
697 '--wrapper-path=%s' % wrapper_path,
698 '--']
699 me.extend(orig_args)
700 me.extend(extra_args)
701 try:
702 os.execv(main, me)
703 except OSError, e:
704 print >>sys.stderr, "fatal: unable to start %s" % main
705 print >>sys.stderr, "fatal: %s" % e
706 sys.exit(148)
707
708
709if __name__ == '__main__':
710 main(sys.argv[1:])