repo,可以直接复制粘贴到你的~/bin/repo文件中

完美的失败方案让 repo init 安卓源码仓库恢复到最初状态 repo sync -d 报错 The program 'repo' can be found in the following packages: * phablet-tools * repo Try: sudo apt install <selected package> 安装repo sudo apt install repo 没有repo init error: command 'sync' requires repo to be installed first. 阅读详情

#!/usr/bin/env python

# repo default configuration
#
import os
REPO_URL = os.environ.get('REPO_URL', None)
if not REPO_URL:
  REPO_URL = 'https://gerrit.googlesource.com/git-repo'
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.

# increment this whenever we make important changes to this script
VERSION = (1, 25)

# increment this if the MAINTAINER_KEYS block is modified
KEYRING_VERSION = (1, 2)

# Each individual key entry is created by using:
# gpg --armor --export keyid
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
Fxp5YpHuIuMImopWEMFIRQNrvlg+YVK8t3FpdI1RY0LYqha8pPzANhEYgSfoVzO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91cAAwUP/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
-----END PGP PUBLIC KEY BLOCK-----

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

mQENBFHRvc8BCADFg45Xx/y6QDC+T7Y/gGc7vx0ww7qfOwIKlAZ9xG3qKunMxo+S
hPCnzEl3cq+6I1Ww/ndop/HB3N3toPXRCoN8Vs4/Hc7by+SnaLFnacrm+tV5/OgT
V37Lzt8lhay1Kl+YfpFwHYYpIEBLFV9knyfRXS/428W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y2pZ8I7gAAcEM0Xw8drr4omg2fUoK1J33ozlA/RxeA/lJ
I3KnyCDTpXuIeBKPGkdL8uMATC9Z8DnBBajRlftNDVZS3Hz4G09G9QpMojvJkFJV
By+01Flw/X+eeN8NpqSuLV4W+AjEO8at/VvgKr1AFvBRdZ7GkpI1o6DgPe7ZqX+1
dzQZt3e13W0rVBb/bUgx9iSLoeWP3aq/k+/GRGOR+S6F6BBSl0SQ2EF2+dIywb1x
JuinEP+AwLAUZ1Bsx9ISC0Agpk2VeHXPL3FGhroEmoMvBzO0kTFGyoeT7PR/BfKv
+H/g3HsL2LOB9uoIm8/5p2TTU5ttYCXMHhQZ81AY
=AUp4
-----END PGP PUBLIC KEY BLOCK-----
"""

GIT = 'git'                      # our git command
MIN_GIT_VERSION = (1, 7, 2)      # minimum supported git version
repodir = '.repo'                # name of repo's private directory
S_repo = 'repo'                  # special repo repository
S_manifests = 'manifests'        # special manifest repository
REPO_MAIN = S_repo + '/main.py'  # main script
MIN_PYTHON_VERSION = (2, 7)      # minimum supported python version
GITC_CONFIG_FILE = '/gitc/.config'
GITC_FS_ROOT_DIR = '/gitc/manifest-rw/'


import errno
import optparse
import platform
import re
import shutil
import stat
import subprocess
import sys

if sys.version_info[0] == 3:
  import urllib.request
  import urllib.error
else:
  import imp
  import urllib2
  urllib = imp.new_module('urllib')
  urllib.request = urllib2
  urllib.error = urllib2


def _print(*objects, **kwargs):
  sep = kwargs.get('sep', ' ')
  end = kwargs.get('end', '\n')
  out = kwargs.get('file', sys.stdout)
  out.write(sep.join(objects) + end)

  # On Windows stderr is buffered, so flush to maintain the order of error messages.
  if out == sys.stderr and platform.system() == "Windows":
    out.flush()


# Python version check
ver = sys.version_info
if (ver[0], ver[1]) < MIN_PYTHON_VERSION:
  _print('error: Python version {} unsupported.\n'
         'Please use Python {}.{} instead.'.format(
             sys.version.split(' ')[0],
             MIN_PYTHON_VERSION[0],
             MIN_PYTHON_VERSION[1],
         ), file=sys.stderr)
  sys.exit(1)

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',
                 help='initial manifest file', metavar='NAME.xml')
group.add_option('--current-branch',
                 dest='current_branch_only', action='store_true',
                 help='fetch only current manifest branch from server')
group.add_option('--mirror',
                 dest='mirror', action='store_true',
                 help='create a replica of the remote repositories '
                      'rather than a client working directory')
group.add_option('--reference',
                 dest='reference',
                 help='location of mirror directory', metavar='DIR')
group.add_option('--dissociate',
                 dest='dissociate', action='store_true',
                 help='dissociate from reference mirrors after clone')
group.add_option('--depth', type='int', default=None,
                 dest='depth',
                 help='create a shallow clone with given depth; see git clone')
group.add_option('--archive',
                 dest='archive', action='store_true',
                 help='checkout an archive instead of a git repository for '
                      'each project. See git archive.')
group.add_option('--submodules',
                 dest='submodules', action='store_true',
                 help='sync any submodules associated with the manifest repo')
group.add_option('-g', '--groups',
                 dest='groups', default='default',
                 help='restrict manifest projects to ones with specified '
                      'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
                 metavar='GROUP')
group.add_option('-p', '--platform',
                 dest='platform', default="auto",
                 help='restrict manifest projects to ones with a specified '
                      'platform group [auto|all|none|linux|darwin|...]',
                 metavar='PLATFORM')
group.add_option('--no-clone-bundle',
                 dest='no_clone_bundle', action='store_true',
                 help='disable use of /clone.bundle on HTTP/HTTPS')
group.add_option('--no-tags',
                 dest='no_tags', action='store_true',
                 help="don't fetch tags in the manifest")


# 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')

# 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')


def _GitcInitOptions(init_optparse_arg):
  init_optparse_arg.set_usage("repo gitc-init -u url -c client [options]")
  g = init_optparse_arg.add_option_group('GITC options')
  g.add_option('-f', '--manifest-file',
               dest='manifest_file',
               help='Optional manifest file to use for this GITC client.')
  g.add_option('-c', '--gitc-client',
               dest='gitc_client',
               help='The name of the gitc_client instance to create or modify.')

_gitc_manifest_dir = None


def get_gitc_manifest_dir():
  global _gitc_manifest_dir
  if _gitc_manifest_dir is None:
    _gitc_manifest_dir = ''
    try:
      with open(GITC_CONFIG_FILE, 'r') as gitc_config:
        for line in gitc_config:
          match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
          if match:
            _gitc_manifest_dir = match.group('gitc_manifest_dir')
    except IOError:
      pass
  return _gitc_manifest_dir


def gitc_parse_clientdir(gitc_fs_path):
  """Parse a path in the GITC FS and return its client name.

  @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.

  @returns: The GITC client name
  """
  if gitc_fs_path == GITC_FS_ROOT_DIR:
    return None
  if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
    manifest_dir = get_gitc_manifest_dir()
    if manifest_dir == '':
      return None
    if manifest_dir[-1] != '/':
      manifest_dir += '/'
    if gitc_fs_path == manifest_dir:
      return None
    if not gitc_fs_path.startswith(manifest_dir):
      return None
    return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
  return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]


class CloneFailure(Exception):

  """Indicate the remote clone of repo itself failed.
  """


def _Init(args, gitc_init=False):
  """Installs repo by cloning it over the network.
  """
  if gitc_init:
    _GitcInitOptions(init_optparse)
  opt, args = init_optparse.parse_args(args)
  if args:
    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("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
    raise CloneFailure()

  try:
    if gitc_init:
      gitc_manifest_dir = get_gitc_manifest_dir()
      if not gitc_manifest_dir:
        _print('fatal: GITC filesystem is not available. Exiting...',
               file=sys.stderr)
        sys.exit(1)
      gitc_client = opt.gitc_client
      if not gitc_client:
        gitc_client = gitc_parse_clientdir(os.getcwd())
      if not gitc_client:
        _print('fatal: GITC client (-c) is required.', file=sys.stderr)
        sys.exit(1)
      client_dir = os.path.join(gitc_manifest_dir, gitc_client)
      if not os.path.exists(client_dir):
        os.makedirs(client_dir)
      os.chdir(client_dir)
      if os.path.exists(repodir):
        # This GITC Client has already initialized repo so continue.
        return

    os.mkdir(repodir)
  except OSError as e:
    if e.errno != errno.EEXIST:
      _print('fatal: cannot make %s directory: %s'
             % (repodir, e.strerror), file=sys.stderr)
      # Don't raise CloneFailure; that would delete the
      # name. Instead exit immediately.
      #
      sys.exit(1)

  _CheckGitVersion()
  try:
    if NeedSetupGnuPG():
      can_verify = SetupGnuPG(opt.quiet)
    else:
      can_verify = True

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

    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)

    if not os.path.isfile(os.path.join(dst, 'repo')):
      _print("warning: '%s' does not look like a git-repo repository, is "
             "REPO_URL set correctly?" % url, file=sys.stderr)

  except CloneFailure:
    if opt.quiet:
      _print('fatal: repo init failed; run without --quiet to see why',
             file=sys.stderr)
    raise


def ParseGitVersion(ver_str):
  if not ver_str.startswith('git version '):
    return None

  num_ver_str = ver_str[len('git version '):].strip().split('-')[0]
  to_tuple = []
  for num_str in num_ver_str.split('.')[:3]:
    if num_str.isdigit():
      to_tuple.append(int(num_str))
    else:
      to_tuple.append(0)
  return tuple(to_tuple)


def _CheckGitVersion():
  cmd = [GIT, '--version']
  try:
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  except OSError as e:
    _print(file=sys.stderr)
    _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
    _print('fatal: %s' % e, file=sys.stderr)
    _print(file=sys.stderr)
    _print('Please make sure %s is installed and in your path.' % GIT,
           file=sys.stderr)
    raise CloneFailure()

  ver_str = proc.stdout.read().strip()
  proc.stdout.close()
  proc.wait()

  ver_act = ParseGitVersion(ver_str)
  if ver_act is None:
    _print('error: "%s" unsupported' % ver_str, file=sys.stderr)
    raise CloneFailure()

  if ver_act < MIN_GIT_VERSION:
    need = '.'.join(map(str, MIN_GIT_VERSION))
    _print('fatal: git %s or later required' % need, file=sys.stderr)
    raise CloneFailure()


def NeedSetupGnuPG():
  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(int, kv.split('.')))
  if kv < KEYRING_VERSION:
    return True
  return False


def SetupGnuPG(quiet):
  try:
    os.mkdir(home_dot_repo)
  except OSError as e:
    if e.errno != errno.EEXIST:
      _print('fatal: cannot make %s directory: %s'
             % (home_dot_repo, e.strerror), file=sys.stderr)
      sys.exit(1)

  try:
    os.mkdir(gpg_dir, stat.S_IRWXU)
  except OSError as e:
    if e.errno != errno.EEXIST:
      _print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
             file=sys.stderr)
      sys.exit(1)

  env = os.environ.copy()
  try:
    env['GNUPGHOME'] = gpg_dir
  except UnicodeEncodeError:
    env['GNUPGHOME'] = gpg_dir.encode()

  cmd = ['gpg', '--import']
  try:
    proc = subprocess.Popen(cmd,
                            env=env,
                            stdin=subprocess.PIPE)
  except OSError as e:
    if not quiet:
      _print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
      _print('warning: Installing it is strongly encouraged.', file=sys.stderr)
      _print(file=sys.stderr)
    return False

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

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

  fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
  fd.write('.'.join(map(str, 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()


def _InitHttp():
  handlers = []

  mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  try:
    import netrc
    n = netrc.netrc()
    for host in n.hosts:
      p = n.hosts[host]
      mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
      mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  except:
    pass
  handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
  handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))

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


def _Fetch(url, local, src, quiet):
  if not quiet:
    _print('Get %s' % url, file=sys.stderr)

  cmd = [GIT, 'fetch']
  if quiet:
    cmd.append('--quiet')
    err = subprocess.PIPE
  else:
    err = None
  cmd.append(src)
  cmd.append('+refs/heads/*:refs/remotes/origin/*')
  cmd.append('+refs/tags/*:refs/tags/*')

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


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 = urllib.request.urlopen(url)
    except urllib.error.HTTPError as e:
      if e.code in [401, 403, 404, 501]:
        return False
      _print('fatal: Cannot get %s' % url, file=sys.stderr)
      _print('fatal: HTTP error %s' % e.code, file=sys.stderr)
      raise CloneFailure()
    except urllib.error.URLError as e:
      _print('fatal: Cannot get %s' % url, file=sys.stderr)
      _print('fatal: error %s' % e.reason, file=sys.stderr)
      raise CloneFailure()
    try:
      if not quiet:
        _print('Get %s' % url, file=sys.stderr)
      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)


def _Clone(url, local, quiet, clone_bundle):
  """Clones a git repository to a new subdirectory of repodir
  """
  try:
    os.mkdir(local)
  except OSError as e:
    _print('fatal: cannot make %s directory: %s' % (local, e.strerror),
           file=sys.stderr)
    raise CloneFailure()

  cmd = [GIT, 'init', '--quiet']
  try:
    proc = subprocess.Popen(cmd, cwd=local)
  except OSError as e:
    _print(file=sys.stderr)
    _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
    _print('fatal: %s' % e, file=sys.stderr)
    _print(file=sys.stderr)
    _print('Please make sure %s is installed and in your path.' % GIT,
           file=sys.stderr)
    raise CloneFailure()
  if proc.wait() != 0:
    _print('fatal: could not create %s' % local, file=sys.stderr)
    raise CloneFailure()

  _InitHttp()
  _SetConfig(local, 'remote.origin.url', url)
  _SetConfig(local,
             'remote.origin.fetch',
             '+refs/heads/*:refs/remotes/origin/*')
  if clone_bundle and _DownloadBundle(url, local, quiet):
    _ImportBundle(local)
  _Fetch(url, local, 'origin', quiet)


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(file=sys.stderr)
    _print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
    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(file=sys.stderr)
      _print("info: Ignoring branch '%s'; using tagged release '%s'"
             % (branch, cur), file=sys.stderr)
      _print(file=sys.stderr)

  env = os.environ.copy()
  try:
    env['GNUPGHOME'] = gpg_dir
  except UnicodeEncodeError:
    env['GNUPGHOME'] = gpg_dir.encode()

  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(file=sys.stderr)
    _print(out, file=sys.stderr)
    _print(err, file=sys.stderr)
    _print(file=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.
  """
  curdir = os.getcwd()
  repo = None

  olddir = None
  while curdir != '/' \
          and curdir != olddir \
          and not repo:
    repo = os.path.join(curdir, repodir, REPO_MAIN)
    if not os.path.isfile(repo):
      repo = None
      olddir = curdir
      curdir = os.path.dirname(curdir)
  return (repo, os.path.join(curdir, repodir))


class _Options(object):
  help = False


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

  for i in range(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():
  gitc_usage = ""
  if get_gitc_manifest_dir():
    gitc_usage = "  gitc-init Initialize a GITC Client.\n"

  _print(
      """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
""" + gitc_usage +
      """  help      Display detailed help on a command

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


def _Help(args):
  if args:
    if args[0] == 'init':
      init_optparse.print_help()
      sys.exit(0)
    elif args[0] == 'gitc-init':
      _GitcInitOptions(init_optparse)
      init_optparse.print_help()
      sys.exit(0)
    else:
      _print("error: '%s' is not a bootstrap command.\n"
             '        For access to online help, install repo ("repo init").'
             % args[0], file=sys.stderr)
  else:
    _Usage()
  sys.exit(1)


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


def _NoCommands(cmd):
  _print("""error: command '%s' requires repo to be installed first.
         Use "repo init" to install it here.""" % cmd, file=sys.stderr)
  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('fatal: %s has no current branch' % gitdir, file=sys.stderr)
    sys.exit(1)


def main(orig_args):
  cmd, opt, args = _ParseArguments(orig_args)

  repo_main, rel_repo_dir = None, None
  # Don't use the local repo copy, make sure to switch to the gitc client first.
  if cmd != 'gitc-init':
    repo_main, rel_repo_dir = _FindRepo()

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

  cwd = os.getcwd()
  if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
    _print('error: repo cannot be used in the GITC local manifest directory.'
           '\nIf you want to work on this GITC client please rerun this '
           'command from the corresponding client under /gitc/',
           file=sys.stderr)
    sys.exit(1)
  if not repo_main:
    if opt.help:
      _Usage()
    if cmd == 'help':
      _Help(args)
    if not cmd:
      _NotInstalled()
    if cmd == 'init' or cmd == 'gitc-init':
      if my_git:
        _SetDefaultsTo(my_git)
      try:
        _Init(args, gitc_init=(cmd == 'gitc-init'))
      except CloneFailure:
        path = os.path.join(repodir, S_repo)
        _print("fatal: cloning the git-repo repository failed, will remove "
               "'%s' " % path, file=sys.stderr)
        shutil.rmtree(path, ignore_errors=True)
        sys.exit(1)
      repo_main, rel_repo_dir = _FindRepo()
    else:
      _NoCommands(cmd)

  if my_main:
    repo_main = my_main

  ver_str = '.'.join(map(str, VERSION))
  me = [sys.executable, repo_main,
        '--repo-dir=%s' % rel_repo_dir,
        '--wrapper-version=%s' % ver_str,
        '--wrapper-path=%s' % wrapper_path,
        '--']
  me.extend(orig_args)
  me.extend(extra_args)
  try:
    if platform.system() == "Windows":
      sys.exit(subprocess.call(me))
    else:
      os.execv(sys.executable, me)
  except OSError as e:
    _print("fatal: unable to start %s" % repo_main, file=sys.stderr)
    _print("fatal: %s" % e, file=sys.stderr)
    sys.exit(148)


if __name__ == '__main__':
  if ver[0] == 3:
    _print('warning: Python 3 support is currently experimental. YMMV.\n'
           'Please use Python 2.7 instead.',
           file=sys.stderr)
  main(sys.argv[1:])

Opencode安装卸载全指南:curl/npm/源码三方式深度解析 Opencode是一种面向开发者的本地AI编程协作者运行时环境,其核心在于可嵌入、可裁剪、可编程的设计理念,区别于传统图形化编辑器或封装式AI工具。它基于轻量命令行交互,依赖curl快速获取、npm集成Node生态、Rust源码支持深度定制,技术价值体现在对模型调度权、上下文管理权和工具调用权的完全用户掌控。典型应用场景包括树莓派轻量分析、企业内网PR自动检查、Ollama离线补全等。本文聚焦Opencode的安装机制与安全卸载逻辑,深入解析curl | bash的安全校验流程、npm在Windows下的P 阅读详情

相关推荐

GOPATH 在 Go Modules 时代的真实角色与实战配置

GOPATH 是 Go 语言构建系统的核心工作空间协议,其本质是定义源码(src)、编译缓存(pkg)和可执行文件(bin)三位一体的路径约定。尽管 Go Modules 自 1.11 起解耦了项目路径依赖,但 GOPATH 仍深度参与模块缓存管理、go install 输出定位及依赖解析基础设施——尤其在 CI/CD、Docker 构建和多用户环境中,其权限、路径与 GOBIN 配置直接影响 go mod download 和 go install 的稳定性。理解 GOPATH 的‘隐身术’,是规避 pe

dht91597的博客 400

repo source

#!/usr/bin/env python ## repo default configuration ## REPO_URL = 'https://gerrit.googlesource.com/git-repo' REPO_REV = 'stable' # Copyright (C) 2008 Google Inc. # # Licensed under the Apac

weiyog29的专栏 3086

Ubuntu 18.04 安装 Anaconda 后 conda 命令失效的根因与 conda init 全链路解析

conda 是 Python 科学计算生态的核心环境管理工具,其本质是通过 shell 初始化机制将命令与函数注入运行时环境;在 Ubuntu 18.04 中,因默认使用 dash 作为 /bin/sh、login shell 与 non-login shell 配置文件加载路径分离(如 ~/.profile 与 ~/.bashrc)、以及 Anaconda 安装器默认仅修改当前终端配置等设计差异,导致 conda 命令在新终端、SSH、cron 等场景下不可见;技术价值在于厘清 shell 启动流程、PA

weixin_30562507的博客 401

repo系列讲解 —— 使用问题汇总(持续更新)

1. repo init相关 1.1 Python 3 support is currently experimental. YMMV Please use Python 2.7 instead. sun@sun-pc:~/project/AOSP$ repo init -u https://mirrors.tuna.tsinghua.edu.cn/git/AOSP/platform/manifest warning: Python 3 support is currently experimental.

In_engineer的博客 1万+

SSH密钥配置全攻略:从原理到实战,解决开发中的连接难题

SSH(Secure Shell)是一种广泛应用于远程登录和安全文件传输的网络协议,其核心是基于非对称加密的身份认证机制。通过生成公钥和私钥对,SSH实现了无需密码传输的高安全性认证,有效防止了中间人攻击和密码泄露风险。这一技术为自动化脚本、持续集成/持续部署(CI/CD)流程以及远程开发环境提供了基础安全支撑。在实际应用场景中,开发者常需在Linux服务器、Git平台(如GitHub、GitLab)以及各类IDE工具间建立安全连接。针对常见的权限错误、多密钥管理混乱等问题,本文聚焦于SSH密钥配置的实战技

weixin_34059951的博客 612

数据科学本地工作台搭建:Python/R/Shell/Git四层解耦实践

数据科学环境不是开箱即用的工具箱,而是需持续维护的‘第一份数据产品’。其核心在于理解解释器、包管理、IDE与Shell的分层协作原理——Python依赖conda环境隔离避免包冲突,R借助renv锁定依赖保障可复现性,Shell层需WSL2或Homebrew提供工程化能力,Git则通过环境快照(如environment.yml、renv.lock)实现‘环境即代码’。这种设计显著提升Kaggle项目复现、团队协作建模及云边协同分析的稳定性与效率。本文聚焦Miniconda、RSPM、WSL2和VS Code

weixin_34236869的博客 412

完全掌握Mac下配置环境变量,从此不用再复制粘贴胡乱找

原理: 在Mac中我们的环境是添加到PATH路径下的,系统运行的时候会直接去找/usr/libexec/path_helper这个文件,里面内容就是我们通过环境变量设置的PATH,所以我们设置环境变量是通过PATH来设置的。 具体的配置: export M2_HOME=/Users/weixl/Downloads/apache-maven-3.6.3 export MYSQL_HOME=/usr/local/mysql/bin export PATH=$PATH:$M2_HOME/bin:$MYSQL_HO

xiaole060901的博客 539

Ubuntu 18.04 安装 Anaconda 卡在 ‘installer file may be damaged‘ 的根因与修复

Anaconda 是面向数据科学的 Python 发行版,其安装脚本本质为 Bash 脚本,依赖 `[[ ]]` 语法和算术扩展等 Bash 特性;而 Ubuntu 18.04 系统默认将 `/bin/sh` 指向轻量级 `dash` shell,导致校验逻辑执行异常,触发 'installer file may be damaged' 错误。该问题并非文件损坏或网络问题,而是 shell 兼容性引发的完整性校验失效,进一步连锁导致 'defaulting to user installation' 权限降

weixin_33725722的博客 511

Linux入门指南:从基础到文件管理

本文总结了Linux系统基础操作的核心知识点,分为四部分内容:1)Linux系统组成与基本操作,包括系统架构、终端使用和目录切换;2)命令执行规范,涵盖命令格式、帮助查询和时间管理;3)文件类型解析,详细说明7种文件类型及软硬链接区别;4)文件管理基础,涉及命名规则和硬链接原理。重点内容包括Shell命令解释器作用、虚拟终端切换、timedatectl时间配置、ls命令参数详解、文件类型标识字符(如-表普通文件、d表目录)、软硬链接的inode差异等实用技术要点,并配有重置root密码等典型操作示例。全文系

weixin_75090808的博客 227

Ubuntu 20.04 安装 Composer 2.5 全流程深度解析

Composer 是 PHP 生态中核心的依赖管理工具,其运行依赖于 PHP 环境完整性、系统权限模型与网络证书链三重保障。在 Ubuntu 20.04 这一长期支持版本中,PHP 7.4 默认精简安装,mbstring、openssl、zip 等关键扩展常处于未启用状态;同时 AppArmor 安全策略严格限制 /usr/local/bin 的可执行性,导致常见‘Permission denied’错误频发。Composer 2.5 更强化了启动时的扩展校验机制,使环境不兼容问题从警告升级为阻断。因此,可

weixin_34293911的博客 421

Ubuntu 20.04 正确安装 Composer 2.5+ 的完整指南

Composer 是 PHP 生态的核心包管理器,其本质是一个可执行的 PHAR 归档文件,依赖 PHP CLI 运行并支持 self-update 自动升级。在 Ubuntu 20.04 这类 LTS 系统中,官方 apt 源长期锁定 Composer 1.x,已停止维护且不兼容 Laravel 10+、Symfony 6+ 等现代框架所需的 PHP 8.1+ 语法与依赖解析能力。因此,工程实践中必须绕过 apt,采用 curl 安全下载 + php 执行官方 installer 的方式部署独立 PHAR

liudaoru - 悟 387

别再手动复制粘贴了!这个开源爬虫工具一次搞定小红书、抖音、B站、快手、微博的数据采集

周五晚上十一点,老板在群里甩下一句话:下周一早会的方案,要覆盖全网竞品的最新数据。我盯着屏幕上二十多个打开的标签页,陷入"复制—粘贴—切页—再复制"的循环,直到凌晨一点才整理了不到三分之一。要不是朋友甩来一个开源项目 **MediaCrawler-new**——一个能同时采集小红书、抖音、快手、B站、微博五大平台数据的爬虫框架,我的周末恐怕就要交代给 Ctrl+C 了。 这篇文章把我从"手动采集

gitblog_01002的博客 264

原生android 11 系统手动编译包,直接下载即可安装,内置系统驱动

该安装包内置驱动,是开源android 11 的系统,自己手动编译的,编译过程见:https://blog.youkuaiyun.com/qq_40340448/article/details/124502496?spm=1001.2014.3001.5502 。 用于测试以及,签发系统签名,安装系统级别apk都可,获得系统权限。 下载下来,使用fastbot 相关命令即可安装使用。

Ubuntu 14.04+HHVM+Nginx遗留系统逆向工程实战

FastCGI是一种标准Web服务器与应用服务器通信的协议,其核心在于进程间请求转发与生命周期协同。理解Nginx的fastcgi_pass机制、HHVM的FastCGI服务模式及Ubuntu LTS系统依赖约束,是保障PHP遗留系统稳定运行的技术基础。该组合虽已退出主流支持,但在安全审计、漏洞复现、历史兼容性测试等场景中仍具不可替代的工程价值。本文聚焦HHVM与Nginx在Ubuntu 14.04环境下的真实联调细节,覆盖源仓库迁移、ABI兼容性排查、socket通信配置、超时参数对齐及Repo字节码优化

weixin_30415113的博客 477

小笑授权系统V7.3全开源版支持二开

小笑授权系统旨在为个人开发者或者开发团队提供一种高效便捷的管理个人源码的方案。通过小笑多应用授权系统,您可以随时随地的面向您的用户添加授权、管理授权。此外还可以通过简单的配置实现源码的在线下载、用户远程的在线更新、盗版系统的追踪打击。所以说,使用小笑授权系统便可极大程度的方便您的系统开发。 功能介绍 多应用授权,盗版入库,在线更新,代理查询,多种下载源码方式 支持自助注册用户,支持自助升级权限等级,支持自助购买授权 支持卡密授权,支持自助更换授权,支持API授权接口 支持第三方快捷登录,拥有远程接口,用户密价[授权系统独家拥有] 多种模板自由切换使用,支持用户自行定制模板使用,无限制无加密 数据库更新[新方法更便捷],版本管理 多应用的应用包目录支持自定义方便记忆,也支持在线上传安装包更新包 工单系统,用户实名认证[可控制单程序],域名导入功能 邮件通知,短信通知【可选择更加方便的跳转方式】

安卓机型第三方gsi镜像系统合集 持续更新下载地址

安卓机型第三方gsi镜像系统合集 持续更新下载地址 1---体验第三方gsi系统的乐趣。体验非官方系统的乐趣 2---资源内涵盖了miui.Flyme.zui.原生.joyui.三星等等系统的gsi镜像系统 4----资源保持更新状态。你下载的网盘地址我会随时更新其中资源 5----包含上百G的各种分区的gsi镜像系统 6---需要有一定的刷机常识的友友下载使用 7---资源有可复制性。下载后不支持退。 具体可以参考我这个博文。 https://blog.youkuaiyun.com/u011283906/article/details/129116172

5.vim 编辑器(从零开始学)

每一个系统管理员都有一个偏爱的文本编辑器。有的管理员偏爱gedit,有的偏爱nano,甚至有的偏爱emacs。即使已经有偏爱的编辑器,了解vim还是有必要的。因为vim可以安装在任何系统。:只提供vi和相关命令。:提供vim命令,提供语法高亮拼写检查等特性。vim-X11:提供gvim,图形界面下的vim。gvim包涵菜单栏。当用户不知道命令的时候,可以通过菜单操作。# 安装 vim 工具密码:已加载插件:fastestmirror, langpacks未知的错误"

fengkai4545的博客 374

2025亿云多应用授权系统源码

2025亿云多应用授权系统源码 服务器环境要求:Nginx PHP版本要求:7.3 MySQL版本要求:5.6+ 满足以上条件后 直接打开域名/install进行安装

上一篇: 汉语拼音常识
下一篇: Android 匿名共享内存demo篇(一)
杨鑫校
博客等级 码龄11年 24粉丝 113原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值