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