repo 30 KB

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