blob: 860a15d5e84b2957bcc3e6744610a8acc92dd7e0 [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001#!/bin/sh
2
3## repo default configuration
4##
Shawn O. Pearce44da16e2011-09-05 14:02:38 -07005REPO_URL='https://code.google.com/p/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
Conley Owens971de8e2012-04-16 10:36:08 -070031VERSION = (1, 16)
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']
223 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
224 ver_str = proc.stdout.read().strip()
225 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700226 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700227
228 if not ver_str.startswith('git version '):
229 print >>sys.stderr, 'error: "%s" unsupported' % ver_str
230 raise CloneFailure()
231
232 ver_str = ver_str[len('git version '):].strip()
233 ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
234 if ver_act < MIN_GIT_VERSION:
235 need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
236 print >>sys.stderr, 'fatal: git %s or later required' % need
237 raise CloneFailure()
238
239
240def _NeedSetupGnuPG():
241 if not os.path.isdir(home_dot_repo):
242 return True
243
244 kv = os.path.join(home_dot_repo, 'keyring-version')
245 if not os.path.exists(kv):
246 return True
247
248 kv = open(kv).read()
249 if not kv:
250 return True
251
252 kv = tuple(map(lambda x: int(x), kv.split('.')))
253 if kv < KEYRING_VERSION:
254 return True
255 return False
256
257
258def _SetupGnuPG(quiet):
259 if not os.path.isdir(home_dot_repo):
260 try:
261 os.mkdir(home_dot_repo)
262 except OSError, e:
263 print >>sys.stderr, \
264 'fatal: cannot make %s directory: %s' % (
265 home_dot_repo, e.strerror)
266 sys.exit(1)
267
268 if not os.path.isdir(gpg_dir):
269 try:
270 os.mkdir(gpg_dir, 0700)
271 except OSError, e:
272 print >>sys.stderr, \
273 'fatal: cannot make %s directory: %s' % (
274 gpg_dir, e.strerror)
275 sys.exit(1)
276
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800277 env = os.environ.copy()
278 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700279
280 cmd = ['gpg', '--import']
281 try:
282 proc = subprocess.Popen(cmd,
283 env = env,
284 stdin = subprocess.PIPE)
285 except OSError, e:
286 if not quiet:
287 print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
288 print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
289 print >>sys.stderr
290 return False
291
292 proc.stdin.write(MAINTAINER_KEYS)
293 proc.stdin.close()
294
295 if proc.wait() != 0:
296 print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
297 sys.exit(1)
298 print
299
300 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
301 fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
302 fd.close()
303 return True
304
305
306def _SetConfig(local, name, value):
307 """Set a git configuration option to the specified value.
308 """
309 cmd = [GIT, 'config', name, value]
310 if subprocess.Popen(cmd, cwd = local).wait() != 0:
311 raise CloneFailure()
312
313
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700314def _InitHttp():
315 handlers = []
316
317 mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
318 try:
319 import netrc
320 n = netrc.netrc()
321 for host in n.hosts:
322 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800323 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
324 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700325 except:
326 pass
327 handlers.append(urllib2.HTTPBasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800328 handlers.append(urllib2.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700329
330 if 'http_proxy' in os.environ:
331 url = os.environ['http_proxy']
332 handlers.append(urllib2.ProxyHandler({'http': url, 'https': url}))
333 if 'REPO_CURL_VERBOSE' in os.environ:
334 handlers.append(urllib2.HTTPHandler(debuglevel=1))
335 handlers.append(urllib2.HTTPSHandler(debuglevel=1))
336 urllib2.install_opener(urllib2.build_opener(*handlers))
337
338def _Fetch(url, local, src, quiet):
339 if not quiet:
340 print >>sys.stderr, 'Get %s' % url
341
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700342 cmd = [GIT, 'fetch']
343 if quiet:
344 cmd.append('--quiet')
345 err = subprocess.PIPE
346 else:
347 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700348 cmd.append(src)
349 cmd.append('+refs/heads/*:refs/remotes/origin/*')
350 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700351
352 proc = subprocess.Popen(cmd, cwd = local, stderr = err)
353 if err:
354 proc.stderr.read()
355 proc.stderr.close()
356 if proc.wait() != 0:
357 raise CloneFailure()
358
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700359def _DownloadBundle(url, local, quiet):
360 if not url.endswith('/'):
361 url += '/'
362 url += 'clone.bundle'
363
364 proc = subprocess.Popen(
365 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
366 cwd = local,
367 stdout = subprocess.PIPE)
368 for line in proc.stdout:
369 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
370 if m:
371 new_url = m.group(1)
372 old_url = m.group(2)
373 if url.startswith(old_url):
374 url = new_url + url[len(old_url):]
375 break
376 proc.stdout.close()
377 proc.wait()
378
379 if not url.startswith('http:') and not url.startswith('https:'):
380 return False
381
382 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
383 try:
384 try:
385 r = urllib2.urlopen(url)
386 except urllib2.HTTPError, e:
387 if e.code == 404:
388 return False
389 print >>sys.stderr, 'fatal: Cannot get %s' % url
390 print >>sys.stderr, 'fatal: HTTP error %s' % e.code
391 raise CloneFailure()
392 except urllib2.URLError, e:
393 print >>sys.stderr, 'fatal: Cannot get %s' % url
394 print >>sys.stderr, 'fatal: error %s' % e.reason
395 raise CloneFailure()
396 try:
397 if not quiet:
398 print >>sys.stderr, 'Get %s' % url
399 while True:
400 buf = r.read(8192)
401 if buf == '':
402 return True
403 dest.write(buf)
404 finally:
405 r.close()
406 finally:
407 dest.close()
408
409def _ImportBundle(local):
410 path = os.path.join(local, '.git', 'clone.bundle')
411 try:
412 _Fetch(local, local, path, True)
413 finally:
414 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700415
416def _Clone(url, local, quiet):
417 """Clones a git repository to a new subdirectory of repodir
418 """
419 try:
420 os.mkdir(local)
421 except OSError, e:
422 print >>sys.stderr, \
423 'fatal: cannot make %s directory: %s' \
424 % (local, e.strerror)
425 raise CloneFailure()
426
427 cmd = [GIT, 'init', '--quiet']
428 try:
429 proc = subprocess.Popen(cmd, cwd = local)
430 except OSError, e:
431 print >>sys.stderr
432 print >>sys.stderr, "fatal: '%s' is not available" % GIT
433 print >>sys.stderr, 'fatal: %s' % e
434 print >>sys.stderr
435 print >>sys.stderr, 'Please make sure %s is installed'\
436 ' and in your path.' % GIT
437 raise CloneFailure()
438 if proc.wait() != 0:
439 print >>sys.stderr, 'fatal: could not create %s' % local
440 raise CloneFailure()
441
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700442 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700443 _SetConfig(local, 'remote.origin.url', url)
444 _SetConfig(local, 'remote.origin.fetch',
445 '+refs/heads/*:refs/remotes/origin/*')
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700446 if _DownloadBundle(url, local, quiet):
447 _ImportBundle(local)
448 else:
449 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700450
451
452def _Verify(cwd, branch, quiet):
453 """Verify the branch has been signed by a tag.
454 """
455 cmd = [GIT, 'describe', 'origin/%s' % branch]
456 proc = subprocess.Popen(cmd,
457 stdout=subprocess.PIPE,
458 stderr=subprocess.PIPE,
459 cwd = cwd)
460 cur = proc.stdout.read().strip()
461 proc.stdout.close()
462
463 proc.stderr.read()
464 proc.stderr.close()
465
466 if proc.wait() != 0 or not cur:
467 print >>sys.stderr
468 print >>sys.stderr,\
469 "fatal: branch '%s' has not been signed" \
470 % branch
471 raise CloneFailure()
472
473 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
474 if m:
475 cur = m.group(1)
476 if not quiet:
477 print >>sys.stderr
478 print >>sys.stderr, \
479 "info: Ignoring branch '%s'; using tagged release '%s'" \
480 % (branch, cur)
481 print >>sys.stderr
482
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800483 env = os.environ.copy()
484 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700485
486 cmd = [GIT, 'tag', '-v', cur]
487 proc = subprocess.Popen(cmd,
488 stdout = subprocess.PIPE,
489 stderr = subprocess.PIPE,
490 cwd = cwd,
491 env = env)
492 out = proc.stdout.read()
493 proc.stdout.close()
494
495 err = proc.stderr.read()
496 proc.stderr.close()
497
498 if proc.wait() != 0:
499 print >>sys.stderr
500 print >>sys.stderr, out
501 print >>sys.stderr, err
502 print >>sys.stderr
503 raise CloneFailure()
504 return '%s^0' % cur
505
506
507def _Checkout(cwd, branch, rev, quiet):
508 """Checkout an upstream branch into the repository and track it.
509 """
510 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
511 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
512 raise CloneFailure()
513
514 _SetConfig(cwd, 'branch.default.remote', 'origin')
515 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
516
517 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
518 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
519 raise CloneFailure()
520
521 cmd = [GIT, 'read-tree', '--reset', '-u']
522 if not quiet:
523 cmd.append('-v')
524 cmd.append('HEAD')
525 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
526 raise CloneFailure()
527
528
529def _FindRepo():
530 """Look for a repo installation, starting at the current directory.
531 """
532 dir = os.getcwd()
533 repo = None
534
Anthony Newnamdf14a702011-01-09 17:31:57 -0800535 olddir = None
536 while dir != '/' \
537 and dir != olddir \
538 and not repo:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700539 repo = os.path.join(dir, repodir, REPO_MAIN)
540 if not os.path.isfile(repo):
541 repo = None
Anthony Newnamdf14a702011-01-09 17:31:57 -0800542 olddir = dir
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700543 dir = os.path.dirname(dir)
544 return (repo, os.path.join(dir, repodir))
545
546
547class _Options:
548 help = False
549
550
551def _ParseArguments(args):
552 cmd = None
553 opt = _Options()
554 arg = []
555
556 for i in xrange(0, len(args)):
557 a = args[i]
558 if a == '-h' or a == '--help':
559 opt.help = True
560
561 elif not a.startswith('-'):
562 cmd = a
563 arg = args[i + 1:]
564 break
565 return cmd, opt, arg
566
567
568def _Usage():
569 print >>sys.stderr,\
570"""usage: repo COMMAND [ARGS]
571
572repo is not yet installed. Use "repo init" to install it here.
573
574The most commonly used repo commands are:
575
576 init Install repo in the current working directory
577 help Display detailed help on a command
578
579For access to the full online help, install repo ("repo init").
580"""
581 sys.exit(1)
582
583
584def _Help(args):
585 if args:
586 if args[0] == 'init':
587 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100588 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700589 else:
590 print >>sys.stderr,\
591 "error: '%s' is not a bootstrap command.\n"\
592 ' For access to online help, install repo ("repo init").'\
593 % args[0]
594 else:
595 _Usage()
596 sys.exit(1)
597
598
599def _NotInstalled():
600 print >>sys.stderr,\
601'error: repo is not installed. Use "repo init" to install it here.'
602 sys.exit(1)
603
604
605def _NoCommands(cmd):
606 print >>sys.stderr,\
607"""error: command '%s' requires repo to be installed first.
608 Use "repo init" to install it here.""" % cmd
609 sys.exit(1)
610
611
612def _RunSelf(wrapper_path):
613 my_dir = os.path.dirname(wrapper_path)
614 my_main = os.path.join(my_dir, 'main.py')
615 my_git = os.path.join(my_dir, '.git')
616
617 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700618 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700619 'project.py',
620 'subcmds']:
621 if not os.path.exists(os.path.join(my_dir, name)):
622 return None, None
623 return my_main, my_git
624 return None, None
625
626
627def _SetDefaultsTo(gitdir):
628 global REPO_URL
629 global REPO_REV
630
631 REPO_URL = gitdir
632 proc = subprocess.Popen([GIT,
633 '--git-dir=%s' % gitdir,
634 'symbolic-ref',
635 'HEAD'],
636 stdout = subprocess.PIPE,
637 stderr = subprocess.PIPE)
638 REPO_REV = proc.stdout.read().strip()
639 proc.stdout.close()
640
641 proc.stderr.read()
642 proc.stderr.close()
643
644 if proc.wait() != 0:
645 print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
646 sys.exit(1)
647
648
649def main(orig_args):
650 main, dir = _FindRepo()
651 cmd, opt, args = _ParseArguments(orig_args)
652
653 wrapper_path = os.path.abspath(__file__)
654 my_main, my_git = _RunSelf(wrapper_path)
655
656 if not main:
657 if opt.help:
658 _Usage()
659 if cmd == 'help':
660 _Help(args)
661 if not cmd:
662 _NotInstalled()
663 if cmd == 'init':
664 if my_git:
665 _SetDefaultsTo(my_git)
666 try:
667 _Init(args)
668 except CloneFailure:
669 for root, dirs, files in os.walk(repodir, topdown=False):
670 for name in files:
671 os.remove(os.path.join(root, name))
672 for name in dirs:
673 os.rmdir(os.path.join(root, name))
674 os.rmdir(repodir)
675 sys.exit(1)
676 main, dir = _FindRepo()
677 else:
678 _NoCommands(cmd)
679
680 if my_main:
681 main = my_main
682
683 ver_str = '.'.join(map(lambda x: str(x), VERSION))
684 me = [main,
685 '--repo-dir=%s' % dir,
686 '--wrapper-version=%s' % ver_str,
687 '--wrapper-path=%s' % wrapper_path,
688 '--']
689 me.extend(orig_args)
690 me.extend(extra_args)
691 try:
692 os.execv(main, me)
693 except OSError, e:
694 print >>sys.stderr, "fatal: unable to start %s" % main
695 print >>sys.stderr, "fatal: %s" % e
696 sys.exit(148)
697
698
699if __name__ == '__main__':
700 main(sys.argv[1:])