blob: 7c633fc3728962341de299bcf90d9ef35dd56260 [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
Conley Owensc5aa4d32012-10-26 11:34:11 -070031VERSION = (1, 19)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070032
33# increment this if the MAINTAINER_KEYS block is modified
Conley Owens55e4d462012-10-01 16:12:28 -070034KEYRING_VERSION = (1,1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070035MAINTAINER_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+ZkPY5qOg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IC KEY BLOCK-----
Conley Owens55e4d462012-10-01 16:12:28 -070078
79 Conley Owens <cco3@android.com>
80-----BEGIN PGP PUBLIC KEY BLOCK-----
81Version: GnuPG v1.4.11 (GNU/Linux)
82
83mQENBFBiLPwBCACvISTASOgFXwADw2GYRH2I2z9RvYkYoZ6ThTTNlMXbbYYKO2Wo
84a9LQDNW0TbCEekg5UKk0FD13XOdWaqUt4Gtuvq9c43GRSjMO6NXH+0BjcQ8vUtY2
85/W4CYUevwdo4nQ1+1zsOCu1XYe/CReXq0fdugv3hgmRmh3sz1soo37Q44W2frxxg
86U7Rz3Da4FjgAL0RQ8qndD+LwRHXTY7H7wYM8V/3cYFZV7pSodd75q3MAXYQLf0ZV
87QR1XATu5l1QnXrxgHvz7MmDwb1D+jX3YPKnZveaukigQ6hDHdiVcePBiGXmk8LZC
882jQkdXeF7Su1ZYpr2nnEHLJ6vOLcCpPGb8gDABEBAAG0H0NvbmxleSBPd2VucyA8
89Y2NvM0BhbmRyb2lkLmNvbT6JATgEEwECACIFAlBiLPwCGwMGCwkIBwMCBhUIAgkK
90CwQWAgMBAh4BAheAAAoJEBkmlFUziHGkHVkH/2Hks2Cif5i2xPtv2IFZcjL42joU
91T7lO5XFqUYS9ZNHpGa/V0eiPt7rHoO16glR83NZtwlrq2cSN89i9HfOhMYV/qLu8
92fLCHcV2muw+yCB5s5bxnI5UkToiNZyBNqFkcOt/Kbj9Hpy68A1kmc6myVEaUYebq
932Chx/f3xuEthan099t746v1K+/6SvQGDNctHuaMr9cWdxZtHjdRf31SQRc99Phe5
94w+ZGR/ebxNDKRK9mKgZT8wVFHlXerJsRqWIqtx1fsW1UgLgbpcpe2MChm6B5wTu0
95s1ltzox3l4q71FyRRPUJxXyvGkDLZWpK7EpiHSCOYq/KP3HkKeXU3xqHpcG5AQ0E
96UGIs/AEIAKzO/7lO9cB6dshmZYo8Vy/b7aGicThE+ChcDSfhvyOXVdEM2GKAjsR+
97rlBWbTFX3It301p2HwZPFEi9nEvJxVlqqBiW0bPmNMkDRR55l2vbWg35wwkg6RyE
98Bc5/TQjhXI2w8IvlimoGoUff4t3JmMOnWrnKSvL+5iuRj12p9WmanCHzw3Ee7ztf
99/aU/q+FTpr3DLerb6S8xbv86ySgnJT6o5CyL2DCWRtnYQyGVi0ZmLzEouAYiO0hs
100z0AAu28Mj+12g2WwePRz6gfM9rHtI37ylYW3oT/9M9mO9ei/Bc/1D7Dz6qNV+0vg
101uSVJxM2Bl6GalHPZLhHntFEdIA6EdoUAEQEAAYkBHwQYAQIACQUCUGIs/AIbDAAK
102CRAZJpRVM4hxpNfkB/0W/hP5WK/NETXBlWXXW7JPaWO2c5kGwD0lnj5RRmridyo1
103vbm5PdM91jOsDQYqRu6YOoYBnDnEhB2wL2bPh34HWwwrA+LwB8hlcAV2z1bdwyfl
1043R823fReKN3QcvLHzmvZPrF4Rk97M9UIyKS0RtnfTWykRgDWHIsrtQPoNwsXrWoT
1059LrM2v+1+9mp3vuXnE473/NHxmiWEQH9Ez+O/mOxQ7rSOlqGRiKq/IBZCfioJOtV
106fTQeIu/yASZnsLBqr6SJEGwYBoWcyjG++k4fyw8ocOAo4uGDYbxgN7yYfNQ0OH7o
107V6pfUgqKLWa/aK7/N1ZHnPdFLD8Xt0Dmy4BPwrKC
108=O7am
109-----END PGP PUBLIC KEY BLOCK-----
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700110"""
111
112GIT = 'git' # our git command
Conley Owensc5aa4d32012-10-26 11:34:11 -0700113MIN_GIT_VERSION = (1, 7, 2) # minimum supported git version
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700114repodir = '.repo' # name of repo's private directory
Conley Owensc9129d92012-10-01 16:12:28 -0700115S_repo = 'repo' # special repo repository
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700116S_manifests = 'manifests' # special manifest repository
117REPO_MAIN = S_repo + '/main.py' # main script
118
119
120import optparse
121import os
122import re
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700123import subprocess
124import sys
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700125import urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700126
127home_dot_repo = os.path.expanduser('~/.repoconfig')
128gpg_dir = os.path.join(home_dot_repo, 'gnupg')
129
130extra_args = []
131init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
132
133# Logging
134group = init_optparse.add_option_group('Logging options')
135group.add_option('-q', '--quiet',
136 dest="quiet", action="store_true", default=False,
137 help="be quiet")
138
139# Manifest
140group = init_optparse.add_option_group('Manifest options')
141group.add_option('-u', '--manifest-url',
142 dest='manifest_url',
143 help='manifest repository location', metavar='URL')
144group.add_option('-b', '--manifest-branch',
145 dest='manifest_branch',
146 help='manifest branch or revision', metavar='REVISION')
147group.add_option('-m', '--manifest-name',
148 dest='manifest_name',
149 help='initial manifest file', metavar='NAME.xml')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800150group.add_option('--mirror',
151 dest='mirror', action='store_true',
152 help='mirror the forrest')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200153group.add_option('--reference',
154 dest='reference',
155 help='location of mirror directory', metavar='DIR')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700156group.add_option('--depth', type='int', default=None,
157 dest='depth',
158 help='create a shallow clone with given depth; see git clone')
Colin Cross5acde752012-03-28 20:15:45 -0700159group.add_option('-g', '--groups',
Conley Owens971de8e2012-04-16 10:36:08 -0700160 dest='groups', default='default',
Colin Cross5acde752012-03-28 20:15:45 -0700161 help='restrict manifest projects to ones with a specified group',
162 metavar='GROUP')
Conley Owensd21720d2012-04-16 11:02:21 -0700163group.add_option('-p', '--platform',
164 dest='platform', default="auto",
Conley Owensc9129d92012-10-01 16:12:28 -0700165 help='restrict manifest projects to ones with a specified '
Conley Owensd21720d2012-04-16 11:02:21 -0700166 'platform group [auto|all|none|linux|darwin|...]',
167 metavar='PLATFORM')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700168
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700169
170# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700171group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700172group.add_option('--repo-url',
173 dest='repo_url',
174 help='repo repository location', metavar='URL')
175group.add_option('--repo-branch',
176 dest='repo_branch',
177 help='repo branch or revision', metavar='REVISION')
178group.add_option('--no-repo-verify',
179 dest='no_repo_verify', action='store_true',
180 help='do not verify repo source code')
181
Victor Boivie841be342011-04-05 11:31:10 +0200182# Other
183group = init_optparse.add_option_group('Other options')
184group.add_option('--config-name',
185 dest='config_name', action="store_true", default=False,
186 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700187
188class CloneFailure(Exception):
189 """Indicate the remote clone of repo itself failed.
190 """
191
192
193def _Init(args):
194 """Installs repo by cloning it over the network.
195 """
196 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800197 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700198 init_optparse.print_usage()
199 sys.exit(1)
200
201 url = opt.repo_url
202 if not url:
203 url = REPO_URL
204 extra_args.append('--repo-url=%s' % url)
205
206 branch = opt.repo_branch
207 if not branch:
208 branch = REPO_REV
209 extra_args.append('--repo-branch=%s' % branch)
210
211 if branch.startswith('refs/heads/'):
212 branch = branch[len('refs/heads/'):]
213 if branch.startswith('refs/'):
214 print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
215 raise CloneFailure()
216
217 if not os.path.isdir(repodir):
218 try:
219 os.mkdir(repodir)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700220 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700221 print >>sys.stderr, \
222 'fatal: cannot make %s directory: %s' % (
223 repodir, e.strerror)
224 # Don't faise CloneFailure; that would delete the
225 # name. Instead exit immediately.
226 #
227 sys.exit(1)
228
229 _CheckGitVersion()
230 try:
Conley Owensc9129d92012-10-01 16:12:28 -0700231 if NeedSetupGnuPG():
232 can_verify = SetupGnuPG(opt.quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700233 else:
234 can_verify = True
235
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700236 dst = os.path.abspath(os.path.join(repodir, S_repo))
237 _Clone(url, dst, opt.quiet)
238
239 if can_verify and not opt.no_repo_verify:
240 rev = _Verify(dst, branch, opt.quiet)
241 else:
242 rev = 'refs/remotes/origin/%s^0' % branch
243
244 _Checkout(dst, branch, rev, opt.quiet)
245 except CloneFailure:
246 if opt.quiet:
247 print >>sys.stderr, \
248 'fatal: repo init failed; run without --quiet to see why'
249 raise
250
251
252def _CheckGitVersion():
253 cmd = [GIT, '--version']
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700254 try:
255 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700256 except OSError as e:
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700257 print >>sys.stderr
258 print >>sys.stderr, "fatal: '%s' is not available" % GIT
259 print >>sys.stderr, 'fatal: %s' % e
260 print >>sys.stderr
261 print >>sys.stderr, 'Please make sure %s is installed'\
262 ' and in your path.' % GIT
263 raise CloneFailure()
264
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700265 ver_str = proc.stdout.read().strip()
266 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700267 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700268
269 if not ver_str.startswith('git version '):
270 print >>sys.stderr, 'error: "%s" unsupported' % ver_str
271 raise CloneFailure()
272
273 ver_str = ver_str[len('git version '):].strip()
274 ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
275 if ver_act < MIN_GIT_VERSION:
276 need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
277 print >>sys.stderr, 'fatal: git %s or later required' % need
278 raise CloneFailure()
279
280
Conley Owensc9129d92012-10-01 16:12:28 -0700281def NeedSetupGnuPG():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700282 if not os.path.isdir(home_dot_repo):
283 return True
284
285 kv = os.path.join(home_dot_repo, 'keyring-version')
286 if not os.path.exists(kv):
287 return True
288
289 kv = open(kv).read()
290 if not kv:
291 return True
292
293 kv = tuple(map(lambda x: int(x), kv.split('.')))
294 if kv < KEYRING_VERSION:
295 return True
296 return False
297
298
Conley Owensc9129d92012-10-01 16:12:28 -0700299def SetupGnuPG(quiet):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700300 if not os.path.isdir(home_dot_repo):
301 try:
302 os.mkdir(home_dot_repo)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700303 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700304 print >>sys.stderr, \
305 'fatal: cannot make %s directory: %s' % (
306 home_dot_repo, e.strerror)
307 sys.exit(1)
308
309 if not os.path.isdir(gpg_dir):
310 try:
311 os.mkdir(gpg_dir, 0700)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700312 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700313 print >>sys.stderr, \
314 'fatal: cannot make %s directory: %s' % (
315 gpg_dir, e.strerror)
316 sys.exit(1)
317
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800318 env = os.environ.copy()
319 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700320
321 cmd = ['gpg', '--import']
322 try:
323 proc = subprocess.Popen(cmd,
324 env = env,
325 stdin = subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700326 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700327 if not quiet:
328 print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
329 print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
330 print >>sys.stderr
331 return False
332
333 proc.stdin.write(MAINTAINER_KEYS)
334 proc.stdin.close()
335
336 if proc.wait() != 0:
337 print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
338 sys.exit(1)
339 print
340
341 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
342 fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
343 fd.close()
344 return True
345
346
347def _SetConfig(local, name, value):
348 """Set a git configuration option to the specified value.
349 """
350 cmd = [GIT, 'config', name, value]
351 if subprocess.Popen(cmd, cwd = local).wait() != 0:
352 raise CloneFailure()
353
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700354
355def _InitHttp():
356 handlers = []
357
358 mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
359 try:
360 import netrc
361 n = netrc.netrc()
362 for host in n.hosts:
363 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800364 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
365 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700366 except:
367 pass
368 handlers.append(urllib2.HTTPBasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800369 handlers.append(urllib2.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700370
371 if 'http_proxy' in os.environ:
372 url = os.environ['http_proxy']
373 handlers.append(urllib2.ProxyHandler({'http': url, 'https': url}))
374 if 'REPO_CURL_VERBOSE' in os.environ:
375 handlers.append(urllib2.HTTPHandler(debuglevel=1))
376 handlers.append(urllib2.HTTPSHandler(debuglevel=1))
377 urllib2.install_opener(urllib2.build_opener(*handlers))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700378
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700379def _Fetch(url, local, src, quiet):
380 if not quiet:
381 print >>sys.stderr, 'Get %s' % url
382
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700383 cmd = [GIT, 'fetch']
384 if quiet:
385 cmd.append('--quiet')
386 err = subprocess.PIPE
387 else:
388 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700389 cmd.append(src)
390 cmd.append('+refs/heads/*:refs/remotes/origin/*')
391 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700392
393 proc = subprocess.Popen(cmd, cwd = local, stderr = err)
394 if err:
395 proc.stderr.read()
396 proc.stderr.close()
397 if proc.wait() != 0:
398 raise CloneFailure()
399
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700400def _DownloadBundle(url, local, quiet):
401 if not url.endswith('/'):
402 url += '/'
403 url += 'clone.bundle'
404
405 proc = subprocess.Popen(
406 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
407 cwd = local,
408 stdout = subprocess.PIPE)
409 for line in proc.stdout:
410 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
411 if m:
412 new_url = m.group(1)
413 old_url = m.group(2)
414 if url.startswith(old_url):
415 url = new_url + url[len(old_url):]
416 break
417 proc.stdout.close()
418 proc.wait()
419
420 if not url.startswith('http:') and not url.startswith('https:'):
421 return False
422
423 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
424 try:
425 try:
426 r = urllib2.urlopen(url)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700427 except urllib2.HTTPError as e:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700428 if e.code == 404:
429 return False
430 print >>sys.stderr, 'fatal: Cannot get %s' % url
431 print >>sys.stderr, 'fatal: HTTP error %s' % e.code
432 raise CloneFailure()
Sarah Owensa5be53f2012-09-09 15:37:57 -0700433 except urllib2.URLError as e:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700434 print >>sys.stderr, 'fatal: Cannot get %s' % url
435 print >>sys.stderr, 'fatal: error %s' % e.reason
436 raise CloneFailure()
437 try:
438 if not quiet:
439 print >>sys.stderr, 'Get %s' % url
440 while True:
441 buf = r.read(8192)
442 if buf == '':
443 return True
444 dest.write(buf)
445 finally:
446 r.close()
447 finally:
448 dest.close()
449
450def _ImportBundle(local):
451 path = os.path.join(local, '.git', 'clone.bundle')
452 try:
453 _Fetch(local, local, path, True)
454 finally:
455 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700456
457def _Clone(url, local, quiet):
458 """Clones a git repository to a new subdirectory of repodir
459 """
460 try:
461 os.mkdir(local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700462 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700463 print >>sys.stderr, \
464 'fatal: cannot make %s directory: %s' \
465 % (local, e.strerror)
466 raise CloneFailure()
467
468 cmd = [GIT, 'init', '--quiet']
469 try:
470 proc = subprocess.Popen(cmd, cwd = local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700471 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700472 print >>sys.stderr
473 print >>sys.stderr, "fatal: '%s' is not available" % GIT
474 print >>sys.stderr, 'fatal: %s' % e
475 print >>sys.stderr
476 print >>sys.stderr, 'Please make sure %s is installed'\
477 ' and in your path.' % GIT
478 raise CloneFailure()
479 if proc.wait() != 0:
480 print >>sys.stderr, 'fatal: could not create %s' % local
481 raise CloneFailure()
482
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700483 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700484 _SetConfig(local, 'remote.origin.url', url)
485 _SetConfig(local, 'remote.origin.fetch',
486 '+refs/heads/*:refs/remotes/origin/*')
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700487 if _DownloadBundle(url, local, quiet):
488 _ImportBundle(local)
489 else:
490 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700491
492
493def _Verify(cwd, branch, quiet):
494 """Verify the branch has been signed by a tag.
495 """
496 cmd = [GIT, 'describe', 'origin/%s' % branch]
497 proc = subprocess.Popen(cmd,
498 stdout=subprocess.PIPE,
499 stderr=subprocess.PIPE,
500 cwd = cwd)
501 cur = proc.stdout.read().strip()
502 proc.stdout.close()
503
504 proc.stderr.read()
505 proc.stderr.close()
506
507 if proc.wait() != 0 or not cur:
508 print >>sys.stderr
509 print >>sys.stderr,\
510 "fatal: branch '%s' has not been signed" \
511 % branch
512 raise CloneFailure()
513
514 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
515 if m:
516 cur = m.group(1)
517 if not quiet:
518 print >>sys.stderr
519 print >>sys.stderr, \
520 "info: Ignoring branch '%s'; using tagged release '%s'" \
521 % (branch, cur)
522 print >>sys.stderr
523
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800524 env = os.environ.copy()
525 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700526
527 cmd = [GIT, 'tag', '-v', cur]
528 proc = subprocess.Popen(cmd,
529 stdout = subprocess.PIPE,
530 stderr = subprocess.PIPE,
531 cwd = cwd,
532 env = env)
533 out = proc.stdout.read()
534 proc.stdout.close()
535
536 err = proc.stderr.read()
537 proc.stderr.close()
538
539 if proc.wait() != 0:
540 print >>sys.stderr
541 print >>sys.stderr, out
542 print >>sys.stderr, err
543 print >>sys.stderr
544 raise CloneFailure()
545 return '%s^0' % cur
546
547
548def _Checkout(cwd, branch, rev, quiet):
549 """Checkout an upstream branch into the repository and track it.
550 """
551 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
552 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
553 raise CloneFailure()
554
555 _SetConfig(cwd, 'branch.default.remote', 'origin')
556 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
557
558 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
559 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
560 raise CloneFailure()
561
562 cmd = [GIT, 'read-tree', '--reset', '-u']
563 if not quiet:
564 cmd.append('-v')
565 cmd.append('HEAD')
566 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
567 raise CloneFailure()
568
569
570def _FindRepo():
571 """Look for a repo installation, starting at the current directory.
572 """
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200573 curdir = os.getcwd()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700574 repo = None
575
Anthony Newnamdf14a702011-01-09 17:31:57 -0800576 olddir = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200577 while curdir != '/' \
578 and curdir != olddir \
Anthony Newnamdf14a702011-01-09 17:31:57 -0800579 and not repo:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200580 repo = os.path.join(curdir, repodir, REPO_MAIN)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700581 if not os.path.isfile(repo):
582 repo = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200583 olddir = curdir
584 curdir = os.path.dirname(curdir)
585 return (repo, os.path.join(curdir, repodir))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700586
587
588class _Options:
589 help = False
590
591
592def _ParseArguments(args):
593 cmd = None
594 opt = _Options()
595 arg = []
596
597 for i in xrange(0, len(args)):
598 a = args[i]
599 if a == '-h' or a == '--help':
600 opt.help = True
601
602 elif not a.startswith('-'):
603 cmd = a
604 arg = args[i + 1:]
605 break
606 return cmd, opt, arg
607
608
609def _Usage():
610 print >>sys.stderr,\
611"""usage: repo COMMAND [ARGS]
612
613repo is not yet installed. Use "repo init" to install it here.
614
615The most commonly used repo commands are:
616
617 init Install repo in the current working directory
618 help Display detailed help on a command
619
620For access to the full online help, install repo ("repo init").
621"""
622 sys.exit(1)
623
624
625def _Help(args):
626 if args:
627 if args[0] == 'init':
628 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100629 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700630 else:
631 print >>sys.stderr,\
632 "error: '%s' is not a bootstrap command.\n"\
633 ' For access to online help, install repo ("repo init").'\
634 % args[0]
635 else:
636 _Usage()
637 sys.exit(1)
638
639
640def _NotInstalled():
641 print >>sys.stderr,\
642'error: repo is not installed. Use "repo init" to install it here.'
643 sys.exit(1)
644
645
646def _NoCommands(cmd):
647 print >>sys.stderr,\
648"""error: command '%s' requires repo to be installed first.
649 Use "repo init" to install it here.""" % cmd
650 sys.exit(1)
651
652
653def _RunSelf(wrapper_path):
654 my_dir = os.path.dirname(wrapper_path)
655 my_main = os.path.join(my_dir, 'main.py')
656 my_git = os.path.join(my_dir, '.git')
657
658 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700659 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700660 'project.py',
661 'subcmds']:
662 if not os.path.exists(os.path.join(my_dir, name)):
663 return None, None
664 return my_main, my_git
665 return None, None
666
667
668def _SetDefaultsTo(gitdir):
669 global REPO_URL
670 global REPO_REV
671
672 REPO_URL = gitdir
673 proc = subprocess.Popen([GIT,
674 '--git-dir=%s' % gitdir,
675 'symbolic-ref',
676 'HEAD'],
677 stdout = subprocess.PIPE,
678 stderr = subprocess.PIPE)
679 REPO_REV = proc.stdout.read().strip()
680 proc.stdout.close()
681
682 proc.stderr.read()
683 proc.stderr.close()
684
685 if proc.wait() != 0:
686 print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
687 sys.exit(1)
688
689
690def main(orig_args):
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200691 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700692 cmd, opt, args = _ParseArguments(orig_args)
693
694 wrapper_path = os.path.abspath(__file__)
695 my_main, my_git = _RunSelf(wrapper_path)
696
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200697 if not repo_main:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700698 if opt.help:
699 _Usage()
700 if cmd == 'help':
701 _Help(args)
702 if not cmd:
703 _NotInstalled()
704 if cmd == 'init':
705 if my_git:
706 _SetDefaultsTo(my_git)
707 try:
708 _Init(args)
709 except CloneFailure:
710 for root, dirs, files in os.walk(repodir, topdown=False):
711 for name in files:
712 os.remove(os.path.join(root, name))
713 for name in dirs:
714 os.rmdir(os.path.join(root, name))
715 os.rmdir(repodir)
716 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200717 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700718 else:
719 _NoCommands(cmd)
720
721 if my_main:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200722 repo_main = my_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700723
724 ver_str = '.'.join(map(lambda x: str(x), VERSION))
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200725 me = [repo_main,
726 '--repo-dir=%s' % rel_repo_dir,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700727 '--wrapper-version=%s' % ver_str,
728 '--wrapper-path=%s' % wrapper_path,
729 '--']
730 me.extend(orig_args)
731 me.extend(extra_args)
732 try:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200733 os.execv(repo_main, me)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700734 except OSError as e:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200735 print >>sys.stderr, "fatal: unable to start %s" % repo_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700736 print >>sys.stderr, "fatal: %s" % e
737 sys.exit(148)
738
739
740if __name__ == '__main__':
741 main(sys.argv[1:])