blob: 060ea6d193555ade1018d7bee09fe7a5decfe0d9 [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+ZkPY5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UBLIC 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
Sarah Owens1f7627f2012-10-31 09:21:55 -0700125try:
126 import urllib2
127except ImportError:
128 # For python3
129 import urllib.request
130 import urllib.error
131else:
132 # For python2
133 import imp
134 urllib = imp.new_module('urllib')
135 urllib.request = urllib2
136 urllib.error = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700137
138home_dot_repo = os.path.expanduser('~/.repoconfig')
139gpg_dir = os.path.join(home_dot_repo, 'gnupg')
140
141extra_args = []
142init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
143
144# Logging
145group = init_optparse.add_option_group('Logging options')
146group.add_option('-q', '--quiet',
147 dest="quiet", action="store_true", default=False,
148 help="be quiet")
149
150# Manifest
151group = init_optparse.add_option_group('Manifest options')
152group.add_option('-u', '--manifest-url',
153 dest='manifest_url',
154 help='manifest repository location', metavar='URL')
155group.add_option('-b', '--manifest-branch',
156 dest='manifest_branch',
157 help='manifest branch or revision', metavar='REVISION')
158group.add_option('-m', '--manifest-name',
159 dest='manifest_name',
160 help='initial manifest file', metavar='NAME.xml')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800161group.add_option('--mirror',
162 dest='mirror', action='store_true',
163 help='mirror the forrest')
Shawn O. Pearce88443382010-10-08 10:02:09 +0200164group.add_option('--reference',
165 dest='reference',
166 help='location of mirror directory', metavar='DIR')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700167group.add_option('--depth', type='int', default=None,
168 dest='depth',
169 help='create a shallow clone with given depth; see git clone')
Colin Cross5acde752012-03-28 20:15:45 -0700170group.add_option('-g', '--groups',
Conley Owens971de8e2012-04-16 10:36:08 -0700171 dest='groups', default='default',
Colin Cross5acde752012-03-28 20:15:45 -0700172 help='restrict manifest projects to ones with a specified group',
173 metavar='GROUP')
Conley Owensd21720d2012-04-16 11:02:21 -0700174group.add_option('-p', '--platform',
175 dest='platform', default="auto",
Conley Owensc9129d92012-10-01 16:12:28 -0700176 help='restrict manifest projects to ones with a specified '
Conley Owensd21720d2012-04-16 11:02:21 -0700177 'platform group [auto|all|none|linux|darwin|...]',
178 metavar='PLATFORM')
Doug Anderson49cd59b2011-06-13 21:42:06 -0700179
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700180
181# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700182group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700183group.add_option('--repo-url',
184 dest='repo_url',
185 help='repo repository location', metavar='URL')
186group.add_option('--repo-branch',
187 dest='repo_branch',
188 help='repo branch or revision', metavar='REVISION')
189group.add_option('--no-repo-verify',
190 dest='no_repo_verify', action='store_true',
191 help='do not verify repo source code')
192
Victor Boivie841be342011-04-05 11:31:10 +0200193# Other
194group = init_optparse.add_option_group('Other options')
195group.add_option('--config-name',
196 dest='config_name', action="store_true", default=False,
197 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700198
199class CloneFailure(Exception):
200 """Indicate the remote clone of repo itself failed.
201 """
202
203
204def _Init(args):
205 """Installs repo by cloning it over the network.
206 """
207 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800208 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700209 init_optparse.print_usage()
210 sys.exit(1)
211
212 url = opt.repo_url
213 if not url:
214 url = REPO_URL
215 extra_args.append('--repo-url=%s' % url)
216
217 branch = opt.repo_branch
218 if not branch:
219 branch = REPO_REV
220 extra_args.append('--repo-branch=%s' % branch)
221
222 if branch.startswith('refs/heads/'):
223 branch = branch[len('refs/heads/'):]
224 if branch.startswith('refs/'):
225 print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
226 raise CloneFailure()
227
228 if not os.path.isdir(repodir):
229 try:
230 os.mkdir(repodir)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700231 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700232 print >>sys.stderr, \
233 'fatal: cannot make %s directory: %s' % (
234 repodir, e.strerror)
235 # Don't faise CloneFailure; that would delete the
236 # name. Instead exit immediately.
237 #
238 sys.exit(1)
239
240 _CheckGitVersion()
241 try:
Conley Owensc9129d92012-10-01 16:12:28 -0700242 if NeedSetupGnuPG():
243 can_verify = SetupGnuPG(opt.quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700244 else:
245 can_verify = True
246
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700247 dst = os.path.abspath(os.path.join(repodir, S_repo))
248 _Clone(url, dst, opt.quiet)
249
250 if can_verify and not opt.no_repo_verify:
251 rev = _Verify(dst, branch, opt.quiet)
252 else:
253 rev = 'refs/remotes/origin/%s^0' % branch
254
255 _Checkout(dst, branch, rev, opt.quiet)
256 except CloneFailure:
257 if opt.quiet:
258 print >>sys.stderr, \
259 'fatal: repo init failed; run without --quiet to see why'
260 raise
261
262
263def _CheckGitVersion():
264 cmd = [GIT, '--version']
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700265 try:
266 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700267 except OSError as e:
Shawn O. Pearce4fd38ec2012-06-05 07:55:07 -0700268 print >>sys.stderr
269 print >>sys.stderr, "fatal: '%s' is not available" % GIT
270 print >>sys.stderr, 'fatal: %s' % e
271 print >>sys.stderr
272 print >>sys.stderr, 'Please make sure %s is installed'\
273 ' and in your path.' % GIT
274 raise CloneFailure()
275
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700276 ver_str = proc.stdout.read().strip()
277 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700278 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700279
280 if not ver_str.startswith('git version '):
281 print >>sys.stderr, 'error: "%s" unsupported' % ver_str
282 raise CloneFailure()
283
284 ver_str = ver_str[len('git version '):].strip()
285 ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
286 if ver_act < MIN_GIT_VERSION:
287 need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
288 print >>sys.stderr, 'fatal: git %s or later required' % need
289 raise CloneFailure()
290
291
Conley Owensc9129d92012-10-01 16:12:28 -0700292def NeedSetupGnuPG():
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700293 if not os.path.isdir(home_dot_repo):
294 return True
295
296 kv = os.path.join(home_dot_repo, 'keyring-version')
297 if not os.path.exists(kv):
298 return True
299
300 kv = open(kv).read()
301 if not kv:
302 return True
303
304 kv = tuple(map(lambda x: int(x), kv.split('.')))
305 if kv < KEYRING_VERSION:
306 return True
307 return False
308
309
Conley Owensc9129d92012-10-01 16:12:28 -0700310def SetupGnuPG(quiet):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700311 if not os.path.isdir(home_dot_repo):
312 try:
313 os.mkdir(home_dot_repo)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700314 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700315 print >>sys.stderr, \
316 'fatal: cannot make %s directory: %s' % (
317 home_dot_repo, e.strerror)
318 sys.exit(1)
319
320 if not os.path.isdir(gpg_dir):
321 try:
322 os.mkdir(gpg_dir, 0700)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700323 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700324 print >>sys.stderr, \
325 'fatal: cannot make %s directory: %s' % (
326 gpg_dir, e.strerror)
327 sys.exit(1)
328
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800329 env = os.environ.copy()
330 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700331
332 cmd = ['gpg', '--import']
333 try:
334 proc = subprocess.Popen(cmd,
335 env = env,
336 stdin = subprocess.PIPE)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700337 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700338 if not quiet:
339 print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
340 print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
341 print >>sys.stderr
342 return False
343
344 proc.stdin.write(MAINTAINER_KEYS)
345 proc.stdin.close()
346
347 if proc.wait() != 0:
348 print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
349 sys.exit(1)
350 print
351
352 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
353 fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
354 fd.close()
355 return True
356
357
358def _SetConfig(local, name, value):
359 """Set a git configuration option to the specified value.
360 """
361 cmd = [GIT, 'config', name, value]
362 if subprocess.Popen(cmd, cwd = local).wait() != 0:
363 raise CloneFailure()
364
365
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700366def _InitHttp():
367 handlers = []
368
Sarah Owens1f7627f2012-10-31 09:21:55 -0700369 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700370 try:
371 import netrc
372 n = netrc.netrc()
373 for host in n.hosts:
374 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800375 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
376 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700377 except:
378 pass
Sarah Owens1f7627f2012-10-31 09:21:55 -0700379 handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
380 handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700381
382 if 'http_proxy' in os.environ:
383 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700384 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700385 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700386 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
387 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
388 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700389
390def _Fetch(url, local, src, quiet):
391 if not quiet:
392 print >>sys.stderr, 'Get %s' % url
393
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700394 cmd = [GIT, 'fetch']
395 if quiet:
396 cmd.append('--quiet')
397 err = subprocess.PIPE
398 else:
399 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700400 cmd.append(src)
401 cmd.append('+refs/heads/*:refs/remotes/origin/*')
402 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700403
404 proc = subprocess.Popen(cmd, cwd = local, stderr = err)
405 if err:
406 proc.stderr.read()
407 proc.stderr.close()
408 if proc.wait() != 0:
409 raise CloneFailure()
410
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700411def _DownloadBundle(url, local, quiet):
412 if not url.endswith('/'):
413 url += '/'
414 url += 'clone.bundle'
415
416 proc = subprocess.Popen(
417 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
418 cwd = local,
419 stdout = subprocess.PIPE)
420 for line in proc.stdout:
421 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
422 if m:
423 new_url = m.group(1)
424 old_url = m.group(2)
425 if url.startswith(old_url):
426 url = new_url + url[len(old_url):]
427 break
428 proc.stdout.close()
429 proc.wait()
430
431 if not url.startswith('http:') and not url.startswith('https:'):
432 return False
433
434 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
435 try:
436 try:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700437 r = urllib.request.urlopen(url)
438 except urllib.error.HTTPError as e:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700439 if e.code == 404:
440 return False
441 print >>sys.stderr, 'fatal: Cannot get %s' % url
442 print >>sys.stderr, 'fatal: HTTP error %s' % e.code
443 raise CloneFailure()
Sarah Owens1f7627f2012-10-31 09:21:55 -0700444 except urllib.error.URLError as e:
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700445 print >>sys.stderr, 'fatal: Cannot get %s' % url
446 print >>sys.stderr, 'fatal: error %s' % e.reason
447 raise CloneFailure()
448 try:
449 if not quiet:
450 print >>sys.stderr, 'Get %s' % url
451 while True:
452 buf = r.read(8192)
453 if buf == '':
454 return True
455 dest.write(buf)
456 finally:
457 r.close()
458 finally:
459 dest.close()
460
461def _ImportBundle(local):
462 path = os.path.join(local, '.git', 'clone.bundle')
463 try:
464 _Fetch(local, local, path, True)
465 finally:
466 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700467
468def _Clone(url, local, quiet):
469 """Clones a git repository to a new subdirectory of repodir
470 """
471 try:
472 os.mkdir(local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700473 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700474 print >>sys.stderr, \
475 'fatal: cannot make %s directory: %s' \
476 % (local, e.strerror)
477 raise CloneFailure()
478
479 cmd = [GIT, 'init', '--quiet']
480 try:
481 proc = subprocess.Popen(cmd, cwd = local)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700482 except OSError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700483 print >>sys.stderr
484 print >>sys.stderr, "fatal: '%s' is not available" % GIT
485 print >>sys.stderr, 'fatal: %s' % e
486 print >>sys.stderr
487 print >>sys.stderr, 'Please make sure %s is installed'\
488 ' and in your path.' % GIT
489 raise CloneFailure()
490 if proc.wait() != 0:
491 print >>sys.stderr, 'fatal: could not create %s' % local
492 raise CloneFailure()
493
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700494 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700495 _SetConfig(local, 'remote.origin.url', url)
496 _SetConfig(local, 'remote.origin.fetch',
497 '+refs/heads/*:refs/remotes/origin/*')
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700498 if _DownloadBundle(url, local, quiet):
499 _ImportBundle(local)
500 else:
501 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700502
503
504def _Verify(cwd, branch, quiet):
505 """Verify the branch has been signed by a tag.
506 """
507 cmd = [GIT, 'describe', 'origin/%s' % branch]
508 proc = subprocess.Popen(cmd,
509 stdout=subprocess.PIPE,
510 stderr=subprocess.PIPE,
511 cwd = cwd)
512 cur = proc.stdout.read().strip()
513 proc.stdout.close()
514
515 proc.stderr.read()
516 proc.stderr.close()
517
518 if proc.wait() != 0 or not cur:
519 print >>sys.stderr
520 print >>sys.stderr,\
521 "fatal: branch '%s' has not been signed" \
522 % branch
523 raise CloneFailure()
524
525 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
526 if m:
527 cur = m.group(1)
528 if not quiet:
529 print >>sys.stderr
530 print >>sys.stderr, \
531 "info: Ignoring branch '%s'; using tagged release '%s'" \
532 % (branch, cur)
533 print >>sys.stderr
534
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800535 env = os.environ.copy()
536 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700537
538 cmd = [GIT, 'tag', '-v', cur]
539 proc = subprocess.Popen(cmd,
540 stdout = subprocess.PIPE,
541 stderr = subprocess.PIPE,
542 cwd = cwd,
543 env = env)
544 out = proc.stdout.read()
545 proc.stdout.close()
546
547 err = proc.stderr.read()
548 proc.stderr.close()
549
550 if proc.wait() != 0:
551 print >>sys.stderr
552 print >>sys.stderr, out
553 print >>sys.stderr, err
554 print >>sys.stderr
555 raise CloneFailure()
556 return '%s^0' % cur
557
558
559def _Checkout(cwd, branch, rev, quiet):
560 """Checkout an upstream branch into the repository and track it.
561 """
562 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
563 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
564 raise CloneFailure()
565
566 _SetConfig(cwd, 'branch.default.remote', 'origin')
567 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
568
569 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
570 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
571 raise CloneFailure()
572
573 cmd = [GIT, 'read-tree', '--reset', '-u']
574 if not quiet:
575 cmd.append('-v')
576 cmd.append('HEAD')
577 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
578 raise CloneFailure()
579
580
581def _FindRepo():
582 """Look for a repo installation, starting at the current directory.
583 """
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200584 curdir = os.getcwd()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700585 repo = None
586
Anthony Newnamdf14a702011-01-09 17:31:57 -0800587 olddir = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200588 while curdir != '/' \
589 and curdir != olddir \
Anthony Newnamdf14a702011-01-09 17:31:57 -0800590 and not repo:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200591 repo = os.path.join(curdir, repodir, REPO_MAIN)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700592 if not os.path.isfile(repo):
593 repo = None
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200594 olddir = curdir
595 curdir = os.path.dirname(curdir)
596 return (repo, os.path.join(curdir, repodir))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700597
598
599class _Options:
600 help = False
601
602
603def _ParseArguments(args):
604 cmd = None
605 opt = _Options()
606 arg = []
607
608 for i in xrange(0, len(args)):
609 a = args[i]
610 if a == '-h' or a == '--help':
611 opt.help = True
612
613 elif not a.startswith('-'):
614 cmd = a
615 arg = args[i + 1:]
616 break
617 return cmd, opt, arg
618
619
620def _Usage():
621 print >>sys.stderr,\
622"""usage: repo COMMAND [ARGS]
623
624repo is not yet installed. Use "repo init" to install it here.
625
626The most commonly used repo commands are:
627
628 init Install repo in the current working directory
629 help Display detailed help on a command
630
631For access to the full online help, install repo ("repo init").
632"""
633 sys.exit(1)
634
635
636def _Help(args):
637 if args:
638 if args[0] == 'init':
639 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100640 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700641 else:
642 print >>sys.stderr,\
643 "error: '%s' is not a bootstrap command.\n"\
644 ' For access to online help, install repo ("repo init").'\
645 % args[0]
646 else:
647 _Usage()
648 sys.exit(1)
649
650
651def _NotInstalled():
652 print >>sys.stderr,\
653'error: repo is not installed. Use "repo init" to install it here.'
654 sys.exit(1)
655
656
657def _NoCommands(cmd):
658 print >>sys.stderr,\
659"""error: command '%s' requires repo to be installed first.
660 Use "repo init" to install it here.""" % cmd
661 sys.exit(1)
662
663
664def _RunSelf(wrapper_path):
665 my_dir = os.path.dirname(wrapper_path)
666 my_main = os.path.join(my_dir, 'main.py')
667 my_git = os.path.join(my_dir, '.git')
668
669 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700670 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700671 'project.py',
672 'subcmds']:
673 if not os.path.exists(os.path.join(my_dir, name)):
674 return None, None
675 return my_main, my_git
676 return None, None
677
678
679def _SetDefaultsTo(gitdir):
680 global REPO_URL
681 global REPO_REV
682
683 REPO_URL = gitdir
684 proc = subprocess.Popen([GIT,
685 '--git-dir=%s' % gitdir,
686 'symbolic-ref',
687 'HEAD'],
688 stdout = subprocess.PIPE,
689 stderr = subprocess.PIPE)
690 REPO_REV = proc.stdout.read().strip()
691 proc.stdout.close()
692
693 proc.stderr.read()
694 proc.stderr.close()
695
696 if proc.wait() != 0:
697 print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
698 sys.exit(1)
699
700
701def main(orig_args):
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200702 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700703 cmd, opt, args = _ParseArguments(orig_args)
704
705 wrapper_path = os.path.abspath(__file__)
706 my_main, my_git = _RunSelf(wrapper_path)
707
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200708 if not repo_main:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700709 if opt.help:
710 _Usage()
711 if cmd == 'help':
712 _Help(args)
713 if not cmd:
714 _NotInstalled()
715 if cmd == 'init':
716 if my_git:
717 _SetDefaultsTo(my_git)
718 try:
719 _Init(args)
720 except CloneFailure:
721 for root, dirs, files in os.walk(repodir, topdown=False):
722 for name in files:
723 os.remove(os.path.join(root, name))
724 for name in dirs:
725 os.rmdir(os.path.join(root, name))
726 os.rmdir(repodir)
727 sys.exit(1)
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200728 repo_main, rel_repo_dir = _FindRepo()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700729 else:
730 _NoCommands(cmd)
731
732 if my_main:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200733 repo_main = my_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700734
735 ver_str = '.'.join(map(lambda x: str(x), VERSION))
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200736 me = [repo_main,
737 '--repo-dir=%s' % rel_repo_dir,
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700738 '--wrapper-version=%s' % ver_str,
739 '--wrapper-path=%s' % wrapper_path,
740 '--']
741 me.extend(orig_args)
742 me.extend(extra_args)
743 try:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200744 os.execv(repo_main, me)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700745 except OSError as e:
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200746 print >>sys.stderr, "fatal: unable to start %s" % repo_main
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700747 print >>sys.stderr, "fatal: %s" % e
748 sys.exit(148)
749
750
751if __name__ == '__main__':
752 main(sys.argv[1:])