blob: 13742559307bb29df437e3ca18cc85d2ddd55894 [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. Pearce24d8dfb2008-12-18 07:21:32 -080031VERSION = (1, 8)
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')
112group.add_option('-b', '--manifest-branch',
113 dest='manifest_branch',
114 help='manifest branch or revision', metavar='REVISION')
115group.add_option('-m', '--manifest-name',
116 dest='manifest_name',
117 help='initial manifest file', metavar='NAME.xml')
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800118group.add_option('--mirror',
119 dest='mirror', action='store_true',
120 help='mirror the forrest')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700121
122# Tool
Shawn O. Pearcefd89b672009-04-18 11:28:57 -0700123group = init_optparse.add_option_group('repo Version options')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700124group.add_option('--repo-url',
125 dest='repo_url',
126 help='repo repository location', metavar='URL')
127group.add_option('--repo-branch',
128 dest='repo_branch',
129 help='repo branch or revision', metavar='REVISION')
130group.add_option('--no-repo-verify',
131 dest='no_repo_verify', action='store_true',
132 help='do not verify repo source code')
133
134
135class CloneFailure(Exception):
136 """Indicate the remote clone of repo itself failed.
137 """
138
139
140def _Init(args):
141 """Installs repo by cloning it over the network.
142 """
143 opt, args = init_optparse.parse_args(args)
144 if args or not opt.manifest_url:
145 init_optparse.print_usage()
146 sys.exit(1)
147
148 url = opt.repo_url
149 if not url:
150 url = REPO_URL
151 extra_args.append('--repo-url=%s' % url)
152
153 branch = opt.repo_branch
154 if not branch:
155 branch = REPO_REV
156 extra_args.append('--repo-branch=%s' % branch)
157
158 if branch.startswith('refs/heads/'):
159 branch = branch[len('refs/heads/'):]
160 if branch.startswith('refs/'):
161 print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
162 raise CloneFailure()
163
164 if not os.path.isdir(repodir):
165 try:
166 os.mkdir(repodir)
167 except OSError, e:
168 print >>sys.stderr, \
169 'fatal: cannot make %s directory: %s' % (
170 repodir, e.strerror)
171 # Don't faise CloneFailure; that would delete the
172 # name. Instead exit immediately.
173 #
174 sys.exit(1)
175
176 _CheckGitVersion()
177 try:
178 if _NeedSetupGnuPG():
179 can_verify = _SetupGnuPG(opt.quiet)
180 else:
181 can_verify = True
182
183 if not opt.quiet:
184 print >>sys.stderr, 'Getting repo ...'
185 print >>sys.stderr, ' from %s' % url
186
187 dst = os.path.abspath(os.path.join(repodir, S_repo))
188 _Clone(url, dst, opt.quiet)
189
190 if can_verify and not opt.no_repo_verify:
191 rev = _Verify(dst, branch, opt.quiet)
192 else:
193 rev = 'refs/remotes/origin/%s^0' % branch
194
195 _Checkout(dst, branch, rev, opt.quiet)
196 except CloneFailure:
197 if opt.quiet:
198 print >>sys.stderr, \
199 'fatal: repo init failed; run without --quiet to see why'
200 raise
201
202
203def _CheckGitVersion():
204 cmd = [GIT, '--version']
205 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
206 ver_str = proc.stdout.read().strip()
207 proc.stdout.close()
Shawn O. Pearce16191342008-10-28 08:33:34 -0700208 proc.wait()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700209
210 if not ver_str.startswith('git version '):
211 print >>sys.stderr, 'error: "%s" unsupported' % ver_str
212 raise CloneFailure()
213
214 ver_str = ver_str[len('git version '):].strip()
215 ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
216 if ver_act < MIN_GIT_VERSION:
217 need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
218 print >>sys.stderr, 'fatal: git %s or later required' % need
219 raise CloneFailure()
220
221
222def _NeedSetupGnuPG():
223 if not os.path.isdir(home_dot_repo):
224 return True
225
226 kv = os.path.join(home_dot_repo, 'keyring-version')
227 if not os.path.exists(kv):
228 return True
229
230 kv = open(kv).read()
231 if not kv:
232 return True
233
234 kv = tuple(map(lambda x: int(x), kv.split('.')))
235 if kv < KEYRING_VERSION:
236 return True
237 return False
238
239
240def _SetupGnuPG(quiet):
241 if not os.path.isdir(home_dot_repo):
242 try:
243 os.mkdir(home_dot_repo)
244 except OSError, e:
245 print >>sys.stderr, \
246 'fatal: cannot make %s directory: %s' % (
247 home_dot_repo, e.strerror)
248 sys.exit(1)
249
250 if not os.path.isdir(gpg_dir):
251 try:
252 os.mkdir(gpg_dir, 0700)
253 except OSError, e:
254 print >>sys.stderr, \
255 'fatal: cannot make %s directory: %s' % (
256 gpg_dir, e.strerror)
257 sys.exit(1)
258
259 env = dict(os.environ)
260 env['GNUPGHOME'] = gpg_dir
261
262 cmd = ['gpg', '--import']
263 try:
264 proc = subprocess.Popen(cmd,
265 env = env,
266 stdin = subprocess.PIPE)
267 except OSError, e:
268 if not quiet:
269 print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
270 print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
271 print >>sys.stderr
272 return False
273
274 proc.stdin.write(MAINTAINER_KEYS)
275 proc.stdin.close()
276
277 if proc.wait() != 0:
278 print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
279 sys.exit(1)
280 print
281
282 fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
283 fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
284 fd.close()
285 return True
286
287
288def _SetConfig(local, name, value):
289 """Set a git configuration option to the specified value.
290 """
291 cmd = [GIT, 'config', name, value]
292 if subprocess.Popen(cmd, cwd = local).wait() != 0:
293 raise CloneFailure()
294
295
296def _Fetch(local, quiet, *args):
297 cmd = [GIT, 'fetch']
298 if quiet:
299 cmd.append('--quiet')
300 err = subprocess.PIPE
301 else:
302 err = None
303 cmd.extend(args)
304 cmd.append('origin')
305
306 proc = subprocess.Popen(cmd, cwd = local, stderr = err)
307 if err:
308 proc.stderr.read()
309 proc.stderr.close()
310 if proc.wait() != 0:
311 raise CloneFailure()
312
313
314def _Clone(url, local, quiet):
315 """Clones a git repository to a new subdirectory of repodir
316 """
317 try:
318 os.mkdir(local)
319 except OSError, e:
320 print >>sys.stderr, \
321 'fatal: cannot make %s directory: %s' \
322 % (local, e.strerror)
323 raise CloneFailure()
324
325 cmd = [GIT, 'init', '--quiet']
326 try:
327 proc = subprocess.Popen(cmd, cwd = local)
328 except OSError, e:
329 print >>sys.stderr
330 print >>sys.stderr, "fatal: '%s' is not available" % GIT
331 print >>sys.stderr, 'fatal: %s' % e
332 print >>sys.stderr
333 print >>sys.stderr, 'Please make sure %s is installed'\
334 ' and in your path.' % GIT
335 raise CloneFailure()
336 if proc.wait() != 0:
337 print >>sys.stderr, 'fatal: could not create %s' % local
338 raise CloneFailure()
339
340 _SetConfig(local, 'remote.origin.url', url)
341 _SetConfig(local, 'remote.origin.fetch',
342 '+refs/heads/*:refs/remotes/origin/*')
343 _Fetch(local, quiet)
344 _Fetch(local, quiet, '--tags')
345
346
347def _Verify(cwd, branch, quiet):
348 """Verify the branch has been signed by a tag.
349 """
350 cmd = [GIT, 'describe', 'origin/%s' % branch]
351 proc = subprocess.Popen(cmd,
352 stdout=subprocess.PIPE,
353 stderr=subprocess.PIPE,
354 cwd = cwd)
355 cur = proc.stdout.read().strip()
356 proc.stdout.close()
357
358 proc.stderr.read()
359 proc.stderr.close()
360
361 if proc.wait() != 0 or not cur:
362 print >>sys.stderr
363 print >>sys.stderr,\
364 "fatal: branch '%s' has not been signed" \
365 % branch
366 raise CloneFailure()
367
368 m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
369 if m:
370 cur = m.group(1)
371 if not quiet:
372 print >>sys.stderr
373 print >>sys.stderr, \
374 "info: Ignoring branch '%s'; using tagged release '%s'" \
375 % (branch, cur)
376 print >>sys.stderr
377
378 env = dict(os.environ)
379 env['GNUPGHOME'] = gpg_dir
380
381 cmd = [GIT, 'tag', '-v', cur]
382 proc = subprocess.Popen(cmd,
383 stdout = subprocess.PIPE,
384 stderr = subprocess.PIPE,
385 cwd = cwd,
386 env = env)
387 out = proc.stdout.read()
388 proc.stdout.close()
389
390 err = proc.stderr.read()
391 proc.stderr.close()
392
393 if proc.wait() != 0:
394 print >>sys.stderr
395 print >>sys.stderr, out
396 print >>sys.stderr, err
397 print >>sys.stderr
398 raise CloneFailure()
399 return '%s^0' % cur
400
401
402def _Checkout(cwd, branch, rev, quiet):
403 """Checkout an upstream branch into the repository and track it.
404 """
405 cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
406 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
407 raise CloneFailure()
408
409 _SetConfig(cwd, 'branch.default.remote', 'origin')
410 _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
411
412 cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
413 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
414 raise CloneFailure()
415
416 cmd = [GIT, 'read-tree', '--reset', '-u']
417 if not quiet:
418 cmd.append('-v')
419 cmd.append('HEAD')
420 if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
421 raise CloneFailure()
422
423
424def _FindRepo():
425 """Look for a repo installation, starting at the current directory.
426 """
427 dir = os.getcwd()
428 repo = None
429
430 while dir != '/' and not repo:
431 repo = os.path.join(dir, repodir, REPO_MAIN)
432 if not os.path.isfile(repo):
433 repo = None
434 dir = os.path.dirname(dir)
435 return (repo, os.path.join(dir, repodir))
436
437
438class _Options:
439 help = False
440
441
442def _ParseArguments(args):
443 cmd = None
444 opt = _Options()
445 arg = []
446
447 for i in xrange(0, len(args)):
448 a = args[i]
449 if a == '-h' or a == '--help':
450 opt.help = True
451
452 elif not a.startswith('-'):
453 cmd = a
454 arg = args[i + 1:]
455 break
456 return cmd, opt, arg
457
458
459def _Usage():
460 print >>sys.stderr,\
461"""usage: repo COMMAND [ARGS]
462
463repo is not yet installed. Use "repo init" to install it here.
464
465The most commonly used repo commands are:
466
467 init Install repo in the current working directory
468 help Display detailed help on a command
469
470For access to the full online help, install repo ("repo init").
471"""
472 sys.exit(1)
473
474
475def _Help(args):
476 if args:
477 if args[0] == 'init':
478 init_optparse.print_help()
479 else:
480 print >>sys.stderr,\
481 "error: '%s' is not a bootstrap command.\n"\
482 ' For access to online help, install repo ("repo init").'\
483 % args[0]
484 else:
485 _Usage()
486 sys.exit(1)
487
488
489def _NotInstalled():
490 print >>sys.stderr,\
491'error: repo is not installed. Use "repo init" to install it here.'
492 sys.exit(1)
493
494
495def _NoCommands(cmd):
496 print >>sys.stderr,\
497"""error: command '%s' requires repo to be installed first.
498 Use "repo init" to install it here.""" % cmd
499 sys.exit(1)
500
501
502def _RunSelf(wrapper_path):
503 my_dir = os.path.dirname(wrapper_path)
504 my_main = os.path.join(my_dir, 'main.py')
505 my_git = os.path.join(my_dir, '.git')
506
507 if os.path.isfile(my_main) and os.path.isdir(my_git):
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700508 for name in ['git_config.py',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700509 'project.py',
510 'subcmds']:
511 if not os.path.exists(os.path.join(my_dir, name)):
512 return None, None
513 return my_main, my_git
514 return None, None
515
516
517def _SetDefaultsTo(gitdir):
518 global REPO_URL
519 global REPO_REV
520
521 REPO_URL = gitdir
522 proc = subprocess.Popen([GIT,
523 '--git-dir=%s' % gitdir,
524 'symbolic-ref',
525 'HEAD'],
526 stdout = subprocess.PIPE,
527 stderr = subprocess.PIPE)
528 REPO_REV = proc.stdout.read().strip()
529 proc.stdout.close()
530
531 proc.stderr.read()
532 proc.stderr.close()
533
534 if proc.wait() != 0:
535 print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
536 sys.exit(1)
537
538
539def main(orig_args):
540 main, dir = _FindRepo()
541 cmd, opt, args = _ParseArguments(orig_args)
542
543 wrapper_path = os.path.abspath(__file__)
544 my_main, my_git = _RunSelf(wrapper_path)
545
546 if not main:
547 if opt.help:
548 _Usage()
549 if cmd == 'help':
550 _Help(args)
551 if not cmd:
552 _NotInstalled()
553 if cmd == 'init':
554 if my_git:
555 _SetDefaultsTo(my_git)
556 try:
557 _Init(args)
558 except CloneFailure:
559 for root, dirs, files in os.walk(repodir, topdown=False):
560 for name in files:
561 os.remove(os.path.join(root, name))
562 for name in dirs:
563 os.rmdir(os.path.join(root, name))
564 os.rmdir(repodir)
565 sys.exit(1)
566 main, dir = _FindRepo()
567 else:
568 _NoCommands(cmd)
569
570 if my_main:
571 main = my_main
572
573 ver_str = '.'.join(map(lambda x: str(x), VERSION))
574 me = [main,
575 '--repo-dir=%s' % dir,
576 '--wrapper-version=%s' % ver_str,
577 '--wrapper-path=%s' % wrapper_path,
578 '--']
579 me.extend(orig_args)
580 me.extend(extra_args)
581 try:
582 os.execv(main, me)
583 except OSError, e:
584 print >>sys.stderr, "fatal: unable to start %s" % main
585 print >>sys.stderr, "fatal: %s" % e
586 sys.exit(148)
587
588
589if __name__ == '__main__':
590 main(sys.argv[1:])
591