repo 22.1 KB
Newer Older
1 2 3 4
#!/bin/sh

## repo default configuration
##
5
REPO_URL='https://git.chromium.org/git/external/repo'
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
REPO_REV='stable'

# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

magic='--calling-python-from-/bin/sh--'
"""exec" python -E "$0" "$@" """#$magic"
if __name__ == '__main__':
  import sys
  if sys.argv[-1] == '#%s' % magic:
    del sys.argv[-1]
del magic

# increment this whenever we make important changes to this script
31
VERSION = (1, 18)
32 33

# increment this if the MAINTAINER_KEYS block is modified
34
KEYRING_VERSION = (1,1)
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
MAINTAINER_KEYS = """

     Repo Maintainer <repo@android.kernel.org>
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.2.2 (GNU/Linux)

mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+IXJDF5MJYcB8f22wAy15lUqPWi
VCkk1l8qqLiuW0fo+ZkPY5qOgrvc0HW1SmdH649uNwqCbcKb6CxaTxzhOwCgj3AP
xI1WfzLqdJjsm1Nq98L0cLcD/iNsILCuw44PRds3J75YP0pze7YF/6WFMB6QSFGu
aUX1FsTTztKNXGms8i5b2l1B8JaLRWq/jOnZzyl1zrUJhkc0JgyZW5oNLGyWGhKD
Fxp5YpHuIuMImopWEMFIR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iMw
xuQ7JwKcw0AUEKTKG7aBgBaTAgT8TOevpvlw91cAAwUP/jRkyVi/0WAb0qlEaq/S
ouWxX1faR+vU3b+Y2/DGjtXQMzG0qpetaTHC/AxxHpgt/dCkWI6ljYDnxgPLwG0a
Oasm94BjZc6vZwf1opFZUKsjOAAxRxNZyjUJKe4UZVuMTk6zo27Nt3LMnc0FO47v
FcOjRyquvgNOS818irVHUf12waDx8gszKxQTTtFxU5/ePB2jZmhP6oXSe4K/LG5T
+WBRPDrHiGPhCzJRzm9BP0lTnGCAj3o9W90STZa65RK7IaYpC8TB35JTBEbrrNCp
w6lzd74LnNEp5eMlKDnXzUAgAH0yzCQeMl7t33QCdYx2hRs2wtTQSjGfAiNmj/WW
Vl5Jn+2jCDnRLenKHwVRFsBX2e0BiRWt/i9Y8fjorLCXVj4z+7yW6DawdLkJorEo
p3v5ILwfC7hVx4jHSnOgZ65L9s8EQdVr1ckN9243yta7rNgwfcqb60ILMFF1BRk/
0V7wCL+68UwwiQDvyMOQuqkysKLSDCLb7BFcyA7j6KG+5hpsREstFX2wK1yKeraz
5xGrFy8tfAaeBMIQ17gvFSp/suc9DYO0ICK2BISzq+F+ZiAKsjMYOBNdH/h0zobQ
HTHs37+/QLMomGEGKZMWi0dShU2J5mNRQu3Hhxl3hHDVbt5CeJBb26aQcQrFz69W
zE3GNvmJosh6leayjtI9P2A6iEkEGBECAAkFAkj3uiACGwwACgkQFlMNXpIPXGWp
TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2
=CMiZ
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
-----END PGP PUBLIC KEY BLOCK-----

     Conley Owens <cco3@android.com>
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.11 (GNU/Linux)

mQENBFBiLPwBCACvISTASOgFXwADw2GYRH2I2z9RvYkYoZ6ThTTNlMXbbYYKO2Wo
a9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W3oT/9M9mO9ei/Bc/1D7Dz6qNV+0vg
uSVJxM2Bl6GalHPZLhHntFEdIA6EdoUAEQEAAYkBHwQYAQIACQUCUGIs/AIbDAAK
CRAZJpRVM4hxpNfkB/0W/hP5WK/NETXBlWXXW7JPaWO2c5kGwD0lnj5RRmridyo1
vbm5PdM91jOsDQYqRu6YOoYBnDnEhB2wL2bPh34HWwwrA+LwB8hlcAV2z1bdwyfl
3R823fReKN3QcvLHzmvZPrF4Rk97M9UIyKS0RtnfTWykRgDWHIsrtQPoNwsXrWoT
9LrM2v+1+9mp3vuXnE473/NHxmiWEQH9Ez+O/mOxQ7rSOlqGRiKq/IBZCfioJOtV
fTQeIu/yASZnsLBqr6SJEGwYBoWcyjG++k4fyw8ocOAo4uGDYbxgN7yYfNQ0OH7o
V6pfUgqKLWa/aK7/N1ZHnPdFLD8Xt0Dmy4BPwrKC
=O7am
109 110 111 112 113 114
-----END PGP PUBLIC KEY BLOCK-----
"""

GIT = 'git'                     # our git command
MIN_GIT_VERSION = (1, 5, 4)     # minimum supported git version
repodir = '.repo'               # name of repo's private directory
115
S_repo = 'repo'                 # special repo repository
116 117 118 119 120 121 122 123 124
S_manifests = 'manifests'       # special manifest repository
REPO_MAIN = S_repo + '/main.py' # main script


import optparse
import os
import re
import subprocess
import sys
125
import urllib2
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

home_dot_repo = os.path.expanduser('~/.repoconfig')
gpg_dir = os.path.join(home_dot_repo, 'gnupg')

extra_args = []
init_optparse = optparse.OptionParser(usage="repo init -u url [options]")

# Logging
group = init_optparse.add_option_group('Logging options')
group.add_option('-q', '--quiet',
                 dest="quiet", action="store_true", default=False,
                 help="be quiet")

# Manifest
group = init_optparse.add_option_group('Manifest options')
group.add_option('-u', '--manifest-url',
                 dest='manifest_url',
                 help='manifest repository location', metavar='URL')
group.add_option('-b', '--manifest-branch',
                 dest='manifest_branch',
                 help='manifest branch or revision', metavar='REVISION')
group.add_option('-m', '--manifest-name',
                 dest='manifest_name',
149
                 help='initial manifest file', metavar='NAME.xml')
150 151 152
group.add_option('--mirror',
                 dest='mirror', action='store_true',
                 help='mirror the forrest')
153 154 155
group.add_option('--reference',
                 dest='reference',
                 help='location of mirror directory', metavar='DIR')
156 157 158
group.add_option('--depth', type='int', default=None,
                 dest='depth',
                 help='create a shallow clone with given depth; see git clone')
159 160 161 162 163 164
group.add_option('-g', '--groups',
                 dest='groups', default='default',
                 help='restrict manifest projects to ones with a specified group',
                 metavar='GROUP')
group.add_option('-p', '--platform',
                 dest='platform', default="auto",
165
                 help='restrict manifest projects to ones with a specified '
166 167
                      'platform group [auto|all|none|linux|darwin|...]',
                 metavar='PLATFORM')
168

169 170 171 172 173 174 175 176 177 178 179 180 181

# Tool
group = init_optparse.add_option_group('repo Version options')
group.add_option('--repo-url',
                 dest='repo_url',
                 help='repo repository location', metavar='URL')
group.add_option('--repo-branch',
                 dest='repo_branch',
                 help='repo branch or revision', metavar='REVISION')
group.add_option('--no-repo-verify',
                 dest='no_repo_verify', action='store_true',
                 help='do not verify repo source code')

182 183 184 185 186
# Other
group = init_optparse.add_option_group('Other options')
group.add_option('--config-name',
                 dest='config_name', action="store_true", default=False,
                 help='Always prompt for name/e-mail')
187 188 189 190 191 192 193 194 195 196

class CloneFailure(Exception):
  """Indicate the remote clone of repo itself failed.
  """


def _Init(args):
  """Installs repo by cloning it over the network.
  """
  opt, args = init_optparse.parse_args(args)
197
  if args:
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    init_optparse.print_usage()
    sys.exit(1)

  url = opt.repo_url
  if not url:
    url = REPO_URL
    extra_args.append('--repo-url=%s' % url)

  branch = opt.repo_branch
  if not branch:
    branch = REPO_REV
    extra_args.append('--repo-branch=%s' % branch)

  if branch.startswith('refs/heads/'):
    branch = branch[len('refs/heads/'):]
  if branch.startswith('refs/'):
    print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
    raise CloneFailure()

  if not os.path.isdir(repodir):
    try:
      os.mkdir(repodir)
220
    except OSError as e:
221 222 223 224 225 226 227 228 229 230
      print >>sys.stderr, \
            'fatal: cannot make %s directory: %s' % (
            repodir, e.strerror)
      # Don't faise CloneFailure; that would delete the
      # name. Instead exit immediately.
      #
      sys.exit(1)

  _CheckGitVersion()
  try:
231 232
    if NeedSetupGnuPG():
      can_verify = SetupGnuPG(opt.quiet)
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    else:
      can_verify = True

    dst = os.path.abspath(os.path.join(repodir, S_repo))
    _Clone(url, dst, opt.quiet)

    if can_verify and not opt.no_repo_verify:
      rev = _Verify(dst, branch, opt.quiet)
    else:
      rev = 'refs/remotes/origin/%s^0' % branch

    _Checkout(dst, branch, rev, opt.quiet)
  except CloneFailure:
    if opt.quiet:
      print >>sys.stderr, \
        'fatal: repo init failed; run without --quiet to see why'
    raise


def _CheckGitVersion():
  cmd = [GIT, '--version']
254 255
  try:
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
256
  except OSError as e:
257 258 259 260 261 262 263 264
    print >>sys.stderr
    print >>sys.stderr, "fatal: '%s' is not available" % GIT
    print >>sys.stderr, 'fatal: %s' % e
    print >>sys.stderr
    print >>sys.stderr, 'Please make sure %s is installed'\
                        ' and in your path.' % GIT
    raise CloneFailure()

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
  ver_str = proc.stdout.read().strip()
  proc.stdout.close()
  proc.wait()

  if not ver_str.startswith('git version '):
    print >>sys.stderr, 'error: "%s" unsupported' % ver_str
    raise CloneFailure()

  ver_str = ver_str[len('git version '):].strip()
  ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
  if ver_act < MIN_GIT_VERSION:
    need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
    print >>sys.stderr, 'fatal: git %s or later required' % need
    raise CloneFailure()


281
def NeedSetupGnuPG():
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
  if not os.path.isdir(home_dot_repo):
    return True

  kv = os.path.join(home_dot_repo, 'keyring-version')
  if not os.path.exists(kv):
    return True

  kv = open(kv).read()
  if not kv:
    return True

  kv = tuple(map(lambda x: int(x), kv.split('.')))
  if kv < KEYRING_VERSION:
    return True
  return False


299
def SetupGnuPG(quiet):
300 301 302
  if not os.path.isdir(home_dot_repo):
    try:
      os.mkdir(home_dot_repo)
303
    except OSError as e:
304 305 306 307 308 309 310 311
      print >>sys.stderr, \
            'fatal: cannot make %s directory: %s' % (
            home_dot_repo, e.strerror)
      sys.exit(1)

  if not os.path.isdir(gpg_dir):
    try:
      os.mkdir(gpg_dir, 0700)
312
    except OSError as e:
313 314 315 316 317
      print >>sys.stderr, \
            'fatal: cannot make %s directory: %s' % (
            gpg_dir, e.strerror)
      sys.exit(1)

318 319
  env = os.environ.copy()
  env['GNUPGHOME'] = gpg_dir.encode()
320 321 322 323 324 325

  cmd = ['gpg', '--import']
  try:
    proc = subprocess.Popen(cmd,
                            env = env,
                            stdin = subprocess.PIPE)
326
  except OSError as e:
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    if not quiet:
      print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
      print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
      print >>sys.stderr
    return False

  proc.stdin.write(MAINTAINER_KEYS)
  proc.stdin.close()

  if proc.wait() != 0:
    print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
    sys.exit(1)
  print

  fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
  fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
  fd.close()
  return True


def _SetConfig(local, name, value):
  """Set a git configuration option to the specified value.
  """
  cmd = [GIT, 'config', name, value]
  if subprocess.Popen(cmd, cwd = local).wait() != 0:
    raise CloneFailure()


355 356 357 358 359 360 361 362 363
def _InitHttp():
  handlers = []

  mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
  try:
    import netrc
    n = netrc.netrc()
    for host in n.hosts:
      p = n.hosts[host]
364 365
      mgr.add_password(p[1], 'http://%s/'  % host, p[0], p[2])
      mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
366 367 368
  except:
    pass
  handlers.append(urllib2.HTTPBasicAuthHandler(mgr))
369
  handlers.append(urllib2.HTTPDigestAuthHandler(mgr))
370 371 372 373 374 375 376 377 378 379 380 381 382

  if 'http_proxy' in os.environ:
    url = os.environ['http_proxy']
    handlers.append(urllib2.ProxyHandler({'http': url, 'https': url}))
  if 'REPO_CURL_VERBOSE' in os.environ:
    handlers.append(urllib2.HTTPHandler(debuglevel=1))
    handlers.append(urllib2.HTTPSHandler(debuglevel=1))
  urllib2.install_opener(urllib2.build_opener(*handlers))

def _Fetch(url, local, src, quiet):
  if not quiet:
    print >>sys.stderr, 'Get %s' % url

383 384 385 386 387 388
  cmd = [GIT, 'fetch']
  if quiet:
    cmd.append('--quiet')
    err = subprocess.PIPE
  else:
    err = None
389 390 391
  cmd.append(src)
  cmd.append('+refs/heads/*:refs/remotes/origin/*')
  cmd.append('refs/tags/*:refs/tags/*')
392 393 394 395 396 397 398 399

  proc = subprocess.Popen(cmd, cwd = local, stderr = err)
  if err:
    proc.stderr.read()
    proc.stderr.close()
  if proc.wait() != 0:
    raise CloneFailure()

400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
def _DownloadBundle(url, local, quiet):
  if not url.endswith('/'):
    url += '/'
  url += 'clone.bundle'

  proc = subprocess.Popen(
    [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
    cwd = local,
    stdout = subprocess.PIPE)
  for line in proc.stdout:
    m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
    if m:
      new_url = m.group(1)
      old_url = m.group(2)
      if url.startswith(old_url):
        url = new_url + url[len(old_url):]
        break
  proc.stdout.close()
  proc.wait()

  if not url.startswith('http:') and not url.startswith('https:'):
    return False

  dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
  try:
    try:
      r = urllib2.urlopen(url)
427
    except urllib2.HTTPError as e:
428 429 430 431 432
      if e.code == 404:
        return False
      print >>sys.stderr, 'fatal: Cannot get %s' % url
      print >>sys.stderr, 'fatal: HTTP error %s' % e.code
      raise CloneFailure()
433
    except urllib2.URLError as e:
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
      print >>sys.stderr, 'fatal: Cannot get %s' % url
      print >>sys.stderr, 'fatal: error %s' % e.reason
      raise CloneFailure()
    try:
      if not quiet:
        print >>sys.stderr, 'Get %s' % url
      while True:
        buf = r.read(8192)
        if buf == '':
          return True
        dest.write(buf)
    finally:
      r.close()
  finally:
    dest.close()

def _ImportBundle(local):
  path = os.path.join(local, '.git', 'clone.bundle')
  try:
    _Fetch(local, local, path, True)
  finally:
    os.remove(path)
456 457 458 459 460 461

def _Clone(url, local, quiet):
  """Clones a git repository to a new subdirectory of repodir
  """
  try:
    os.mkdir(local)
462
  except OSError as e:
463 464 465 466 467 468 469 470
    print >>sys.stderr, \
          'fatal: cannot make %s directory: %s' \
          % (local, e.strerror)
    raise CloneFailure()

  cmd = [GIT, 'init', '--quiet']
  try:
    proc = subprocess.Popen(cmd, cwd = local)
471
  except OSError as e:
472 473 474 475 476 477 478 479 480 481 482
    print >>sys.stderr
    print >>sys.stderr, "fatal: '%s' is not available" % GIT
    print >>sys.stderr, 'fatal: %s' % e
    print >>sys.stderr
    print >>sys.stderr, 'Please make sure %s is installed'\
                        ' and in your path.' % GIT
    raise CloneFailure()
  if proc.wait() != 0:
    print >>sys.stderr, 'fatal: could not create %s' % local
    raise CloneFailure()

483
  _InitHttp()
484 485 486
  _SetConfig(local, 'remote.origin.url', url)
  _SetConfig(local, 'remote.origin.fetch',
                    '+refs/heads/*:refs/remotes/origin/*')
487 488 489 490
  if _DownloadBundle(url, local, quiet):
    _ImportBundle(local)
  else:
    _Fetch(url, local, 'origin', quiet)
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523


def _Verify(cwd, branch, quiet):
  """Verify the branch has been signed by a tag.
  """
  cmd = [GIT, 'describe', 'origin/%s' % branch]
  proc = subprocess.Popen(cmd,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE,
                          cwd = cwd)
  cur = proc.stdout.read().strip()
  proc.stdout.close()

  proc.stderr.read()
  proc.stderr.close()

  if proc.wait() != 0 or not cur:
    print >>sys.stderr
    print >>sys.stderr,\
      "fatal: branch '%s' has not been signed" \
      % branch
    raise CloneFailure()

  m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
  if m:
    cur = m.group(1)
    if not quiet:
      print >>sys.stderr
      print >>sys.stderr, \
        "info: Ignoring branch '%s'; using tagged release '%s'" \
        % (branch, cur)
      print >>sys.stderr

524 525
  env = os.environ.copy()
  env['GNUPGHOME'] = gpg_dir.encode()
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572

  cmd = [GIT, 'tag', '-v', cur]
  proc = subprocess.Popen(cmd,
                          stdout = subprocess.PIPE,
                          stderr = subprocess.PIPE,
                          cwd = cwd,
                          env = env)
  out = proc.stdout.read()
  proc.stdout.close()

  err = proc.stderr.read()
  proc.stderr.close()

  if proc.wait() != 0:
    print >>sys.stderr
    print >>sys.stderr, out
    print >>sys.stderr, err
    print >>sys.stderr
    raise CloneFailure()
  return '%s^0' % cur


def _Checkout(cwd, branch, rev, quiet):
  """Checkout an upstream branch into the repository and track it.
  """
  cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
  if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
    raise CloneFailure()

  _SetConfig(cwd, 'branch.default.remote', 'origin')
  _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)

  cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
  if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
    raise CloneFailure()

  cmd = [GIT, 'read-tree', '--reset', '-u']
  if not quiet:
    cmd.append('-v')
  cmd.append('HEAD')
  if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
    raise CloneFailure()


def _FindRepo():
  """Look for a repo installation, starting at the current directory.
  """
573
  curdir = os.getcwd()
574 575
  repo = None

576
  olddir = None
577 578
  while curdir != '/' \
    and curdir != olddir \
579
    and not repo:
580
    repo = os.path.join(curdir, repodir, REPO_MAIN)
581 582
    if not os.path.isfile(repo):
      repo = None
583 584 585
      olddir = curdir
      curdir = os.path.dirname(curdir)
  return (repo, os.path.join(curdir, repodir))
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628


class _Options:
  help = False


def _ParseArguments(args):
  cmd = None
  opt = _Options()
  arg = []

  for i in xrange(0, len(args)):
    a = args[i]
    if a == '-h' or a == '--help':
      opt.help = True

    elif not a.startswith('-'):
      cmd = a
      arg = args[i + 1:]
      break
  return cmd, opt, arg


def _Usage():
  print >>sys.stderr,\
"""usage: repo COMMAND [ARGS]

repo is not yet installed.  Use "repo init" to install it here.

The most commonly used repo commands are:

  init      Install repo in the current working directory
  help      Display detailed help on a command

For access to the full online help, install repo ("repo init").
"""
  sys.exit(1)


def _Help(args):
  if args:
    if args[0] == 'init':
      init_optparse.print_help()
629
      sys.exit(0)
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
    else:
      print >>sys.stderr,\
      "error: '%s' is not a bootstrap command.\n"\
      '        For access to online help, install repo ("repo init").'\
      % args[0]
  else:
    _Usage()
  sys.exit(1)


def _NotInstalled():
  print >>sys.stderr,\
'error: repo is not installed.  Use "repo init" to install it here.'
  sys.exit(1)


def _NoCommands(cmd):
  print >>sys.stderr,\
"""error: command '%s' requires repo to be installed first.
       Use "repo init" to install it here.""" % cmd
  sys.exit(1)


def _RunSelf(wrapper_path):
  my_dir = os.path.dirname(wrapper_path)
  my_main = os.path.join(my_dir, 'main.py')
  my_git = os.path.join(my_dir, '.git')

  if os.path.isfile(my_main) and os.path.isdir(my_git):
    for name in ['git_config.py',
                 'project.py',
                 'subcmds']:
      if not os.path.exists(os.path.join(my_dir, name)):
        return None, None
    return my_main, my_git
  return None, None


def _SetDefaultsTo(gitdir):
  global REPO_URL
  global REPO_REV

  REPO_URL = gitdir
  proc = subprocess.Popen([GIT,
                           '--git-dir=%s' % gitdir,
                           'symbolic-ref',
                           'HEAD'],
                          stdout = subprocess.PIPE,
                          stderr = subprocess.PIPE)
  REPO_REV = proc.stdout.read().strip()
  proc.stdout.close()

  proc.stderr.read()
  proc.stderr.close()

  if proc.wait() != 0:
    print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
    sys.exit(1)


def main(orig_args):
691
  repo_main, rel_repo_dir = _FindRepo()
692 693 694 695 696
  cmd, opt, args = _ParseArguments(orig_args)

  wrapper_path = os.path.abspath(__file__)
  my_main, my_git = _RunSelf(wrapper_path)

697
  if not repo_main:
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
    if opt.help:
      _Usage()
    if cmd == 'help':
      _Help(args)
    if not cmd:
      _NotInstalled()
    if cmd == 'init':
      if my_git:
        _SetDefaultsTo(my_git)
      try:
        _Init(args)
      except CloneFailure:
        for root, dirs, files in os.walk(repodir, topdown=False):
          for name in files:
            os.remove(os.path.join(root, name))
          for name in dirs:
            os.rmdir(os.path.join(root, name))
        os.rmdir(repodir)
        sys.exit(1)
717
      repo_main, rel_repo_dir = _FindRepo()
718 719 720 721
    else:
      _NoCommands(cmd)

  if my_main:
722
    repo_main = my_main
723 724

  ver_str = '.'.join(map(lambda x: str(x), VERSION))
725 726
  me = [repo_main,
        '--repo-dir=%s' % rel_repo_dir,
727 728 729 730 731 732
        '--wrapper-version=%s' % ver_str,
        '--wrapper-path=%s' % wrapper_path,
        '--']
  me.extend(orig_args)
  me.extend(extra_args)
  try:
733 734 735
    os.execv(repo_main, me)
  except OSError as e:
    print >>sys.stderr, "fatal: unable to start %s" % repo_main
736 737 738 739 740 741
    print >>sys.stderr, "fatal: %s" % e
    sys.exit(148)


if __name__ == '__main__':
  main(sys.argv[1:])