repo 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. """Repo launcher.
  4. This is a standalone tool that people may copy to anywhere in their system.
  5. It is used to get an initial repo client checkout, and after that it runs the
  6. copy of repo in the checkout.
  7. """
  8. from __future__ import print_function
  9. import datetime
  10. import os
  11. import platform
  12. import subprocess
  13. import sys
  14. # Keep basic logic in sync with repo_trace.py.
  15. class Trace(object):
  16. """Trace helper logic."""
  17. REPO_TRACE = 'REPO_TRACE'
  18. def __init__(self):
  19. self.set(os.environ.get(self.REPO_TRACE) == '1')
  20. def set(self, value):
  21. self.enabled = bool(value)
  22. def print(self, *args, **kwargs):
  23. if self.enabled:
  24. print(*args, **kwargs)
  25. trace = Trace()
  26. def exec_command(cmd):
  27. """Execute |cmd| or return None on failure."""
  28. trace.print(':', ' '.join(cmd))
  29. try:
  30. if platform.system() == 'Windows':
  31. ret = subprocess.call(cmd)
  32. sys.exit(ret)
  33. else:
  34. os.execvp(cmd[0], cmd)
  35. except Exception:
  36. pass
  37. def check_python_version():
  38. """Make sure the active Python version is recent enough."""
  39. def reexec(prog):
  40. exec_command([prog] + sys.argv)
  41. MIN_PYTHON_VERSION = (3, 6)
  42. ver = sys.version_info
  43. major = ver.major
  44. minor = ver.minor
  45. # Abort on very old Python 2 versions.
  46. if (major, minor) < (2, 7):
  47. print('repo: error: Your Python version is too old. '
  48. 'Please use Python {}.{} or newer instead.'.format(
  49. *MIN_PYTHON_VERSION), file=sys.stderr)
  50. sys.exit(1)
  51. # Try to re-exec the version specific Python 3 if needed.
  52. if (major, minor) < MIN_PYTHON_VERSION:
  53. # Python makes releases ~once a year, so try our min version +10 to help
  54. # bridge the gap. This is the fallback anyways so perf isn't critical.
  55. min_major, min_minor = MIN_PYTHON_VERSION
  56. for inc in range(0, 10):
  57. reexec('python{}.{}'.format(min_major, min_minor + inc))
  58. # Try the generic Python 3 wrapper, but only if it's new enough. We don't
  59. # want to go from (still supported) Python 2.7 to (unsupported) Python 3.5.
  60. try:
  61. proc = subprocess.Popen(
  62. ['python3', '-c', 'import sys; '
  63. 'print(sys.version_info.major, sys.version_info.minor)'],
  64. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  65. (output, _) = proc.communicate()
  66. python3_ver = tuple(int(x) for x in output.decode('utf-8').split())
  67. except (OSError, subprocess.CalledProcessError):
  68. python3_ver = None
  69. # The python3 version looks like it's new enough, so give it a try.
  70. if python3_ver and python3_ver >= MIN_PYTHON_VERSION:
  71. reexec('python3')
  72. # We're still here, so diagnose things for the user.
  73. if major < 3:
  74. print('repo: warning: Python 2 is no longer supported; '
  75. 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION),
  76. file=sys.stderr)
  77. else:
  78. print('repo: error: Python 3 version is too old; '
  79. 'Please use Python {}.{} or newer.'.format(*MIN_PYTHON_VERSION),
  80. file=sys.stderr)
  81. sys.exit(1)
  82. if __name__ == '__main__':
  83. # TODO(vapier): Enable this on Windows once we have Python 3 issues fixed.
  84. if platform.system() != 'Windows':
  85. check_python_version()
  86. # repo default configuration
  87. #
  88. REPO_URL = os.environ.get('REPO_URL', None)
  89. if not REPO_URL:
  90. REPO_URL = 'https://gerrit.googlesource.com/git-repo'
  91. REPO_REV = os.environ.get('REPO_REV')
  92. if not REPO_REV:
  93. REPO_REV = 'stable'
  94. # Copyright (C) 2008 Google Inc.
  95. #
  96. # Licensed under the Apache License, Version 2.0 (the "License");
  97. # you may not use this file except in compliance with the License.
  98. # You may obtain a copy of the License at
  99. #
  100. # http://www.apache.org/licenses/LICENSE-2.0
  101. #
  102. # Unless required by applicable law or agreed to in writing, software
  103. # distributed under the License is distributed on an "AS IS" BASIS,
  104. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  105. # See the License for the specific language governing permissions and
  106. # limitations under the License.
  107. # increment this whenever we make important changes to this script
  108. VERSION = (2, 3)
  109. # increment this if the MAINTAINER_KEYS block is modified
  110. KEYRING_VERSION = (2, 0)
  111. # Each individual key entry is created by using:
  112. # gpg --armor --export keyid
  113. MAINTAINER_KEYS = """
  114. Repo Maintainer <repo@android.kernel.org>
  115. -----BEGIN PGP PUBLIC KEY BLOCK-----
  116. Version: GnuPG v1.4.2.2 (GNU/Linux)
  117. mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
  118. WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+IXJDF5MJYcB8f22wAy15lUqPWi
  119. VCkk1l8qqLiuW0fo+ZkPY5qOgrvc0HW1SmdH649uNwqCbcKb6CxaTxzhOwCgj3AP
  120. xI1WfzLqdJjsm1Nq98L0cLcD/iNsILCuw44PRds3J75YP0pze7YF/6WFMB6QSFGu
  121. aUX1FsTTztKNXGms8i5b2l1B8JaLRWq/jOnZzyl1zrUJhkc0JgyZW5oNLGyWGhKD
  122. Fxp5YpHuIuMImopWEMFIRQNrvlg+YVK8t3FpdI1RY0LYqha8pPzANhEYgSfoVzOb
  123. fbfbA/4ioOrxy8ifSoga7ITyZMA+XbW8bx33WXutO9N7SPKS/AK2JpasSEVLZcON
  124. ae5hvAEGVXKxVPDjJBmIc2cOe7kOKSi3OxLzBqrjS2rnjiP4o0ekhZIe4+ocwVOg
  125. e0PLlH5avCqihGRhpoqDRsmpzSHzJIxtoeb+GgGEX8KkUsVAhbQpUmVwbyBNYWlu
  126. dGFpbmVyIDxyZXBvQGFuZHJvaWQua2VybmVsLm9yZz6IYAQTEQIAIAUCSPe6AQIb
  127. AwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEBZTDV6SD1xl1GEAn0x/OKQpy7qI
  128. 6G73NJviU0IUMtftAKCFMUhGb/0bZvQ8Rm3QCUpWHyEIu7kEDQRI97ogEBAA2wI6
  129. 5fs9y/rMwD6dkD/vK9v4C9mOn1IL5JCPYMJBVSci+9ED4ChzYvfq7wOcj9qIvaE0
  130. GwCt2ar7Q56me5J+byhSb32Rqsw/r3Vo5cZMH80N4cjesGuSXOGyEWTe4HYoxnHv
  131. gF4EKI2LK7xfTUcxMtlyn52sUpkfKsCpUhFvdmbAiJE+jCkQZr1Z8u2KphV79Ou+
  132. P1N5IXY/XWOlq48Qf4MWCYlJFrB07xjUjLKMPDNDnm58L5byDrP/eHysKexpbakL
  133. xCmYyfT6DV1SWLblpd2hie0sL3YejdtuBMYMS2rI7Yxb8kGuqkz+9l1qhwJtei94
  134. 5MaretDy/d/JH/pRYkRf7L+ke7dpzrP+aJmcz9P1e6gq4NJsWejaALVASBiioqNf
  135. QmtqSVzF1wkR5avZkFHuYvj6V/t1RrOZTXxkSk18KFMJRBZrdHFCWbc5qrVxUB6e
  136. N5pja0NFIUCigLBV1c6I2DwiuboMNh18VtJJh+nwWeez/RueN4ig59gRTtkcc0PR
  137. 35tX2DR8+xCCFVW/NcJ4PSePYzCuuLvp1vEDHnj41R52Fz51hgddT4rBsp0nL+5I
  138. socSOIIezw8T9vVzMY4ArCKFAVu2IVyBcahTfBS8q5EM63mONU6UVJEozfGljiMw
  139. xuQ7JwKcw0AUEKTKG7aBgBaTAgT8TOevpvlw91cAAwUP/jRkyVi/0WAb0qlEaq/S
  140. ouWxX1faR+vU3b+Y2/DGjtXQMzG0qpetaTHC/AxxHpgt/dCkWI6ljYDnxgPLwG0a
  141. Oasm94BjZc6vZwf1opFZUKsjOAAxRxNZyjUJKe4UZVuMTk6zo27Nt3LMnc0FO47v
  142. FcOjRyquvgNOS818irVHUf12waDx8gszKxQTTtFxU5/ePB2jZmhP6oXSe4K/LG5T
  143. +WBRPDrHiGPhCzJRzm9BP0lTnGCAj3o9W90STZa65RK7IaYpC8TB35JTBEbrrNCp
  144. w6lzd74LnNEp5eMlKDnXzUAgAH0yzCQeMl7t33QCdYx2hRs2wtTQSjGfAiNmj/WW
  145. Vl5Jn+2jCDnRLenKHwVRFsBX2e0BiRWt/i9Y8fjorLCXVj4z+7yW6DawdLkJorEo
  146. p3v5ILwfC7hVx4jHSnOgZ65L9s8EQdVr1ckN9243yta7rNgwfcqb60ILMFF1BRk/
  147. 0V7wCL+68UwwiQDvyMOQuqkysKLSDCLb7BFcyA7j6KG+5hpsREstFX2wK1yKeraz
  148. 5xGrFy8tfAaeBMIQ17gvFSp/suc9DYO0ICK2BISzq+F+ZiAKsjMYOBNdH/h0zobQ
  149. HTHs37+/QLMomGEGKZMWi0dShU2J5mNRQu3Hhxl3hHDVbt5CeJBb26aQcQrFz69W
  150. zE3GNvmJosh6leayjtI9P2A6iEkEGBECAAkFAkj3uiACGwwACgkQFlMNXpIPXGWp
  151. TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2
  152. =CMiZ
  153. -----END PGP PUBLIC KEY BLOCK-----
  154. """
  155. GIT = 'git' # our git command
  156. # NB: The version of git that the repo launcher requires may be much older than
  157. # the version of git that the main repo source tree requires. Keeping this at
  158. # an older version also makes it easier for users to upgrade/rollback as needed.
  159. #
  160. # git-1.7 is in (EOL) Ubuntu Precise.
  161. MIN_GIT_VERSION = (1, 7, 2) # minimum supported git version
  162. repodir = '.repo' # name of repo's private directory
  163. S_repo = 'repo' # special repo repository
  164. S_manifests = 'manifests' # special manifest repository
  165. REPO_MAIN = S_repo + '/main.py' # main script
  166. GITC_CONFIG_FILE = '/gitc/.config'
  167. GITC_FS_ROOT_DIR = '/gitc/manifest-rw/'
  168. import collections
  169. import errno
  170. import optparse
  171. import re
  172. import shutil
  173. import stat
  174. if sys.version_info[0] == 3:
  175. import urllib.request
  176. import urllib.error
  177. else:
  178. import imp
  179. import urllib2
  180. urllib = imp.new_module('urllib')
  181. urllib.request = urllib2
  182. urllib.error = urllib2
  183. home_dot_repo = os.path.expanduser('~/.repoconfig')
  184. gpg_dir = os.path.join(home_dot_repo, 'gnupg')
  185. extra_args = []
  186. init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
  187. def _InitParser():
  188. """Setup the init subcommand parser."""
  189. # Logging.
  190. group = init_optparse.add_option_group('Logging options')
  191. group.add_option('-q', '--quiet',
  192. action='store_true', default=False,
  193. help='be quiet')
  194. # Manifest.
  195. group = init_optparse.add_option_group('Manifest options')
  196. group.add_option('-u', '--manifest-url',
  197. help='manifest repository location', metavar='URL')
  198. group.add_option('-b', '--manifest-branch',
  199. help='manifest branch or revision', metavar='REVISION')
  200. group.add_option('-m', '--manifest-name',
  201. help='initial manifest file', metavar='NAME.xml')
  202. group.add_option('--current-branch',
  203. dest='current_branch_only', action='store_true',
  204. help='fetch only current manifest branch from server')
  205. group.add_option('--mirror', action='store_true',
  206. help='create a replica of the remote repositories '
  207. 'rather than a client working directory')
  208. group.add_option('--reference',
  209. help='location of mirror directory', metavar='DIR')
  210. group.add_option('--dissociate', action='store_true',
  211. help='dissociate from reference mirrors after clone')
  212. group.add_option('--depth', type='int', default=None,
  213. help='create a shallow clone with given depth; '
  214. 'see git clone')
  215. group.add_option('--partial-clone', action='store_true',
  216. help='perform partial clone (https://git-scm.com/'
  217. 'docs/gitrepository-layout#_code_partialclone_code)')
  218. group.add_option('--clone-filter', action='store', default='blob:none',
  219. help='filter for use with --partial-clone '
  220. '[default: %default]')
  221. group.add_option('--archive', action='store_true',
  222. help='checkout an archive instead of a git repository for '
  223. 'each project. See git archive.')
  224. group.add_option('--submodules', action='store_true',
  225. help='sync any submodules associated with the manifest repo')
  226. group.add_option('-g', '--groups', default='default',
  227. help='restrict manifest projects to ones with specified '
  228. 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
  229. metavar='GROUP')
  230. group.add_option('-p', '--platform', default='auto',
  231. help='restrict manifest projects to ones with a specified '
  232. 'platform group [auto|all|none|linux|darwin|...]',
  233. metavar='PLATFORM')
  234. group.add_option('--no-clone-bundle', action='store_true',
  235. help='disable use of /clone.bundle on HTTP/HTTPS')
  236. group.add_option('--no-tags', action='store_true',
  237. help="don't fetch tags in the manifest")
  238. # Tool.
  239. group = init_optparse.add_option_group('repo Version options')
  240. group.add_option('--repo-url', metavar='URL',
  241. help='repo repository location ($REPO_URL)')
  242. group.add_option('--repo-branch', metavar='REVISION',
  243. help='repo branch or revision ($REPO_REV)')
  244. group.add_option('--no-repo-verify', action='store_true',
  245. help='do not verify repo source code')
  246. # Other.
  247. group = init_optparse.add_option_group('Other options')
  248. group.add_option('--config-name',
  249. action='store_true', default=False,
  250. help='Always prompt for name/e-mail')
  251. def _GitcInitOptions(init_optparse_arg):
  252. init_optparse_arg.set_usage("repo gitc-init -u url -c client [options]")
  253. g = init_optparse_arg.add_option_group('GITC options')
  254. g.add_option('-f', '--manifest-file',
  255. dest='manifest_file',
  256. help='Optional manifest file to use for this GITC client.')
  257. g.add_option('-c', '--gitc-client',
  258. dest='gitc_client',
  259. help='The name of the gitc_client instance to create or modify.')
  260. # This is a poor replacement for subprocess.run until we require Python 3.6+.
  261. RunResult = collections.namedtuple(
  262. 'RunResult', ('returncode', 'stdout', 'stderr'))
  263. class RunError(Exception):
  264. """Error when running a command failed."""
  265. def run_command(cmd, **kwargs):
  266. """Run |cmd| and return its output."""
  267. check = kwargs.pop('check', False)
  268. if kwargs.pop('capture_output', False):
  269. kwargs.setdefault('stdout', subprocess.PIPE)
  270. kwargs.setdefault('stderr', subprocess.PIPE)
  271. cmd_input = kwargs.pop('input', None)
  272. # Run & package the results.
  273. proc = subprocess.Popen(cmd, **kwargs)
  274. (stdout, stderr) = proc.communicate(input=cmd_input)
  275. if stdout is not None:
  276. stdout = stdout.decode('utf-8')
  277. if stderr is not None:
  278. stderr = stderr.decode('utf-8')
  279. trace.print(':', ' '.join(cmd))
  280. ret = RunResult(proc.returncode, stdout, stderr)
  281. # If things failed, print useful debugging output.
  282. if check and ret.returncode:
  283. print('repo: error: "%s" failed with exit status %s' %
  284. (cmd[0], ret.returncode), file=sys.stderr)
  285. print(' cwd: %s\n cmd: %r' %
  286. (kwargs.get('cwd', os.getcwd()), cmd), file=sys.stderr)
  287. def _print_output(name, output):
  288. if output:
  289. print(' %s:\n >> %s' % (name, '\n >> '.join(output.splitlines())),
  290. file=sys.stderr)
  291. _print_output('stdout', ret.stdout)
  292. _print_output('stderr', ret.stderr)
  293. raise RunError(ret)
  294. return ret
  295. _gitc_manifest_dir = None
  296. def get_gitc_manifest_dir():
  297. global _gitc_manifest_dir
  298. if _gitc_manifest_dir is None:
  299. _gitc_manifest_dir = ''
  300. try:
  301. with open(GITC_CONFIG_FILE, 'r') as gitc_config:
  302. for line in gitc_config:
  303. match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
  304. if match:
  305. _gitc_manifest_dir = match.group('gitc_manifest_dir')
  306. except IOError:
  307. pass
  308. return _gitc_manifest_dir
  309. def gitc_parse_clientdir(gitc_fs_path):
  310. """Parse a path in the GITC FS and return its client name.
  311. @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
  312. @returns: The GITC client name
  313. """
  314. if gitc_fs_path == GITC_FS_ROOT_DIR:
  315. return None
  316. if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
  317. manifest_dir = get_gitc_manifest_dir()
  318. if manifest_dir == '':
  319. return None
  320. if manifest_dir[-1] != '/':
  321. manifest_dir += '/'
  322. if gitc_fs_path == manifest_dir:
  323. return None
  324. if not gitc_fs_path.startswith(manifest_dir):
  325. return None
  326. return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
  327. return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]
  328. class CloneFailure(Exception):
  329. """Indicate the remote clone of repo itself failed.
  330. """
  331. def _Init(args, gitc_init=False):
  332. """Installs repo by cloning it over the network.
  333. """
  334. if gitc_init:
  335. _GitcInitOptions(init_optparse)
  336. opt, args = init_optparse.parse_args(args)
  337. if args:
  338. init_optparse.print_usage()
  339. sys.exit(1)
  340. url = opt.repo_url
  341. if not url:
  342. url = REPO_URL
  343. extra_args.append('--repo-url=%s' % url)
  344. branch = opt.repo_branch
  345. if not branch:
  346. branch = REPO_REV
  347. extra_args.append('--repo-branch=%s' % branch)
  348. if branch.startswith('refs/heads/'):
  349. branch = branch[len('refs/heads/'):]
  350. if branch.startswith('refs/'):
  351. print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
  352. raise CloneFailure()
  353. try:
  354. if gitc_init:
  355. gitc_manifest_dir = get_gitc_manifest_dir()
  356. if not gitc_manifest_dir:
  357. print('fatal: GITC filesystem is not available. Exiting...',
  358. file=sys.stderr)
  359. sys.exit(1)
  360. gitc_client = opt.gitc_client
  361. if not gitc_client:
  362. gitc_client = gitc_parse_clientdir(os.getcwd())
  363. if not gitc_client:
  364. print('fatal: GITC client (-c) is required.', file=sys.stderr)
  365. sys.exit(1)
  366. client_dir = os.path.join(gitc_manifest_dir, gitc_client)
  367. if not os.path.exists(client_dir):
  368. os.makedirs(client_dir)
  369. os.chdir(client_dir)
  370. if os.path.exists(repodir):
  371. # This GITC Client has already initialized repo so continue.
  372. return
  373. os.mkdir(repodir)
  374. except OSError as e:
  375. if e.errno != errno.EEXIST:
  376. print('fatal: cannot make %s directory: %s'
  377. % (repodir, e.strerror), file=sys.stderr)
  378. # Don't raise CloneFailure; that would delete the
  379. # name. Instead exit immediately.
  380. #
  381. sys.exit(1)
  382. _CheckGitVersion()
  383. try:
  384. if opt.no_repo_verify:
  385. do_verify = False
  386. else:
  387. if NeedSetupGnuPG():
  388. do_verify = SetupGnuPG(opt.quiet)
  389. else:
  390. do_verify = True
  391. dst = os.path.abspath(os.path.join(repodir, S_repo))
  392. _Clone(url, dst, opt.quiet, not opt.no_clone_bundle)
  393. if do_verify:
  394. rev = _Verify(dst, branch, opt.quiet)
  395. else:
  396. rev = 'refs/remotes/origin/%s^0' % branch
  397. _Checkout(dst, branch, rev, opt.quiet)
  398. if not os.path.isfile(os.path.join(dst, 'repo')):
  399. print("warning: '%s' does not look like a git-repo repository, is "
  400. "REPO_URL set correctly?" % url, file=sys.stderr)
  401. except CloneFailure:
  402. if opt.quiet:
  403. print('fatal: repo init failed; run without --quiet to see why',
  404. file=sys.stderr)
  405. raise
  406. def run_git(*args, **kwargs):
  407. """Run git and return execution details."""
  408. kwargs.setdefault('capture_output', True)
  409. kwargs.setdefault('check', True)
  410. try:
  411. return run_command([GIT] + list(args), **kwargs)
  412. except OSError as e:
  413. print(file=sys.stderr)
  414. print('repo: error: "%s" is not available' % GIT, file=sys.stderr)
  415. print('repo: error: %s' % e, file=sys.stderr)
  416. print(file=sys.stderr)
  417. print('Please make sure %s is installed and in your path.' % GIT,
  418. file=sys.stderr)
  419. sys.exit(1)
  420. except RunError:
  421. raise CloneFailure()
  422. # The git version info broken down into components for easy analysis.
  423. # Similar to Python's sys.version_info.
  424. GitVersion = collections.namedtuple(
  425. 'GitVersion', ('major', 'minor', 'micro', 'full'))
  426. def ParseGitVersion(ver_str=None):
  427. if ver_str is None:
  428. # Load the version ourselves.
  429. ver_str = run_git('--version').stdout
  430. if not ver_str.startswith('git version '):
  431. return None
  432. full_version = ver_str[len('git version '):].strip()
  433. num_ver_str = full_version.split('-')[0]
  434. to_tuple = []
  435. for num_str in num_ver_str.split('.')[:3]:
  436. if num_str.isdigit():
  437. to_tuple.append(int(num_str))
  438. else:
  439. to_tuple.append(0)
  440. to_tuple.append(full_version)
  441. return GitVersion(*to_tuple)
  442. def _CheckGitVersion():
  443. ver_act = ParseGitVersion()
  444. if ver_act is None:
  445. print('fatal: unable to detect git version', file=sys.stderr)
  446. raise CloneFailure()
  447. if ver_act < MIN_GIT_VERSION:
  448. need = '.'.join(map(str, MIN_GIT_VERSION))
  449. print('fatal: git %s or later required' % need, file=sys.stderr)
  450. raise CloneFailure()
  451. def SetGitTrace2ParentSid(env=None):
  452. """Set up GIT_TRACE2_PARENT_SID for git tracing."""
  453. # We roughly follow the format git itself uses in trace2/tr2_sid.c.
  454. # (1) Be unique (2) be valid filename (3) be fixed length.
  455. #
  456. # Since we always export this variable, we try to avoid more expensive calls.
  457. # e.g. We don't attempt hostname lookups or hashing the results.
  458. if env is None:
  459. env = os.environ
  460. KEY = 'GIT_TRACE2_PARENT_SID'
  461. now = datetime.datetime.utcnow()
  462. value = 'repo-%s-P%08x' % (now.strftime('%Y%m%dT%H%M%SZ'), os.getpid())
  463. # If it's already set, then append ourselves.
  464. if KEY in env:
  465. value = env[KEY] + '/' + value
  466. _setenv(KEY, value, env=env)
  467. def _setenv(key, value, env=None):
  468. """Set |key| in the OS environment |env| to |value|."""
  469. if env is None:
  470. env = os.environ
  471. # Environment handling across systems is messy.
  472. try:
  473. env[key] = value
  474. except UnicodeEncodeError:
  475. env[key] = value.encode()
  476. def NeedSetupGnuPG():
  477. if not os.path.isdir(home_dot_repo):
  478. return True
  479. kv = os.path.join(home_dot_repo, 'keyring-version')
  480. if not os.path.exists(kv):
  481. return True
  482. kv = open(kv).read()
  483. if not kv:
  484. return True
  485. kv = tuple(map(int, kv.split('.')))
  486. if kv < KEYRING_VERSION:
  487. return True
  488. return False
  489. def SetupGnuPG(quiet):
  490. try:
  491. os.mkdir(home_dot_repo)
  492. except OSError as e:
  493. if e.errno != errno.EEXIST:
  494. print('fatal: cannot make %s directory: %s'
  495. % (home_dot_repo, e.strerror), file=sys.stderr)
  496. sys.exit(1)
  497. try:
  498. os.mkdir(gpg_dir, stat.S_IRWXU)
  499. except OSError as e:
  500. if e.errno != errno.EEXIST:
  501. print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
  502. file=sys.stderr)
  503. sys.exit(1)
  504. env = os.environ.copy()
  505. _setenv('GNUPGHOME', gpg_dir, env)
  506. cmd = ['gpg', '--import']
  507. try:
  508. ret = run_command(cmd, env=env, stdin=subprocess.PIPE,
  509. capture_output=quiet,
  510. input=MAINTAINER_KEYS.encode('utf-8'))
  511. except OSError:
  512. if not quiet:
  513. print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
  514. print('warning: Installing it is strongly encouraged.', file=sys.stderr)
  515. print(file=sys.stderr)
  516. return False
  517. if not quiet:
  518. print()
  519. with open(os.path.join(home_dot_repo, 'keyring-version'), 'w') as fd:
  520. fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
  521. return True
  522. def _SetConfig(cwd, name, value):
  523. """Set a git configuration option to the specified value.
  524. """
  525. run_git('config', name, value, cwd=cwd)
  526. def _InitHttp():
  527. handlers = []
  528. mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  529. try:
  530. import netrc
  531. n = netrc.netrc()
  532. for host in n.hosts:
  533. p = n.hosts[host]
  534. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  535. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  536. except Exception:
  537. pass
  538. handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
  539. handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
  540. if 'http_proxy' in os.environ:
  541. url = os.environ['http_proxy']
  542. handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
  543. if 'REPO_CURL_VERBOSE' in os.environ:
  544. handlers.append(urllib.request.HTTPHandler(debuglevel=1))
  545. handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
  546. urllib.request.install_opener(urllib.request.build_opener(*handlers))
  547. def _Fetch(url, cwd, src, quiet):
  548. if not quiet:
  549. print('Get %s' % url, file=sys.stderr)
  550. cmd = ['fetch']
  551. if quiet:
  552. cmd.append('--quiet')
  553. err = subprocess.PIPE
  554. else:
  555. err = None
  556. cmd.append(src)
  557. cmd.append('+refs/heads/*:refs/remotes/origin/*')
  558. cmd.append('+refs/tags/*:refs/tags/*')
  559. run_git(*cmd, stderr=err, cwd=cwd)
  560. def _DownloadBundle(url, cwd, quiet):
  561. if not url.endswith('/'):
  562. url += '/'
  563. url += 'clone.bundle'
  564. ret = run_git('config', '--get-regexp', 'url.*.insteadof', cwd=cwd,
  565. check=False)
  566. for line in ret.stdout.splitlines():
  567. m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
  568. if m:
  569. new_url = m.group(1)
  570. old_url = m.group(2)
  571. if url.startswith(old_url):
  572. url = new_url + url[len(old_url):]
  573. break
  574. if not url.startswith('http:') and not url.startswith('https:'):
  575. return False
  576. dest = open(os.path.join(cwd, '.git', 'clone.bundle'), 'w+b')
  577. try:
  578. try:
  579. r = urllib.request.urlopen(url)
  580. except urllib.error.HTTPError as e:
  581. if e.code in [401, 403, 404, 501]:
  582. return False
  583. print('fatal: Cannot get %s' % url, file=sys.stderr)
  584. print('fatal: HTTP error %s' % e.code, file=sys.stderr)
  585. raise CloneFailure()
  586. except urllib.error.URLError as e:
  587. print('fatal: Cannot get %s' % url, file=sys.stderr)
  588. print('fatal: error %s' % e.reason, file=sys.stderr)
  589. raise CloneFailure()
  590. try:
  591. if not quiet:
  592. print('Get %s' % url, file=sys.stderr)
  593. while True:
  594. buf = r.read(8192)
  595. if not buf:
  596. return True
  597. dest.write(buf)
  598. finally:
  599. r.close()
  600. finally:
  601. dest.close()
  602. def _ImportBundle(cwd):
  603. path = os.path.join(cwd, '.git', 'clone.bundle')
  604. try:
  605. _Fetch(cwd, cwd, path, True)
  606. finally:
  607. os.remove(path)
  608. def _Clone(url, cwd, quiet, clone_bundle):
  609. """Clones a git repository to a new subdirectory of repodir
  610. """
  611. try:
  612. os.mkdir(cwd)
  613. except OSError as e:
  614. print('fatal: cannot make %s directory: %s' % (cwd, e.strerror),
  615. file=sys.stderr)
  616. raise CloneFailure()
  617. run_git('init', '--quiet', cwd=cwd)
  618. _InitHttp()
  619. _SetConfig(cwd, 'remote.origin.url', url)
  620. _SetConfig(cwd,
  621. 'remote.origin.fetch',
  622. '+refs/heads/*:refs/remotes/origin/*')
  623. if clone_bundle and _DownloadBundle(url, cwd, quiet):
  624. _ImportBundle(cwd)
  625. _Fetch(url, cwd, 'origin', quiet)
  626. def _Verify(cwd, branch, quiet):
  627. """Verify the branch has been signed by a tag.
  628. """
  629. try:
  630. ret = run_git('describe', 'origin/%s' % branch, cwd=cwd)
  631. cur = ret.stdout.strip()
  632. except CloneFailure:
  633. print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
  634. raise
  635. m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
  636. if m:
  637. cur = m.group(1)
  638. if not quiet:
  639. print(file=sys.stderr)
  640. print("info: Ignoring branch '%s'; using tagged release '%s'"
  641. % (branch, cur), file=sys.stderr)
  642. print(file=sys.stderr)
  643. env = os.environ.copy()
  644. _setenv('GNUPGHOME', gpg_dir, env)
  645. run_git('tag', '-v', cur, cwd=cwd, env=env)
  646. return '%s^0' % cur
  647. def _Checkout(cwd, branch, rev, quiet):
  648. """Checkout an upstream branch into the repository and track it.
  649. """
  650. run_git('update-ref', 'refs/heads/default', rev, cwd=cwd)
  651. _SetConfig(cwd, 'branch.default.remote', 'origin')
  652. _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
  653. run_git('symbolic-ref', 'HEAD', 'refs/heads/default', cwd=cwd)
  654. cmd = ['read-tree', '--reset', '-u']
  655. if not quiet:
  656. cmd.append('-v')
  657. cmd.append('HEAD')
  658. run_git(*cmd, cwd=cwd)
  659. def _FindRepo():
  660. """Look for a repo installation, starting at the current directory.
  661. """
  662. curdir = os.getcwd()
  663. repo = None
  664. olddir = None
  665. while curdir != '/' \
  666. and curdir != olddir \
  667. and not repo:
  668. repo = os.path.join(curdir, repodir, REPO_MAIN)
  669. if not os.path.isfile(repo):
  670. repo = None
  671. olddir = curdir
  672. curdir = os.path.dirname(curdir)
  673. return (repo, os.path.join(curdir, repodir))
  674. class _Options(object):
  675. help = False
  676. version = False
  677. def _ParseArguments(args):
  678. cmd = None
  679. opt = _Options()
  680. arg = []
  681. for i in range(len(args)):
  682. a = args[i]
  683. if a == '-h' or a == '--help':
  684. opt.help = True
  685. elif a == '--version':
  686. opt.version = True
  687. elif a == '--trace':
  688. trace.set(True)
  689. elif not a.startswith('-'):
  690. cmd = a
  691. arg = args[i + 1:]
  692. break
  693. return cmd, opt, arg
  694. def _Usage():
  695. gitc_usage = ""
  696. if get_gitc_manifest_dir():
  697. gitc_usage = " gitc-init Initialize a GITC Client.\n"
  698. print(
  699. """usage: repo COMMAND [ARGS]
  700. repo is not yet installed. Use "repo init" to install it here.
  701. The most commonly used repo commands are:
  702. init Install repo in the current working directory
  703. """ + gitc_usage +
  704. """ help Display detailed help on a command
  705. For access to the full online help, install repo ("repo init").
  706. """)
  707. sys.exit(0)
  708. def _Help(args):
  709. if args:
  710. if args[0] == 'init':
  711. init_optparse.print_help()
  712. sys.exit(0)
  713. elif args[0] == 'gitc-init':
  714. _GitcInitOptions(init_optparse)
  715. init_optparse.print_help()
  716. sys.exit(0)
  717. else:
  718. print("error: '%s' is not a bootstrap command.\n"
  719. ' For access to online help, install repo ("repo init").'
  720. % args[0], file=sys.stderr)
  721. else:
  722. _Usage()
  723. sys.exit(1)
  724. def _Version():
  725. """Show version information."""
  726. print('<repo not installed>')
  727. print('repo launcher version %s' % ('.'.join(str(x) for x in VERSION),))
  728. print(' (from %s)' % (__file__,))
  729. print('git %s' % (ParseGitVersion().full,))
  730. print('Python %s' % sys.version)
  731. sys.exit(0)
  732. def _NotInstalled():
  733. print('error: repo is not installed. Use "repo init" to install it here.',
  734. file=sys.stderr)
  735. sys.exit(1)
  736. def _NoCommands(cmd):
  737. print("""error: command '%s' requires repo to be installed first.
  738. Use "repo init" to install it here.""" % cmd, file=sys.stderr)
  739. sys.exit(1)
  740. def _RunSelf(wrapper_path):
  741. my_dir = os.path.dirname(wrapper_path)
  742. my_main = os.path.join(my_dir, 'main.py')
  743. my_git = os.path.join(my_dir, '.git')
  744. if os.path.isfile(my_main) and os.path.isdir(my_git):
  745. for name in ['git_config.py',
  746. 'project.py',
  747. 'subcmds']:
  748. if not os.path.exists(os.path.join(my_dir, name)):
  749. return None, None
  750. return my_main, my_git
  751. return None, None
  752. def _SetDefaultsTo(gitdir):
  753. global REPO_URL
  754. global REPO_REV
  755. REPO_URL = gitdir
  756. try:
  757. ret = run_git('--git-dir=%s' % gitdir, 'symbolic-ref', 'HEAD')
  758. REPO_REV = ret.stdout.strip()
  759. except CloneFailure:
  760. print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
  761. sys.exit(1)
  762. def main(orig_args):
  763. cmd, opt, args = _ParseArguments(orig_args)
  764. # We run this early as we run some git commands ourselves.
  765. SetGitTrace2ParentSid()
  766. repo_main, rel_repo_dir = None, None
  767. # Don't use the local repo copy, make sure to switch to the gitc client first.
  768. if cmd != 'gitc-init':
  769. repo_main, rel_repo_dir = _FindRepo()
  770. wrapper_path = os.path.abspath(__file__)
  771. my_main, my_git = _RunSelf(wrapper_path)
  772. cwd = os.getcwd()
  773. if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
  774. print('error: repo cannot be used in the GITC local manifest directory.'
  775. '\nIf you want to work on this GITC client please rerun this '
  776. 'command from the corresponding client under /gitc/',
  777. file=sys.stderr)
  778. sys.exit(1)
  779. _InitParser()
  780. if not repo_main:
  781. if opt.help:
  782. _Usage()
  783. if cmd == 'help':
  784. _Help(args)
  785. if opt.version or cmd == 'version':
  786. _Version()
  787. if not cmd:
  788. _NotInstalled()
  789. if cmd == 'init' or cmd == 'gitc-init':
  790. if my_git:
  791. _SetDefaultsTo(my_git)
  792. try:
  793. _Init(args, gitc_init=(cmd == 'gitc-init'))
  794. except CloneFailure:
  795. path = os.path.join(repodir, S_repo)
  796. print("fatal: cloning the git-repo repository failed, will remove "
  797. "'%s' " % path, file=sys.stderr)
  798. shutil.rmtree(path, ignore_errors=True)
  799. sys.exit(1)
  800. repo_main, rel_repo_dir = _FindRepo()
  801. else:
  802. _NoCommands(cmd)
  803. if my_main:
  804. repo_main = my_main
  805. ver_str = '.'.join(map(str, VERSION))
  806. me = [sys.executable, repo_main,
  807. '--repo-dir=%s' % rel_repo_dir,
  808. '--wrapper-version=%s' % ver_str,
  809. '--wrapper-path=%s' % wrapper_path,
  810. '--']
  811. me.extend(orig_args)
  812. me.extend(extra_args)
  813. exec_command(me)
  814. print("fatal: unable to start %s" % repo_main, file=sys.stderr)
  815. sys.exit(148)
  816. if __name__ == '__main__':
  817. main(sys.argv[1:])