Update repo to v2.4

Change-Id: I1c40f48bf22c73742290b79caa8f5a6392fbe783
diff --git a/generic/repo/METADATA b/generic/repo/METADATA
index a408d66..e63a27c 100644
--- a/generic/repo/METADATA
+++ b/generic/repo/METADATA
@@ -10,7 +10,7 @@
     type: ARCHIVE
     value: "https://storage.googleapis.com/git-repo-downloads/repo"
   }
-  version: "1.13.6"
-  last_upgrade_date { year: 2019 month: 10 day: 1 }
+  version: "2.4"
+  last_upgrade_date { year: 2020 month: 3 day: 10 }
   license_type: NOTICE
 }
diff --git a/generic/repo/repo b/generic/repo/repo
index f251a1d..77a3f8d 100755
--- a/generic/repo/repo
+++ b/generic/repo/repo
@@ -1,12 +1,122 @@
 #!/usr/bin/env python
+# -*- coding:utf-8 -*-
+
+"""Repo launcher.
+
+This is a standalone tool that people may copy to anywhere in their system.
+It is used to get an initial repo client checkout, and after that it runs the
+copy of repo in the checkout.
+"""
+
+from __future__ import print_function
+
+import datetime
+import os
+import platform
+import shlex
+import subprocess
+import sys
+
+
+# Keep basic logic in sync with repo_trace.py.
+class Trace(object):
+  """Trace helper logic."""
+
+  REPO_TRACE = 'REPO_TRACE'
+
+  def __init__(self):
+    self.set(os.environ.get(self.REPO_TRACE) == '1')
+
+  def set(self, value):
+    self.enabled = bool(value)
+
+  def print(self, *args, **kwargs):
+    if self.enabled:
+      print(*args, **kwargs)
+
+
+trace = Trace()
+
+
+def exec_command(cmd):
+  """Execute |cmd| or return None on failure."""
+  trace.print(':', ' '.join(cmd))
+  try:
+    if platform.system() == 'Windows':
+      ret = subprocess.call(cmd)
+      sys.exit(ret)
+    else:
+      os.execvp(cmd[0], cmd)
+  except Exception:
+    pass
+
+
+def check_python_version():
+  """Make sure the active Python version is recent enough."""
+  def reexec(prog):
+    exec_command([prog] + sys.argv)
+
+  MIN_PYTHON_VERSION = (3, 6)
+
+  ver = sys.version_info
+  major = ver.major
+  minor = ver.minor
+
+  # Abort on very old Python 2 versions.
+  if (major, minor) < (2, 7):
+    print('repo: error: Your Python version is too old. '
+          'Please use Python {}.{} or newer instead.'.format(
+              *MIN_PYTHON_VERSION), file=sys.stderr)
+    sys.exit(1)
+
+  # Try to re-exec the version specific Python 3 if needed.
+  if (major, minor) < MIN_PYTHON_VERSION:
+    # Python makes releases ~once a year, so try our min version +10 to help
+    # bridge the gap.  This is the fallback anyways so perf isn't critical.
+    min_major, min_minor = MIN_PYTHON_VERSION
+    for inc in range(0, 10):
+      reexec('python{}.{}'.format(min_major, min_minor + inc))
+
+    # Try the generic Python 3 wrapper, but only if it's new enough.  We don't
+    # want to go from (still supported) Python 2.7 to (unsupported) Python 3.5.
+    try:
+      proc = subprocess.Popen(
+          ['python3', '-c', 'import sys; '
+           'print(sys.version_info.major, sys.version_info.minor)'],
+          stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+      (output, _) = proc.communicate()
+      python3_ver = tuple(int(x) for x in output.decode('utf-8').split())
+    except (OSError, subprocess.CalledProcessError):
+      python3_ver = None
+
+    # The python3 version looks like it's new enough, so give it a try.
+    if python3_ver and python3_ver >= MIN_PYTHON_VERSION:
+      reexec('python3')
+
+    # We're still here, so diagnose things for the user.
+    if major < 3:
+      print('repo: warning: Python 2 is no longer supported; '
+            'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION),
+            file=sys.stderr)
+    else:
+      print('repo: error: Python 3 version is too old; '
+            'Please use Python {}.{} or newer.'.format(*MIN_PYTHON_VERSION),
+            file=sys.stderr)
+      sys.exit(1)
+
+
+if __name__ == '__main__':
+  check_python_version()
+
 
 # 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'
+REPO_REV = os.environ.get('REPO_REV')
+if not REPO_REV:
+  REPO_REV = 'stable'
 
 # Copyright (C) 2008 Google Inc.
 #
@@ -23,10 +133,10 @@
 # limitations under the License.
 
 # increment this whenever we make important changes to this script
-VERSION = (1, 25)
+VERSION = (2, 4)
 
 # increment this if the MAINTAINER_KEYS block is modified
-KEYRING_VERSION = (1, 2)
+KEYRING_VERSION = (2, 3)
 
 # Each individual key entry is created by using:
 # gpg --armor --export keyid
@@ -34,7 +144,6 @@
 
      Repo Maintainer <repo@android.kernel.org>
 -----BEGIN PGP PUBLIC KEY BLOCK-----
-Version: GnuPG v1.4.2.2 (GNU/Linux)
 
 mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
 WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+IXJDF5MJYcB8f22wAy15lUqPWi
@@ -70,62 +179,63 @@
 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/428W2qhdzYfvB15/AasRmwmor
-py4NIzSs8UD/SPr1ihqNCdZM76+MQyN5HMYXW/ALZXUFG0pwluHFA7hrfPG74i8C
-zMiP7qvMWIl/r/jtzHioH1dRKgbod+LZsrDJ8mBaqsZaDmNJMhss9g76XvfMyLra
-9DI9/iFuBpGzeqBv0hwOGQspLRrEoyTe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/KkYhYOWFx7zRyDhrTf9spAPwIfSBOAGtwxjLO
+DCce5OaQJl/YuGHvXq2yx5h7T8pdAZ+PAJ4qfIk2LLSidsplTDXOKhOQAuOqUQCf
+cZ7aFsJF4PtcDrfdejyAxbtsSHI=
+=82Tj
 -----END PGP PUBLIC KEY BLOCK-----
 """
 
 GIT = 'git'                      # our git command
+# NB: The version of git that the repo launcher requires may be much older than
+# the version of git that the main repo source tree requires.  Keeping this at
+# an older version also makes it easier for users to upgrade/rollback as needed.
+#
+# git-1.7 is in (EOL) Ubuntu Precise.
 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 collections
 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
@@ -138,120 +248,161 @@
   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')
+def GetParser(gitc_init=False):
+  """Setup the CLI parser."""
+  if gitc_init:
+    usage = 'repo gitc-init -u url -c client [options]'
+  else:
+    usage = 'repo init -u url [options]'
 
-# 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')
+  parser = optparse.OptionParser(usage=usage)
+
+  # Logging.
+  group = parser.add_option_group('Logging options')
+  group.add_option('-q', '--quiet',
+                   action='store_true', default=False,
+                   help='be quiet')
+
+  # Manifest.
+  group = parser.add_option_group('Manifest options')
+  group.add_option('-u', '--manifest-url',
+                   help='manifest repository location', metavar='URL')
+  group.add_option('-b', '--manifest-branch',
+                   help='manifest branch or revision', metavar='REVISION')
+  group.add_option('-m', '--manifest-name',
+                   help='initial manifest file', metavar='NAME.xml')
+  cbr_opts = ['--current-branch']
+  # The gitc-init subcommand allocates -c itself, but a lot of init users
+  # want -c, so try to satisfy both as best we can.
+  if not gitc_init:
+    cbr_opts += ['-c']
+  group.add_option(*cbr_opts,
+                   dest='current_branch_only', action='store_true',
+                   help='fetch only current manifest branch from server')
+  group.add_option('--mirror', action='store_true',
+                   help='create a replica of the remote repositories '
+                        'rather than a client working directory')
+  group.add_option('--reference',
+                   help='location of mirror directory', metavar='DIR')
+  group.add_option('--dissociate', action='store_true',
+                   help='dissociate from reference mirrors after clone')
+  group.add_option('--depth', type='int', default=None,
+                   help='create a shallow clone with given depth; '
+                        'see git clone')
+  group.add_option('--partial-clone', action='store_true',
+                   help='perform partial clone (https://git-scm.com/'
+                        'docs/gitrepository-layout#_code_partialclone_code)')
+  group.add_option('--clone-filter', action='store', default='blob:none',
+                   help='filter for use with --partial-clone '
+                        '[default: %default]')
+  group.add_option('--worktree', action='store_true',
+                   help=optparse.SUPPRESS_HELP)
+  group.add_option('--archive', action='store_true',
+                   help='checkout an archive instead of a git repository for '
+                        'each project. See git archive.')
+  group.add_option('--submodules', action='store_true',
+                   help='sync any submodules associated with the manifest repo')
+  group.add_option('-g', '--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', 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='clone_bundle', default=True, action='store_false',
+                   help='disable use of /clone.bundle on HTTP/HTTPS')
+  group.add_option('--no-tags',
+                   dest='tags', default=True, action='store_false',
+                   help="don't fetch tags in the manifest")
+
+  # Tool.
+  group = parser.add_option_group('repo Version options')
+  group.add_option('--repo-url', metavar='URL',
+                   help='repo repository location ($REPO_URL)')
+  group.add_option('--repo-branch', metavar='REVISION',
+                   help='repo branch or revision ($REPO_REV)')
+  group.add_option('--no-repo-verify',
+                   dest='repo_verify', default=True, action='store_false',
+                   help='do not verify repo source code')
+
+  # Other.
+  group = parser.add_option_group('Other options')
+  group.add_option('--config-name',
+                   action='store_true', default=False,
+                   help='Always prompt for name/e-mail')
+
+  # gitc-init specific settings.
+  if gitc_init:
+    group = parser.add_option_group('GITC options')
+    group.add_option('-f', '--manifest-file',
+                     help='Optional manifest file to use for this GITC client.')
+    group.add_option('-c', '--gitc-client',
+                     help='Name of the gitc_client instance to create or modify.')
+
+  return parser
 
 
-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.')
+# This is a poor replacement for subprocess.run until we require Python 3.6+.
+RunResult = collections.namedtuple(
+    'RunResult', ('returncode', 'stdout', 'stderr'))
+
+
+class RunError(Exception):
+  """Error when running a command failed."""
+
+
+def run_command(cmd, **kwargs):
+  """Run |cmd| and return its output."""
+  check = kwargs.pop('check', False)
+  if kwargs.pop('capture_output', False):
+    kwargs.setdefault('stdout', subprocess.PIPE)
+    kwargs.setdefault('stderr', subprocess.PIPE)
+  cmd_input = kwargs.pop('input', None)
+
+  def decode(output):
+    """Decode |output| to text."""
+    if output is None:
+      return output
+    try:
+      return output.decode('utf-8')
+    except UnicodeError:
+      print('repo: warning: Invalid UTF-8 output:\ncmd: %r\n%r' % (cmd, output),
+            file=sys.stderr)
+      # TODO(vapier): Once we require Python 3, use 'backslashreplace'.
+      return output.decode('utf-8', 'replace')
+
+  # Run & package the results.
+  proc = subprocess.Popen(cmd, **kwargs)
+  (stdout, stderr) = proc.communicate(input=cmd_input)
+  trace.print(':', ' '.join(cmd))
+  ret = RunResult(proc.returncode, decode(stdout), decode(stderr))
+
+  # If things failed, print useful debugging output.
+  if check and ret.returncode:
+    print('repo: error: "%s" failed with exit status %s' %
+          (cmd[0], ret.returncode), file=sys.stderr)
+    print('  cwd: %s\n  cmd: %r' %
+          (kwargs.get('cwd', os.getcwd()), cmd), file=sys.stderr)
+
+    def _print_output(name, output):
+      if output:
+        print('  %s:\n  >> %s' % (name, '\n  >> '.join(output.splitlines())),
+              file=sys.stderr)
+
+    _print_output('stdout', ret.stdout)
+    _print_output('stderr', ret.stderr)
+    raise RunError(ret)
+
+  return ret
+
 
 _gitc_manifest_dir = None
 
@@ -303,11 +454,10 @@
 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)
+  parser = GetParser(gitc_init=gitc_init)
+  opt, args = parser.parse_args(args)
   if args:
-    init_optparse.print_usage()
+    parser.print_usage()
     sys.exit(1)
 
   url = opt.repo_url
@@ -323,21 +473,21 @@
   if branch.startswith('refs/heads/'):
     branch = branch[len('refs/heads/'):]
   if branch.startswith('refs/'):
-    _print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
+    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)
+        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)
+        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):
@@ -350,8 +500,8 @@
     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)
+      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.
       #
@@ -359,15 +509,18 @@
 
   _CheckGitVersion()
   try:
-    if NeedSetupGnuPG():
-      can_verify = SetupGnuPG(opt.quiet)
+    if not opt.repo_verify:
+      do_verify = False
     else:
-      can_verify = True
+      if NeedSetupGnuPG():
+        do_verify = SetupGnuPG(opt.quiet)
+      else:
+        do_verify = True
 
     dst = os.path.abspath(os.path.join(repodir, S_repo))
-    _Clone(url, dst, opt.quiet, not opt.no_clone_bundle)
+    _Clone(url, dst, opt.quiet, opt.clone_bundle)
 
-    if can_verify and not opt.no_repo_verify:
+    if do_verify:
       rev = _Verify(dst, branch, opt.quiet)
     else:
       rev = 'refs/remotes/origin/%s^0' % branch
@@ -375,58 +528,105 @@
     _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)
+      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)
+      print('fatal: repo init failed; run without --quiet to see why',
+            file=sys.stderr)
     raise
 
 
-def ParseGitVersion(ver_str):
+def run_git(*args, **kwargs):
+  """Run git and return execution details."""
+  kwargs.setdefault('capture_output', True)
+  kwargs.setdefault('check', True)
+  try:
+    return run_command([GIT] + list(args), **kwargs)
+  except OSError as e:
+    print(file=sys.stderr)
+    print('repo: error: "%s" is not available' % GIT, file=sys.stderr)
+    print('repo: error: %s' % e, file=sys.stderr)
+    print(file=sys.stderr)
+    print('Please make sure %s is installed and in your path.' % GIT,
+          file=sys.stderr)
+    sys.exit(1)
+  except RunError:
+    raise CloneFailure()
+
+
+# The git version info broken down into components for easy analysis.
+# Similar to Python's sys.version_info.
+GitVersion = collections.namedtuple(
+    'GitVersion', ('major', 'minor', 'micro', 'full'))
+
+
+def ParseGitVersion(ver_str=None):
+  if ver_str is None:
+    # Load the version ourselves.
+    ver_str = run_git('--version').stdout
+
   if not ver_str.startswith('git version '):
     return None
 
-  num_ver_str = ver_str[len('git version '):].strip().split('-')[0]
+  full_version = ver_str[len('git version '):].strip()
+  num_ver_str = full_version.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)
+  to_tuple.append(full_version)
+  return GitVersion(*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)
+  ver_act = ParseGitVersion()
   if ver_act is None:
-    _print('error: "%s" unsupported' % ver_str, file=sys.stderr)
+    print('fatal: unable to detect git version', 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)
+    print('fatal: git %s or later required' % need, file=sys.stderr)
     raise CloneFailure()
 
 
+def SetGitTrace2ParentSid(env=None):
+  """Set up GIT_TRACE2_PARENT_SID for git tracing."""
+  # We roughly follow the format git itself uses in trace2/tr2_sid.c.
+  # (1) Be unique (2) be valid filename (3) be fixed length.
+  #
+  # Since we always export this variable, we try to avoid more expensive calls.
+  # e.g. We don't attempt hostname lookups or hashing the results.
+  if env is None:
+    env = os.environ
+
+  KEY = 'GIT_TRACE2_PARENT_SID'
+
+  now = datetime.datetime.utcnow()
+  value = 'repo-%s-P%08x' % (now.strftime('%Y%m%dT%H%M%SZ'), os.getpid())
+
+  # If it's already set, then append ourselves.
+  if KEY in env:
+    value = env[KEY] + '/' + value
+
+  _setenv(KEY, value, env=env)
+
+
+def _setenv(key, value, env=None):
+  """Set |key| in the OS environment |env| to |value|."""
+  if env is None:
+    env = os.environ
+  # Environment handling across systems is messy.
+  try:
+    env[key] = value
+  except UnicodeEncodeError:
+    env[key] = value.encode()
+
+
 def NeedSetupGnuPG():
   if not os.path.isdir(home_dot_repo):
     return True
@@ -450,56 +650,66 @@
     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)
+      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)
+      print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
+            file=sys.stderr)
       sys.exit(1)
 
-  env = os.environ.copy()
+  if not quiet:
+    print('repo: Updating release signing keys to keyset ver %s' %
+          ('.'.join(str(x) for x in KEYRING_VERSION),))
+  # NB: We use --homedir (and cwd below) because some environments (Windows) do
+  # not correctly handle full native paths.  We avoid the issue by changing to
+  # the right dir with cwd=gpg_dir before executing gpg, and then telling gpg to
+  # use the cwd (.) as its homedir which leaves the path resolution logic to it.
+  cmd = ['gpg', '--homedir', '.', '--import']
   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:
+    # gpg can be pretty chatty.  Always capture the output and if something goes
+    # wrong, the builtin check failure will dump stdout & stderr for debugging.
+    run_command(cmd, stdin=subprocess.PIPE, capture_output=True,
+                cwd=gpg_dir, check=True,
+                input=MAINTAINER_KEYS.encode('utf-8'))
+  except OSError:
     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)
+      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()
+  with open(os.path.join(home_dot_repo, 'keyring-version'), 'w') as fd:
+    fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
   return True
 
 
-def _SetConfig(local, name, value):
+def _SetConfig(cwd, 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()
+  run_git('config', name, value, cwd=cwd)
+
+
+def _GetRepoConfig(name):
+  """Read a repo configuration option."""
+  config = os.path.join(home_dot_repo, 'config')
+  if not os.path.exists(config):
+    return None
+
+  cmd = ['config', '--file', config, '--get', name]
+  ret = run_git(*cmd, check=False)
+  if ret.returncode == 0:
+    return ret.stdout
+  elif ret.returncode == 1:
+    return None
+  else:
+    print('repo: error: git %s failed:\n%s' % (' '.join(cmd), ret.stderr),
+          file=sys.stderr)
+    raise RunError()
 
 
 def _InitHttp():
@@ -513,7 +723,7 @@
       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:
+  except Exception:
     pass
   handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
   handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
@@ -527,11 +737,11 @@
   urllib.request.install_opener(urllib.request.build_opener(*handlers))
 
 
-def _Fetch(url, local, src, quiet):
+def _Fetch(url, cwd, src, quiet):
   if not quiet:
-    _print('Get %s' % url, file=sys.stderr)
+    print('Get %s' % url, file=sys.stderr)
 
-  cmd = [GIT, 'fetch']
+  cmd = ['fetch']
   if quiet:
     cmd.append('--quiet')
     err = subprocess.PIPE
@@ -540,25 +750,17 @@
   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()
+  run_git(*cmd, stderr=err, cwd=cwd)
 
 
-def _DownloadBundle(url, local, quiet):
+def _DownloadBundle(url, cwd, 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:
+  ret = run_git('config', '--get-regexp', 'url.*.insteadof', cwd=cwd,
+                check=False)
+  for line in ret.stdout.splitlines():
     m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
     if m:
       new_url = m.group(1)
@@ -566,32 +768,30 @@
       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')
+  dest = open(os.path.join(cwd, '.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)
+      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)
+      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)
+        print('Get %s' % url, file=sys.stderr)
       while True:
         buf = r.read(8192)
-        if buf == '':
+        if not buf:
           return True
         dest.write(buf)
     finally:
@@ -600,124 +800,76 @@
     dest.close()
 
 
-def _ImportBundle(local):
-  path = os.path.join(local, '.git', 'clone.bundle')
+def _ImportBundle(cwd):
+  path = os.path.join(cwd, '.git', 'clone.bundle')
   try:
-    _Fetch(local, local, path, True)
+    _Fetch(cwd, cwd, path, True)
   finally:
     os.remove(path)
 
 
-def _Clone(url, local, quiet, clone_bundle):
+def _Clone(url, cwd, quiet, clone_bundle):
   """Clones a git repository to a new subdirectory of repodir
   """
   try:
-    os.mkdir(local)
+    os.mkdir(cwd)
   except OSError as e:
-    _print('fatal: cannot make %s directory: %s' % (local, e.strerror),
-           file=sys.stderr)
+    print('fatal: cannot make %s directory: %s' % (cwd, 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()
+  run_git('init', '--quiet', cwd=cwd)
 
   _InitHttp()
-  _SetConfig(local, 'remote.origin.url', url)
-  _SetConfig(local,
+  _SetConfig(cwd, 'remote.origin.url', url)
+  _SetConfig(cwd,
              'remote.origin.fetch',
              '+refs/heads/*:refs/remotes/origin/*')
-  if clone_bundle and _DownloadBundle(url, local, quiet):
-    _ImportBundle(local)
-  _Fetch(url, local, 'origin', quiet)
+  if clone_bundle and _DownloadBundle(url, cwd, quiet):
+    _ImportBundle(cwd)
+  _Fetch(url, cwd, '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()
+  try:
+    ret = run_git('describe', 'origin/%s' % branch, cwd=cwd)
+    cur = ret.stdout.strip()
+  except CloneFailure:
+    print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
+    raise
 
   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)
+      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()
+  _setenv('GNUPGHOME', gpg_dir, env)
+  run_git('tag', '-v', cur, cwd=cwd, env=env)
   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()
+  run_git('update-ref', 'refs/heads/default', rev, cwd=cwd)
 
   _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()
+  run_git('symbolic-ref', 'HEAD', 'refs/heads/default', cwd=cwd)
 
-  cmd = [GIT, 'read-tree', '--reset', '-u']
+  cmd = ['read-tree', '--reset', '-u']
   if not quiet:
     cmd.append('-v')
   cmd.append('HEAD')
-  if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
-    raise CloneFailure()
+  run_git(*cmd, cwd=cwd)
 
 
 def _FindRepo():
@@ -740,6 +892,26 @@
 
 class _Options(object):
   help = False
+  version = False
+
+
+def _ExpandAlias(name):
+  """Look up user registered aliases."""
+  # We don't resolve aliases for existing subcommands.  This matches git.
+  if name in {'gitc-init', 'help', 'init'}:
+    return name, []
+
+  alias = _GetRepoConfig('alias.%s' % (name,))
+  if alias is None:
+    return name, []
+
+  args = alias.strip().split(' ', 1)
+  name = args[0]
+  if len(args) == 2:
+    args = shlex.split(args[1])
+  else:
+    args = []
+  return name, args
 
 
 def _ParseArguments(args):
@@ -751,7 +923,10 @@
     a = args[i]
     if a == '-h' or a == '--help':
       opt.help = True
-
+    elif a == '--version':
+      opt.version = True
+    elif a == '--trace':
+      trace.set(True)
     elif not a.startswith('-'):
       cmd = a
       arg = args[i + 1:]
@@ -764,7 +939,7 @@
   if get_gitc_manifest_dir():
     gitc_usage = "  gitc-init Initialize a GITC Client.\n"
 
-  _print(
+  print(
       """usage: repo COMMAND [ARGS]
 
 repo is not yet installed.  Use "repo init" to install it here.
@@ -776,37 +951,44 @@
       """  help      Display detailed help on a command
 
 For access to the full online help, install repo ("repo init").
-""", file=sys.stderr)
-  sys.exit(1)
+""")
+  sys.exit(0)
 
 
 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()
+    if args[0] in {'init', 'gitc-init'}:
+      parser = GetParser(gitc_init=args[0] == 'gitc-init')
+      parser.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)
+      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 _Version():
+  """Show version information."""
+  print('<repo not installed>')
+  print('repo launcher version %s' % ('.'.join(str(x) for x in VERSION),))
+  print('       (from %s)' % (__file__,))
+  print('git %s' % (ParseGitVersion().full,))
+  print('Python %s' % sys.version)
+  sys.exit(0)
+
+
 def _NotInstalled():
-  _print('error: repo is not installed.  Use "repo init" to install it here.',
-         file=sys.stderr)
+  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)
+  print("""error: command '%s' requires repo to be installed first.
+        Use "repo init" to install it here.""" % cmd, file=sys.stderr)
   sys.exit(1)
 
 
@@ -830,26 +1012,20 @@
   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)
+  try:
+    ret = run_git('--git-dir=%s' % gitdir, 'symbolic-ref', 'HEAD')
+    REPO_REV = ret.stdout.strip()
+  except CloneFailure:
+    print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
     sys.exit(1)
 
 
 def main(orig_args):
   cmd, opt, args = _ParseArguments(orig_args)
 
+  # We run this early as we run some git commands ourselves.
+  SetGitTrace2ParentSid()
+
   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':
@@ -860,16 +1036,23 @@
 
   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)
+    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:
+    # Only expand aliases here since we'll be parsing the CLI ourselves.
+    # If we had repo_main, alias expansion would happen in main.py.
+    cmd, alias_args = _ExpandAlias(cmd)
+    args = alias_args + args
+
     if opt.help:
       _Usage()
     if cmd == 'help':
       _Help(args)
+    if opt.version or cmd == 'version':
+      _Version()
     if not cmd:
       _NotInstalled()
     if cmd == 'init' or cmd == 'gitc-init':
@@ -879,8 +1062,8 @@
         _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)
+        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()
@@ -898,20 +1081,10 @@
         '--']
   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)
+  exec_command(me)
+  print("fatal: unable to start %s" % repo_main, 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:])