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