blob: 3a545cc679d387fe4e6606f640cabbc94649e4bc [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001#!/bin/sh
2
3## repo default configuration
4##
Shawn O. Pearce24d8dfb2008-12-18 07:21:32 -08005REPO_URL='git://android.git.kernel.org/tools/repo.git'
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. Pearce5f947bb2009-07-03 17:24:17 -070031VERSION = (1, 9)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070032
33# increment this if the MAINTAINER_KEYS block is modified
34KEYRING_VERSION = (1,0)
35MAINTAINER_KEYS = """
36
37 Repo Maintainer <repo@android.kernel.org>
38-----BEGIN PGP PUBLIC KEY BLOCK-----
39Version: GnuPG v1.4.2.2 (GNU/Linux)
40
41mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
42WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+IXJDF5MJYcB8f22wAy15lUqPWi
43VCkk1l8qqLiuW0fo+ZkPY5qOgrvc0HW1SmdH649uNwqCbcKb6CxaTxzhOwCgj3AP
44xI1WfzLq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MNh18VtJJh+nwWeez/RueN4ig59gRTtkcc0PR
6135tX2DR8+xCCFVW/NcJ4PSePYzCuuLvp1vEDHnj41R52Fz51hgddT4rBsp0nL+5I
62socSOIIezw8T9vVzMY4ArCKFAVu2IVyBcahTfBS8q5EM63mONU6UVJEozfGljiMw
63xuQ7JwKcw0AUEKTKG7aBgBaTAgT8TOevpvlw91cAAwUP/jRkyVi/0WAb0qlEaq/S
64ouWxX1faR+vU3b+Y2/DGjtXQMzG0qpetaTHC/AxxHpgt/dCkWI6ljYDnxgPLwG0a
65Oasm94BjZc6vZwf1opFZUKsjOAAxRxNZyjUJKe4UZVuMTk6zo27Nt3LMnc0FO47v
66FcOjRyquvgNOS818irVHUf12waDx8gszKxQTTtFxU5/ePB2jZmhP6oXSe4K/LG5T
67+WBRPDrHiGPhCzJRzm9BP0lTnGCAj3o9W90STZa65RK7IaYpC8TB35JTBEbrrNCp
68w6lzd74LnNEp5eMlKDnXzUAgAH0yzCQeMl7t33QCdYx2hRs2wtTQSjGfAiNmj/WW
69Vl5Jn+2jCDnRLenKHwVRFsBX2e0BiRWt/i9Y8fjorLCXVj4z+7yW6DawdLkJorEo
70p3v5ILwfC7hVx4jHSnOgZ65L9s8EQdVr1ckN9243yta7rNgwfcqb60ILMFF1BRk/
710V7wCL+68UwwiQDvyMOQuqkysKLSDCLb7BFcyA7j6KG+5hpsREstFX2wK1yKeraz
725xGrFy8tfAaeBMIQ17gvFSp/suc9DYO0ICK2BISzq+F+ZiAKsjMYOBNdH/h0zobQ
73HTHs37+/QLMomGEGKZMWi0dShU2J5mNRQu3Hhxl3hHDVbt5CeJBb26aQcQrFz69W
74zE3GNvmJosh6leayjtI9P2A6iEkEGBECAAkFAkj3uiACGwwACgkQFlMNXpIPXGWp
75TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2
76=CMiZ
77-----END PGP PUBLIC KEY BLOCK-----
78"""
79
80GIT = 'git' # our git command
81MIN_GIT_VERSION = (1, 5, 4) # minimum supported git version
82repodir = '.repo' # name of repo's private directory
83S_repo = 'repo' # special repo reposiory
84S_manifests = 'manifests' # special manifest repository
85REPO_MAIN = S_repo + '/main.py' # main script
86
87
88import optparse
89import os
90import re
91import readline
92import subprocess
93import sys
94
95home_dot_repo = os.path.expanduser('~/.repoconfig')
96gpg_dir = os.path.join(home_dot_repo, 'gnupg')
97
98extra_args = []
99init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
100
101# Logging
102group = init_optparse.add_option_group('Logging options')
103group.add_option('-q', '--quiet',
104 dest="quiet", action="store_true", default=False,
105 help="be quiet")
106
107# Manifest
108group = init_optparse.add_option_group('Manifest options')
109group.add_option('-u', '--manifest-url',
110 dest='manifest_url',
111 help='manifest repository location', metavar='URL')
Shawn O. Pearce5f947bb2009-07-03 17:24:17 -0700112group.add_option('-o', '--origin',
113 dest='manifest_origin',
114 help="use REMOTE instead of 'origin' to track upstream",
115 metavar='REMOTE')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700116group.add_option('-b', '--manifest-branch',
117 dest='manifest_branch',
118 help='manifest branch or revision', metavar='REVISION')
119group.add_option('-m', '--manifest-name',
120 dest='manifest_name',
Shawn O. Pearceb3d2c922009-07-03 17:24:45 -0700121 help='initial manifest file (deprecated)',
122 metavar='NAME.xml')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800123group.add_option('--mirror',
124 dest='mirror', action='store_true',
125 help='mirror the forrest')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700126
127# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700128group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700129group.add_option('--repo-url',
130 dest='repo_url',
131 help='repo repository location', metavar='URL')
132group.add_option('--repo-branch',
133 dest='repo_branch',
134 help='repo branch or revision', metavar='REVISION')
135group.add_option('--no-repo-verify',
136 dest='no_repo_verify', action='store_true',
137 help='do not verify repo source code')
138
139
140class CloneFailure(Exception):
141 """Indicate the remote clone of repo itself failed.
142 """
143
144
145def _Init(args):
146 """Installs repo by cloning it over the network.
147 """
148 opt, args = init_optparse.parse_args(args)
149 if args or not opt.manifest_url:
150 init_optparse.print_usage()
151 sys.exit(1)
152
153 url = opt.repo_url
154 if not url:
155 url = REPO_URL
156 extra_args.append('--repo-url=%s' % url)
157
158 branch = opt.repo_branch
159 if not branch:
160 branch = REPO_REV
161 extra_args.append('--repo-branch=%s' % branch)
162
163 if branch.startswith('refs/heads/'):
164 branch = branch[len('refs/heads/'):]
165 if branch.startswith('refs/'):
166 print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
167 raise CloneFailure()
168
169 if not os.path.isdir(repodir):
170 try:
171 os.mkdir(repodir)
172 except OSError, e:
173 print >>sys.stderr, \
174 'fatal: cannot make %s directory: %s' % (
175 repodir, e.strerror)
176 # Don't faise CloneFailure; that would delete the
177 # name. Instead exit immediately.
178 #
179 sys.exit(1)
180
181 _CheckGitVersion()
182 try:
183 if _NeedSetupGnuPG():
184 can_verify = _SetupGnuPG(opt.quiet)
185 else:
186 can_verify = True
187
188 if not opt.quiet:
189 print >>sys.stderr, 'Getting repo ...'
190 print >>sys.stderr, ' from %s' % url
191
192 dst = os.path.abspath(os.path.join(repodir, S_repo))
193 _Clone(url, dst, opt.quiet)
194
195 if can_verify and not opt.no_repo_verify:
196 rev = _Verify(dst, branch, opt.quiet)
197 else:
198 rev = 'refs/remotes/origin/%s^0' % branch
199
200 _Checkout(dst, branch, rev, opt.quiet)
201 except CloneFailure:
202 if opt.quiet:
203 print >>sys.stderr, \
204 'fatal: repo init failed; run without --quiet to see why'
205 raise
206
207
208def _CheckGitVersion():
209 cmd = [GIT, '--version']
210 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
211 ver_str = proc.stdout.read().strip()
212 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700213 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700214
215 if not ver_str.startswith('git version '):
216 print >>sys.stderr, 'error: "%s" unsupported' % ver_str
217 raise CloneFailure()
218
219 ver_str = ver_str[len('git version '):].strip()
220 ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
221 if ver_act < MIN_GIT_VERSION:
222 need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
223 print >>sys.stderr, 'fatal: git %s or later required' % need
224 raise CloneFailure()
225
226
227def _NeedSetupGnuPG():
228 if not os.path.isdir(home_dot_repo):
229 return True
230
231 kv = os.path.join(home_dot_repo, 'keyring-version')
232 if not os.path.exists(kv):
233 return True
234
235 kv = open(kv).read()
236 if not kv:
237 return True
238
239 kv = tuple(map(lambda x: int(x), kv.split('.')))
240 if kv < KEYRING_VERSION:
241 return True
242 return False
243
244
245def _SetupGnuPG(quiet):
246 if not os.path.isdir(home_dot_repo):
247 try:
248 os.mkdir(home_dot_repo)
249 except OSError, e:
250 print >>sys.stderr, \
251 'fatal: cannot make %s directory: %s' % (
252 home_dot_repo, e.strerror)
253 sys.exit(1)
254
255 if not os.path.isdir(gpg_dir):
256 try:
257 os.mkdir(gpg_dir, 0700)
258 except OSError, e:
259 print >>sys.stderr, \
260 'fatal: cannot make %s directory: %s' % (
261 gpg_dir, e.strerror)
262 sys.exit(1)
263
264 env = dict(os.environ)
265 env['GNUPGHOME'] = gpg_dir
266
267 cmd = ['gpg', '--import']
268 try:
269 proc = subprocess.Popen(cmd,
270 env = env,
271 stdin = subprocess.PIPE)
272 except OSError, e:
273 if not quiet:
274 print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
275 print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
276 print >>sys.stderr
277 return False
278
279 proc.stdin.write(MAINTAINER_KEYS)
280 proc.stdin.close()
281
282 if proc.wait() != 0:
283 print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
284 sys.exit(1)
285 print
286
287 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
288 fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
289 fd.close()
290 return True
291
292
293def _SetConfig(local, name, value):
294 """Set a git configuration option to the specified value.
295 """
296 cmd = [GIT, 'config', name, value]
297 if subprocess.Popen(cmd, cwd = local).wait() != 0:
298 raise CloneFailure()
299
300
301def _Fetch(local, quiet, *args):
302 cmd = [GIT, 'fetch']
303 if quiet:
304 cmd.append('--quiet')
305 err = subprocess.PIPE
306 else:
307 err = None
308 cmd.extend(args)
309 cmd.append('origin')
310
311 proc = subprocess.Popen(cmd, cwd = local, stderr = err)
312 if err:
313 proc.stderr.read()
314 proc.stderr.close()
315 if proc.wait() != 0:
316 raise CloneFailure()
317
318
319def _Clone(url, local, quiet):
320 """Clones a git repository to a new subdirectory of repodir
321 """
322 try:
323 os.mkdir(local)
324 except OSError, e:
325 print >>sys.stderr, \
326 'fatal: cannot make %s directory: %s' \
327 % (local, e.strerror)
328 raise CloneFailure()
329
330 cmd = [GIT, 'init', '--quiet']
331 try:
332 proc = subprocess.Popen(cmd, cwd = local)
333 except OSError, e:
334 print >>sys.stderr
335 print >>sys.stderr, "fatal: '%s' is not available" % GIT
336 print >>sys.stderr, 'fatal: %s' % e
337 print >>sys.stderr
338 print >>sys.stderr, 'Please make sure %s is installed'\
339 ' and in your path.' % GIT
340 raise CloneFailure()
341 if proc.wait() != 0:
342 print >>sys.stderr, 'fatal: could not create %s' % local
343 raise CloneFailure()
344
345 _SetConfig(local, 'remote.origin.url', url)
346 _SetConfig(local, 'remote.origin.fetch',
347 '+refs/heads/*:refs/remotes/origin/*')
348 _Fetch(local, quiet)
349 _Fetch(local, quiet, '--tags')
350
351
352def _Verify(cwd, branch, quiet):
353 """Verify the branch has been signed by a tag.
354 """
355 cmd = [GIT, 'describe', 'origin/%s' % branch]
356 proc = subprocess.Popen(cmd,
357 stdout=subprocess.PIPE,
358 stderr=subprocess.PIPE,
359 cwd = cwd)
360 cur = proc.stdout.read().strip()
361 proc.stdout.close()
362
363 proc.stderr.read()
364 proc.stderr.close()
365
366 if proc.wait() != 0 or not cur:
367 print >>sys.stderr
368 print >>sys.stderr,\
369 "fatal: branch '%s' has not been signed" \
370 % branch
371 raise CloneFailure()
372
373 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
374 if m:
375 cur = m.group(1)
376 if not quiet:
377 print >>sys.stderr
378 print >>sys.stderr, \
379 "info: Ignoring branch '%s'; using tagged release '%s'" \
380 % (branch, cur)
381 print >>sys.stderr
382
383 env = dict(os.environ)
384 env['GNUPGHOME'] = gpg_dir
385
386 cmd = [GIT, 'tag', '-v', cur]
387 proc = subprocess.Popen(cmd,
388 stdout = subprocess.PIPE,
389 stderr = subprocess.PIPE,
390 cwd = cwd,
391 env = env)
392 out = proc.stdout.read()
393 proc.stdout.close()
394
395 err = proc.stderr.read()
396 proc.stderr.close()
397
398 if proc.wait() != 0:
399 print >>sys.stderr
400 print >>sys.stderr, out
401 print >>sys.stderr, err
402 print >>sys.stderr
403 raise CloneFailure()
404 return '%s^0' % cur
405
406
407def _Checkout(cwd, branch, rev, quiet):
408 """Checkout an upstream branch into the repository and track it.
409 """
410 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
411 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
412 raise CloneFailure()
413
414 _SetConfig(cwd, 'branch.default.remote', 'origin')
415 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
416
417 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
418 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
419 raise CloneFailure()
420
421 cmd = [GIT, 'read-tree', '--reset', '-u']
422 if not quiet:
423 cmd.append('-v')
424 cmd.append('HEAD')
425 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
426 raise CloneFailure()
427
428
429def _FindRepo():
430 """Look for a repo installation, starting at the current directory.
431 """
432 dir = os.getcwd()
433 repo = None
434
Anthony Newnamb0f9a022010-11-29 13:15:24 -0600435 olddir = None
436 while dir != '/' \
437 and dir != olddir \
438 and not repo:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700439 repo = os.path.join(dir, repodir, REPO_MAIN)
440 if not os.path.isfile(repo):
441 repo = None
Anthony Newnamb0f9a022010-11-29 13:15:24 -0600442 olddir = dir
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700443 dir = os.path.dirname(dir)
444 return (repo, os.path.join(dir, repodir))
445
446
447class _Options:
448 help = False
449
450
451def _ParseArguments(args):
452 cmd = None
453 opt = _Options()
454 arg = []
455
456 for i in xrange(0, len(args)):
457 a = args[i]
458 if a == '-h' or a == '--help':
459 opt.help = True
460
461 elif not a.startswith('-'):
462 cmd = a
463 arg = args[i + 1:]
464 break
465 return cmd, opt, arg
466
467
468def _Usage():
469 print >>sys.stderr,\
470"""usage: repo COMMAND [ARGS]
471
472repo is not yet installed. Use "repo init" to install it here.
473
474The most commonly used repo commands are:
475
476 init Install repo in the current working directory
477 help Display detailed help on a command
478
479For access to the full online help, install repo ("repo init").
480"""
481 sys.exit(1)
482
483
484def _Help(args):
485 if args:
486 if args[0] == 'init':
487 init_optparse.print_help()
488 else:
489 print >>sys.stderr,\
490 "error: '%s' is not a bootstrap command.\n"\
491 ' For access to online help, install repo ("repo init").'\
492 % args[0]
493 else:
494 _Usage()
495 sys.exit(1)
496
497
498def _NotInstalled():
499 print >>sys.stderr,\
500'error: repo is not installed. Use "repo init" to install it here.'
501 sys.exit(1)
502
503
504def _NoCommands(cmd):
505 print >>sys.stderr,\
506"""error: command '%s' requires repo to be installed first.
507 Use "repo init" to install it here.""" % cmd
508 sys.exit(1)
509
510
511def _RunSelf(wrapper_path):
512 my_dir = os.path.dirname(wrapper_path)
513 my_main = os.path.join(my_dir, 'main.py')
514 my_git = os.path.join(my_dir, '.git')
515
516 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700517 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700518 'project.py',
519 'subcmds']:
520 if not os.path.exists(os.path.join(my_dir, name)):
521 return None, None
522 return my_main, my_git
523 return None, None
524
525
526def _SetDefaultsTo(gitdir):
527 global REPO_URL
528 global REPO_REV
529
530 REPO_URL = gitdir
531 proc = subprocess.Popen([GIT,
532 '--git-dir=%s' % gitdir,
533 'symbolic-ref',
534 'HEAD'],
535 stdout = subprocess.PIPE,
536 stderr = subprocess.PIPE)
537 REPO_REV = proc.stdout.read().strip()
538 proc.stdout.close()
539
540 proc.stderr.read()
541 proc.stderr.close()
542
543 if proc.wait() != 0:
544 print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
545 sys.exit(1)
546
547
548def main(orig_args):
549 main, dir = _FindRepo()
550 cmd, opt, args = _ParseArguments(orig_args)
551
552 wrapper_path = os.path.abspath(__file__)
553 my_main, my_git = _RunSelf(wrapper_path)
554
555 if not main:
556 if opt.help:
557 _Usage()
558 if cmd == 'help':
559 _Help(args)
560 if not cmd:
561 _NotInstalled()
562 if cmd == 'init':
563 if my_git:
564 _SetDefaultsTo(my_git)
565 try:
566 _Init(args)
567 except CloneFailure:
568 for root, dirs, files in os.walk(repodir, topdown=False):
569 for name in files:
570 os.remove(os.path.join(root, name))
571 for name in dirs:
572 os.rmdir(os.path.join(root, name))
573 os.rmdir(repodir)
574 sys.exit(1)
575 main, dir = _FindRepo()
576 else:
577 _NoCommands(cmd)
578
579 if my_main:
580 main = my_main
581
582 ver_str = '.'.join(map(lambda x: str(x), VERSION))
583 me = [main,
584 '--repo-dir=%s' % dir,
585 '--wrapper-version=%s' % ver_str,
586 '--wrapper-path=%s' % wrapper_path,
587 '--']
588 me.extend(orig_args)
589 me.extend(extra_args)
590 try:
591 os.execv(main, me)
592 except OSError, e:
593 print >>sys.stderr, "fatal: unable to start %s" % main
594 print >>sys.stderr, "fatal: %s" % e
595 sys.exit(148)
596
597
598if __name__ == '__main__':
599 main(sys.argv[1:])
600