blob: 1977d6359df2533affb1641cfe53b95c70739166 [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
Xiaodong Xuae0a36c2012-01-31 11:10:09 +080031VERSION = (1, 14)
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
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
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')
128
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700129
130# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700131group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700132group.add_option('--repo-url',
133 dest='repo_url',
134 help='repo repository location', metavar='URL')
135group.add_option('--repo-branch',
136 dest='repo_branch',
137 help='repo branch or revision', metavar='REVISION')
138group.add_option('--no-repo-verify',
139 dest='no_repo_verify', action='store_true',
140 help='do not verify repo source code')
141
Victor Boivie841be342011-04-05 11:31:10 +0200142# Other
143group = init_optparse.add_option_group('Other options')
144group.add_option('--config-name',
145 dest='config_name', action="store_true", default=False,
146 help='Always prompt for name/e-mail')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700147
148class CloneFailure(Exception):
149 """Indicate the remote clone of repo itself failed.
150 """
151
152
153def _Init(args):
154 """Installs repo by cloning it over the network.
155 """
156 opt, args = init_optparse.parse_args(args)
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800157 if args:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700158 init_optparse.print_usage()
159 sys.exit(1)
160
161 url = opt.repo_url
162 if not url:
163 url = REPO_URL
164 extra_args.append('--repo-url=%s' % url)
165
166 branch = opt.repo_branch
167 if not branch:
168 branch = REPO_REV
169 extra_args.append('--repo-branch=%s' % branch)
170
171 if branch.startswith('refs/heads/'):
172 branch = branch[len('refs/heads/'):]
173 if branch.startswith('refs/'):
174 print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
175 raise CloneFailure()
176
177 if not os.path.isdir(repodir):
178 try:
179 os.mkdir(repodir)
180 except OSError, e:
181 print >>sys.stderr, \
182 'fatal: cannot make %s directory: %s' % (
183 repodir, e.strerror)
184 # Don't faise CloneFailure; that would delete the
185 # name. Instead exit immediately.
186 #
187 sys.exit(1)
188
189 _CheckGitVersion()
190 try:
191 if _NeedSetupGnuPG():
192 can_verify = _SetupGnuPG(opt.quiet)
193 else:
194 can_verify = True
195
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700196 dst = os.path.abspath(os.path.join(repodir, S_repo))
197 _Clone(url, dst, opt.quiet)
198
199 if can_verify and not opt.no_repo_verify:
200 rev = _Verify(dst, branch, opt.quiet)
201 else:
202 rev = 'refs/remotes/origin/%s^0' % branch
203
204 _Checkout(dst, branch, rev, opt.quiet)
205 except CloneFailure:
206 if opt.quiet:
207 print >>sys.stderr, \
208 'fatal: repo init failed; run without --quiet to see why'
209 raise
210
211
212def _CheckGitVersion():
213 cmd = [GIT, '--version']
214 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
215 ver_str = proc.stdout.read().strip()
216 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700217 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700218
219 if not ver_str.startswith('git version '):
220 print >>sys.stderr, 'error: "%s" unsupported' % ver_str
221 raise CloneFailure()
222
223 ver_str = ver_str[len('git version '):].strip()
224 ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
225 if ver_act < MIN_GIT_VERSION:
226 need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
227 print >>sys.stderr, 'fatal: git %s or later required' % need
228 raise CloneFailure()
229
230
231def _NeedSetupGnuPG():
232 if not os.path.isdir(home_dot_repo):
233 return True
234
235 kv = os.path.join(home_dot_repo, 'keyring-version')
236 if not os.path.exists(kv):
237 return True
238
239 kv = open(kv).read()
240 if not kv:
241 return True
242
243 kv = tuple(map(lambda x: int(x), kv.split('.')))
244 if kv < KEYRING_VERSION:
245 return True
246 return False
247
248
249def _SetupGnuPG(quiet):
250 if not os.path.isdir(home_dot_repo):
251 try:
252 os.mkdir(home_dot_repo)
253 except OSError, e:
254 print >>sys.stderr, \
255 'fatal: cannot make %s directory: %s' % (
256 home_dot_repo, e.strerror)
257 sys.exit(1)
258
259 if not os.path.isdir(gpg_dir):
260 try:
261 os.mkdir(gpg_dir, 0700)
262 except OSError, e:
263 print >>sys.stderr, \
264 'fatal: cannot make %s directory: %s' % (
265 gpg_dir, e.strerror)
266 sys.exit(1)
267
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800268 env = os.environ.copy()
269 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700270
271 cmd = ['gpg', '--import']
272 try:
273 proc = subprocess.Popen(cmd,
274 env = env,
275 stdin = subprocess.PIPE)
276 except OSError, e:
277 if not quiet:
278 print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
279 print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
280 print >>sys.stderr
281 return False
282
283 proc.stdin.write(MAINTAINER_KEYS)
284 proc.stdin.close()
285
286 if proc.wait() != 0:
287 print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
288 sys.exit(1)
289 print
290
291 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
292 fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
293 fd.close()
294 return True
295
296
297def _SetConfig(local, name, value):
298 """Set a git configuration option to the specified value.
299 """
300 cmd = [GIT, 'config', name, value]
301 if subprocess.Popen(cmd, cwd = local).wait() != 0:
302 raise CloneFailure()
303
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700304
305def _InitHttp():
306 handlers = []
307
308 mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
309 try:
310 import netrc
311 n = netrc.netrc()
312 for host in n.hosts:
313 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800314 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
315 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700316 except:
317 pass
318 handlers.append(urllib2.HTTPBasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800319 handlers.append(urllib2.HTTPDigestAuthHandler(mgr))
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700320
321 if 'http_proxy' in os.environ:
322 url = os.environ['http_proxy']
323 handlers.append(urllib2.ProxyHandler({'http': url, 'https': url}))
324 if 'REPO_CURL_VERBOSE' in os.environ:
325 handlers.append(urllib2.HTTPHandler(debuglevel=1))
326 handlers.append(urllib2.HTTPSHandler(debuglevel=1))
327 urllib2.install_opener(urllib2.build_opener(*handlers))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700328
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700329def _Fetch(url, local, src, quiet):
330 if not quiet:
331 print >>sys.stderr, 'Get %s' % url
332
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700333 cmd = [GIT, 'fetch']
334 if quiet:
335 cmd.append('--quiet')
336 err = subprocess.PIPE
337 else:
338 err = None
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700339 cmd.append(src)
340 cmd.append('+refs/heads/*:refs/remotes/origin/*')
341 cmd.append('refs/tags/*:refs/tags/*')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700342
343 proc = subprocess.Popen(cmd, cwd = local, stderr = err)
344 if err:
345 proc.stderr.read()
346 proc.stderr.close()
347 if proc.wait() != 0:
348 raise CloneFailure()
349
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700350def _DownloadBundle(url, local, quiet):
351 if not url.endswith('/'):
352 url += '/'
353 url += 'clone.bundle'
354
355 proc = subprocess.Popen(
356 [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
357 cwd = local,
358 stdout = subprocess.PIPE)
359 for line in proc.stdout:
360 m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
361 if m:
362 new_url = m.group(1)
363 old_url = m.group(2)
364 if url.startswith(old_url):
365 url = new_url + url[len(old_url):]
366 break
367 proc.stdout.close()
368 proc.wait()
369
370 if not url.startswith('http:') and not url.startswith('https:'):
371 return False
372
373 dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
374 try:
375 try:
376 r = urllib2.urlopen(url)
377 except urllib2.HTTPError, e:
378 if e.code == 404:
379 return False
380 print >>sys.stderr, 'fatal: Cannot get %s' % url
381 print >>sys.stderr, 'fatal: HTTP error %s' % e.code
382 raise CloneFailure()
383 except urllib2.URLError, e:
384 print >>sys.stderr, 'fatal: Cannot get %s' % url
385 print >>sys.stderr, 'fatal: error %s' % e.reason
386 raise CloneFailure()
387 try:
388 if not quiet:
389 print >>sys.stderr, 'Get %s' % url
390 while True:
391 buf = r.read(8192)
392 if buf == '':
393 return True
394 dest.write(buf)
395 finally:
396 r.close()
397 finally:
398 dest.close()
399
400def _ImportBundle(local):
401 path = os.path.join(local, '.git', 'clone.bundle')
402 try:
403 _Fetch(local, local, path, True)
404 finally:
405 os.remove(path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700406
407def _Clone(url, local, quiet):
408 """Clones a git repository to a new subdirectory of repodir
409 """
410 try:
411 os.mkdir(local)
412 except OSError, e:
413 print >>sys.stderr, \
414 'fatal: cannot make %s directory: %s' \
415 % (local, e.strerror)
416 raise CloneFailure()
417
418 cmd = [GIT, 'init', '--quiet']
419 try:
420 proc = subprocess.Popen(cmd, cwd = local)
421 except OSError, e:
422 print >>sys.stderr
423 print >>sys.stderr, "fatal: '%s' is not available" % GIT
424 print >>sys.stderr, 'fatal: %s' % e
425 print >>sys.stderr
426 print >>sys.stderr, 'Please make sure %s is installed'\
427 ' and in your path.' % GIT
428 raise CloneFailure()
429 if proc.wait() != 0:
430 print >>sys.stderr, 'fatal: could not create %s' % local
431 raise CloneFailure()
432
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700433 _InitHttp()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700434 _SetConfig(local, 'remote.origin.url', url)
435 _SetConfig(local, 'remote.origin.fetch',
436 '+refs/heads/*:refs/remotes/origin/*')
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -0700437 if _DownloadBundle(url, local, quiet):
438 _ImportBundle(local)
439 else:
440 _Fetch(url, local, 'origin', quiet)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700441
442
443def _Verify(cwd, branch, quiet):
444 """Verify the branch has been signed by a tag.
445 """
446 cmd = [GIT, 'describe', 'origin/%s' % branch]
447 proc = subprocess.Popen(cmd,
448 stdout=subprocess.PIPE,
449 stderr=subprocess.PIPE,
450 cwd = cwd)
451 cur = proc.stdout.read().strip()
452 proc.stdout.close()
453
454 proc.stderr.read()
455 proc.stderr.close()
456
457 if proc.wait() != 0 or not cur:
458 print >>sys.stderr
459 print >>sys.stderr,\
460 "fatal: branch '%s' has not been signed" \
461 % branch
462 raise CloneFailure()
463
464 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
465 if m:
466 cur = m.group(1)
467 if not quiet:
468 print >>sys.stderr
469 print >>sys.stderr, \
470 "info: Ignoring branch '%s'; using tagged release '%s'" \
471 % (branch, cur)
472 print >>sys.stderr
473
Shawn O. Pearcef18cb762010-12-07 11:41:05 -0800474 env = os.environ.copy()
475 env['GNUPGHOME'] = gpg_dir.encode()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700476
477 cmd = [GIT, 'tag', '-v', cur]
478 proc = subprocess.Popen(cmd,
479 stdout = subprocess.PIPE,
480 stderr = subprocess.PIPE,
481 cwd = cwd,
482 env = env)
483 out = proc.stdout.read()
484 proc.stdout.close()
485
486 err = proc.stderr.read()
487 proc.stderr.close()
488
489 if proc.wait() != 0:
490 print >>sys.stderr
491 print >>sys.stderr, out
492 print >>sys.stderr, err
493 print >>sys.stderr
494 raise CloneFailure()
495 return '%s^0' % cur
496
497
498def _Checkout(cwd, branch, rev, quiet):
499 """Checkout an upstream branch into the repository and track it.
500 """
501 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
502 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
503 raise CloneFailure()
504
505 _SetConfig(cwd, 'branch.default.remote', 'origin')
506 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
507
508 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
509 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
510 raise CloneFailure()
511
512 cmd = [GIT, 'read-tree', '--reset', '-u']
513 if not quiet:
514 cmd.append('-v')
515 cmd.append('HEAD')
516 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
517 raise CloneFailure()
518
519
520def _FindRepo():
521 """Look for a repo installation, starting at the current directory.
522 """
523 dir = os.getcwd()
524 repo = None
525
Anthony Newnamdf14a702011-01-09 17:31:57 -0800526 olddir = None
527 while dir != '/' \
528 and dir != olddir \
529 and not repo:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700530 repo = os.path.join(dir, repodir, REPO_MAIN)
531 if not os.path.isfile(repo):
532 repo = None
Anthony Newnamdf14a702011-01-09 17:31:57 -0800533 olddir = dir
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700534 dir = os.path.dirname(dir)
535 return (repo, os.path.join(dir, repodir))
536
537
538class _Options:
539 help = False
540
541
542def _ParseArguments(args):
543 cmd = None
544 opt = _Options()
545 arg = []
546
547 for i in xrange(0, len(args)):
548 a = args[i]
549 if a == '-h' or a == '--help':
550 opt.help = True
551
552 elif not a.startswith('-'):
553 cmd = a
554 arg = args[i + 1:]
555 break
556 return cmd, opt, arg
557
558
559def _Usage():
560 print >>sys.stderr,\
561"""usage: repo COMMAND [ARGS]
562
563repo is not yet installed. Use "repo init" to install it here.
564
565The most commonly used repo commands are:
566
567 init Install repo in the current working directory
568 help Display detailed help on a command
569
570For access to the full online help, install repo ("repo init").
571"""
572 sys.exit(1)
573
574
575def _Help(args):
576 if args:
577 if args[0] == 'init':
578 init_optparse.print_help()
Trond Norbyed3fd5372011-01-03 11:35:15 +0100579 sys.exit(0)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700580 else:
581 print >>sys.stderr,\
582 "error: '%s' is not a bootstrap command.\n"\
583 ' For access to online help, install repo ("repo init").'\
584 % args[0]
585 else:
586 _Usage()
587 sys.exit(1)
588
589
590def _NotInstalled():
591 print >>sys.stderr,\
592'error: repo is not installed. Use "repo init" to install it here.'
593 sys.exit(1)
594
595
596def _NoCommands(cmd):
597 print >>sys.stderr,\
598"""error: command '%s' requires repo to be installed first.
599 Use "repo init" to install it here.""" % cmd
600 sys.exit(1)
601
602
603def _RunSelf(wrapper_path):
604 my_dir = os.path.dirname(wrapper_path)
605 my_main = os.path.join(my_dir, 'main.py')
606 my_git = os.path.join(my_dir, '.git')
607
608 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700609 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700610 'project.py',
611 'subcmds']:
612 if not os.path.exists(os.path.join(my_dir, name)):
613 return None, None
614 return my_main, my_git
615 return None, None
616
617
618def _SetDefaultsTo(gitdir):
619 global REPO_URL
620 global REPO_REV
621
622 REPO_URL = gitdir
623 proc = subprocess.Popen([GIT,
624 '--git-dir=%s' % gitdir,
625 'symbolic-ref',
626 'HEAD'],
627 stdout = subprocess.PIPE,
628 stderr = subprocess.PIPE)
629 REPO_REV = proc.stdout.read().strip()
630 proc.stdout.close()
631
632 proc.stderr.read()
633 proc.stderr.close()
634
635 if proc.wait() != 0:
636 print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
637 sys.exit(1)
638
639
640def main(orig_args):
641 main, dir = _FindRepo()
642 cmd, opt, args = _ParseArguments(orig_args)
643
644 wrapper_path = os.path.abspath(__file__)
645 my_main, my_git = _RunSelf(wrapper_path)
646
647 if not main:
648 if opt.help:
649 _Usage()
650 if cmd == 'help':
651 _Help(args)
652 if not cmd:
653 _NotInstalled()
654 if cmd == 'init':
655 if my_git:
656 _SetDefaultsTo(my_git)
657 try:
658 _Init(args)
659 except CloneFailure:
660 for root, dirs, files in os.walk(repodir, topdown=False):
661 for name in files:
662 os.remove(os.path.join(root, name))
663 for name in dirs:
664 os.rmdir(os.path.join(root, name))
665 os.rmdir(repodir)
666 sys.exit(1)
667 main, dir = _FindRepo()
668 else:
669 _NoCommands(cmd)
670
671 if my_main:
672 main = my_main
673
674 ver_str = '.'.join(map(lambda x: str(x), VERSION))
675 me = [main,
676 '--repo-dir=%s' % dir,
677 '--wrapper-version=%s' % ver_str,
678 '--wrapper-path=%s' % wrapper_path,
679 '--']
680 me.extend(orig_args)
681 me.extend(extra_args)
682 try:
683 os.execv(main, me)
684 except OSError, e:
685 print >>sys.stderr, "fatal: unable to start %s" % main
686 print >>sys.stderr, "fatal: %s" % e
687 sys.exit(148)
688
689
690if __name__ == '__main__':
691 main(sys.argv[1:])