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