repo 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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 os
  10. import platform
  11. import subprocess
  12. import sys
  13. def exec_command(cmd):
  14. """Execute |cmd| or return None on failure."""
  15. try:
  16. if platform.system() == 'Windows':
  17. ret = subprocess.call(cmd)
  18. sys.exit(ret)
  19. else:
  20. os.execvp(cmd[0], cmd)
  21. except:
  22. pass
  23. def check_python_version():
  24. """Make sure the active Python version is recent enough."""
  25. def reexec(prog):
  26. exec_command([prog] + sys.argv)
  27. MIN_PYTHON_VERSION = (3, 6)
  28. ver = sys.version_info
  29. major = ver.major
  30. minor = ver.minor
  31. # Abort on very old Python 2 versions.
  32. if (major, minor) < (2, 7):
  33. print('repo: error: Your Python version is too old. '
  34. 'Please use Python {}.{} or newer instead.'.format(
  35. *MIN_PYTHON_VERSION), file=sys.stderr)
  36. sys.exit(1)
  37. # Try to re-exec the version specific Python 3 if needed.
  38. if (major, minor) < MIN_PYTHON_VERSION:
  39. # Python makes releases ~once a year, so try our min version +10 to help
  40. # bridge the gap. This is the fallback anyways so perf isn't critical.
  41. min_major, min_minor = MIN_PYTHON_VERSION
  42. for inc in range(0, 10):
  43. reexec('python{}.{}'.format(min_major, min_minor + inc))
  44. # Try the generic Python 3 wrapper, but only if it's new enough. We don't
  45. # want to go from (still supported) Python 2.7 to (unsupported) Python 3.5.
  46. try:
  47. proc = subprocess.Popen(
  48. ['python3', '-c', 'import sys; '
  49. 'print(sys.version_info.major, sys.version_info.minor)'],
  50. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  51. (output, _) = proc.communicate()
  52. python3_ver = tuple(int(x) for x in output.decode('utf-8').split())
  53. except (OSError, subprocess.CalledProcessError):
  54. python3_ver = None
  55. # The python3 version looks like it's new enough, so give it a try.
  56. if python3_ver and python3_ver >= MIN_PYTHON_VERSION:
  57. reexec('python3')
  58. # We're still here, so diagnose things for the user.
  59. if major < 3:
  60. print('repo: warning: Python 2 is no longer supported; '
  61. 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION),
  62. file=sys.stderr)
  63. else:
  64. print('repo: error: Python 3 version is too old; '
  65. 'Please use Python {}.{} or newer.'.format(*MIN_PYTHON_VERSION),
  66. file=sys.stderr)
  67. sys.exit(1)
  68. if __name__ == '__main__':
  69. # TODO(vapier): Enable this on Windows once we have Python 3 issues fixed.
  70. if platform.system() != 'Windows':
  71. check_python_version()
  72. # repo default configuration
  73. #
  74. import os
  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, 0)
  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. MIN_GIT_VERSION = (2, 10, 2) # minimum supported git version
  144. repodir = '.repo' # name of repo's private directory
  145. S_repo = 'repo' # special repo repository
  146. S_manifests = 'manifests' # special manifest repository
  147. REPO_MAIN = S_repo + '/main.py' # main script
  148. GITC_CONFIG_FILE = '/gitc/.config'
  149. GITC_FS_ROOT_DIR = '/gitc/manifest-rw/'
  150. import collections
  151. import errno
  152. import optparse
  153. import re
  154. import shutil
  155. import stat
  156. if sys.version_info[0] == 3:
  157. import urllib.request
  158. import urllib.error
  159. else:
  160. import imp
  161. import urllib2
  162. urllib = imp.new_module('urllib')
  163. urllib.request = urllib2
  164. urllib.error = urllib2
  165. home_dot_repo = os.path.expanduser('~/.repoconfig')
  166. gpg_dir = os.path.join(home_dot_repo, 'gnupg')
  167. extra_args = []
  168. init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
  169. # Logging
  170. group = init_optparse.add_option_group('Logging options')
  171. group.add_option('-q', '--quiet',
  172. dest="quiet", action="store_true", default=False,
  173. help="be quiet")
  174. # Manifest
  175. group = init_optparse.add_option_group('Manifest options')
  176. group.add_option('-u', '--manifest-url',
  177. dest='manifest_url',
  178. help='manifest repository location', metavar='URL')
  179. group.add_option('-b', '--manifest-branch',
  180. dest='manifest_branch',
  181. help='manifest branch or revision', metavar='REVISION')
  182. group.add_option('-m', '--manifest-name',
  183. dest='manifest_name',
  184. help='initial manifest file', metavar='NAME.xml')
  185. group.add_option('--current-branch',
  186. dest='current_branch_only', action='store_true',
  187. help='fetch only current manifest branch from server')
  188. group.add_option('--mirror',
  189. dest='mirror', action='store_true',
  190. help='create a replica of the remote repositories '
  191. 'rather than a client working directory')
  192. group.add_option('--reference',
  193. dest='reference',
  194. help='location of mirror directory', metavar='DIR')
  195. group.add_option('--dissociate',
  196. dest='dissociate', action='store_true',
  197. help='dissociate from reference mirrors after clone')
  198. group.add_option('--depth', type='int', default=None,
  199. dest='depth',
  200. help='create a shallow clone with given depth; see git clone')
  201. group.add_option('--partial-clone', action='store_true',
  202. dest='partial_clone',
  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. dest='clone_filter',
  207. help='filter for use with --partial-clone [default: %default]')
  208. group.add_option('--archive',
  209. dest='archive', action='store_true',
  210. help='checkout an archive instead of a git repository for '
  211. 'each project. See git archive.')
  212. group.add_option('--submodules',
  213. dest='submodules', action='store_true',
  214. help='sync any submodules associated with the manifest repo')
  215. group.add_option('-g', '--groups',
  216. dest='groups', default='default',
  217. help='restrict manifest projects to ones with specified '
  218. 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
  219. metavar='GROUP')
  220. group.add_option('-p', '--platform',
  221. dest='platform', default="auto",
  222. help='restrict manifest projects to ones with a specified '
  223. 'platform group [auto|all|none|linux|darwin|...]',
  224. metavar='PLATFORM')
  225. group.add_option('--no-clone-bundle',
  226. dest='no_clone_bundle', action='store_true',
  227. help='disable use of /clone.bundle on HTTP/HTTPS')
  228. group.add_option('--no-tags',
  229. dest='no_tags', action='store_true',
  230. help="don't fetch tags in the manifest")
  231. # Tool
  232. group = init_optparse.add_option_group('repo Version options')
  233. group.add_option('--repo-url',
  234. dest='repo_url',
  235. help='repo repository location ($REPO_URL)', metavar='URL')
  236. group.add_option('--repo-branch',
  237. dest='repo_branch',
  238. help='repo branch or revision ($REPO_REV)', metavar='REVISION')
  239. group.add_option('--no-repo-verify',
  240. dest='no_repo_verify', action='store_true',
  241. help='do not verify repo source code')
  242. # Other
  243. group = init_optparse.add_option_group('Other options')
  244. group.add_option('--config-name',
  245. dest='config_name', action="store_true", default=False,
  246. help='Always prompt for name/e-mail')
  247. def _GitcInitOptions(init_optparse_arg):
  248. init_optparse_arg.set_usage("repo gitc-init -u url -c client [options]")
  249. g = init_optparse_arg.add_option_group('GITC options')
  250. g.add_option('-f', '--manifest-file',
  251. dest='manifest_file',
  252. help='Optional manifest file to use for this GITC client.')
  253. g.add_option('-c', '--gitc-client',
  254. dest='gitc_client',
  255. help='The name of the gitc_client instance to create or modify.')
  256. _gitc_manifest_dir = None
  257. def get_gitc_manifest_dir():
  258. global _gitc_manifest_dir
  259. if _gitc_manifest_dir is None:
  260. _gitc_manifest_dir = ''
  261. try:
  262. with open(GITC_CONFIG_FILE, 'r') as gitc_config:
  263. for line in gitc_config:
  264. match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
  265. if match:
  266. _gitc_manifest_dir = match.group('gitc_manifest_dir')
  267. except IOError:
  268. pass
  269. return _gitc_manifest_dir
  270. def gitc_parse_clientdir(gitc_fs_path):
  271. """Parse a path in the GITC FS and return its client name.
  272. @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
  273. @returns: The GITC client name
  274. """
  275. if gitc_fs_path == GITC_FS_ROOT_DIR:
  276. return None
  277. if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
  278. manifest_dir = get_gitc_manifest_dir()
  279. if manifest_dir == '':
  280. return None
  281. if manifest_dir[-1] != '/':
  282. manifest_dir += '/'
  283. if gitc_fs_path == manifest_dir:
  284. return None
  285. if not gitc_fs_path.startswith(manifest_dir):
  286. return None
  287. return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
  288. return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]
  289. class CloneFailure(Exception):
  290. """Indicate the remote clone of repo itself failed.
  291. """
  292. def _Init(args, gitc_init=False):
  293. """Installs repo by cloning it over the network.
  294. """
  295. if gitc_init:
  296. _GitcInitOptions(init_optparse)
  297. opt, args = init_optparse.parse_args(args)
  298. if args:
  299. init_optparse.print_usage()
  300. sys.exit(1)
  301. url = opt.repo_url
  302. if not url:
  303. url = REPO_URL
  304. extra_args.append('--repo-url=%s' % url)
  305. branch = opt.repo_branch
  306. if not branch:
  307. branch = REPO_REV
  308. extra_args.append('--repo-branch=%s' % branch)
  309. if branch.startswith('refs/heads/'):
  310. branch = branch[len('refs/heads/'):]
  311. if branch.startswith('refs/'):
  312. print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
  313. raise CloneFailure()
  314. try:
  315. if gitc_init:
  316. gitc_manifest_dir = get_gitc_manifest_dir()
  317. if not gitc_manifest_dir:
  318. print('fatal: GITC filesystem is not available. Exiting...',
  319. file=sys.stderr)
  320. sys.exit(1)
  321. gitc_client = opt.gitc_client
  322. if not gitc_client:
  323. gitc_client = gitc_parse_clientdir(os.getcwd())
  324. if not gitc_client:
  325. print('fatal: GITC client (-c) is required.', file=sys.stderr)
  326. sys.exit(1)
  327. client_dir = os.path.join(gitc_manifest_dir, gitc_client)
  328. if not os.path.exists(client_dir):
  329. os.makedirs(client_dir)
  330. os.chdir(client_dir)
  331. if os.path.exists(repodir):
  332. # This GITC Client has already initialized repo so continue.
  333. return
  334. os.mkdir(repodir)
  335. except OSError as e:
  336. if e.errno != errno.EEXIST:
  337. print('fatal: cannot make %s directory: %s'
  338. % (repodir, e.strerror), file=sys.stderr)
  339. # Don't raise CloneFailure; that would delete the
  340. # name. Instead exit immediately.
  341. #
  342. sys.exit(1)
  343. _CheckGitVersion()
  344. try:
  345. if opt.no_repo_verify:
  346. do_verify = False
  347. else:
  348. if NeedSetupGnuPG():
  349. do_verify = SetupGnuPG(opt.quiet)
  350. else:
  351. do_verify = True
  352. dst = os.path.abspath(os.path.join(repodir, S_repo))
  353. _Clone(url, dst, opt.quiet, not opt.no_clone_bundle)
  354. if do_verify:
  355. rev = _Verify(dst, branch, opt.quiet)
  356. else:
  357. rev = 'refs/remotes/origin/%s^0' % branch
  358. _Checkout(dst, branch, rev, opt.quiet)
  359. if not os.path.isfile(os.path.join(dst, 'repo')):
  360. print("warning: '%s' does not look like a git-repo repository, is "
  361. "REPO_URL set correctly?" % url, file=sys.stderr)
  362. except CloneFailure:
  363. if opt.quiet:
  364. print('fatal: repo init failed; run without --quiet to see why',
  365. file=sys.stderr)
  366. raise
  367. # The git version info broken down into components for easy analysis.
  368. # Similar to Python's sys.version_info.
  369. GitVersion = collections.namedtuple(
  370. 'GitVersion', ('major', 'minor', 'micro', 'full'))
  371. def ParseGitVersion(ver_str=None):
  372. if ver_str is None:
  373. # Load the version ourselves.
  374. ver_str = _GetGitVersion()
  375. if not ver_str.startswith('git version '):
  376. return None
  377. full_version = ver_str[len('git version '):].strip()
  378. num_ver_str = full_version.split('-')[0]
  379. to_tuple = []
  380. for num_str in num_ver_str.split('.')[:3]:
  381. if num_str.isdigit():
  382. to_tuple.append(int(num_str))
  383. else:
  384. to_tuple.append(0)
  385. to_tuple.append(full_version)
  386. return GitVersion(*to_tuple)
  387. def _GetGitVersion():
  388. cmd = [GIT, '--version']
  389. try:
  390. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  391. except OSError as e:
  392. print(file=sys.stderr)
  393. print("fatal: '%s' is not available" % GIT, file=sys.stderr)
  394. print('fatal: %s' % e, file=sys.stderr)
  395. print(file=sys.stderr)
  396. print('Please make sure %s is installed and in your path.' % GIT,
  397. file=sys.stderr)
  398. raise
  399. ver_str = proc.stdout.read().strip()
  400. proc.stdout.close()
  401. proc.wait()
  402. return ver_str.decode('utf-8')
  403. def _CheckGitVersion():
  404. try:
  405. ver_act = ParseGitVersion()
  406. except OSError:
  407. raise CloneFailure()
  408. if ver_act is None:
  409. print('fatal: unable to detect git version', file=sys.stderr)
  410. raise CloneFailure()
  411. if ver_act < MIN_GIT_VERSION:
  412. need = '.'.join(map(str, MIN_GIT_VERSION))
  413. print('fatal: git %s or later required' % need, file=sys.stderr)
  414. raise CloneFailure()
  415. def NeedSetupGnuPG():
  416. if not os.path.isdir(home_dot_repo):
  417. return True
  418. kv = os.path.join(home_dot_repo, 'keyring-version')
  419. if not os.path.exists(kv):
  420. return True
  421. kv = open(kv).read()
  422. if not kv:
  423. return True
  424. kv = tuple(map(int, kv.split('.')))
  425. if kv < KEYRING_VERSION:
  426. return True
  427. return False
  428. def SetupGnuPG(quiet):
  429. try:
  430. os.mkdir(home_dot_repo)
  431. except OSError as e:
  432. if e.errno != errno.EEXIST:
  433. print('fatal: cannot make %s directory: %s'
  434. % (home_dot_repo, e.strerror), file=sys.stderr)
  435. sys.exit(1)
  436. try:
  437. os.mkdir(gpg_dir, stat.S_IRWXU)
  438. except OSError as e:
  439. if e.errno != errno.EEXIST:
  440. print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
  441. file=sys.stderr)
  442. sys.exit(1)
  443. env = os.environ.copy()
  444. try:
  445. env['GNUPGHOME'] = gpg_dir
  446. except UnicodeEncodeError:
  447. env['GNUPGHOME'] = gpg_dir.encode()
  448. cmd = ['gpg', '--import']
  449. try:
  450. proc = subprocess.Popen(cmd,
  451. env=env,
  452. stdin=subprocess.PIPE)
  453. except OSError as e:
  454. if not quiet:
  455. print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
  456. print('warning: Installing it is strongly encouraged.', file=sys.stderr)
  457. print(file=sys.stderr)
  458. return False
  459. proc.stdin.write(MAINTAINER_KEYS.encode('utf-8'))
  460. proc.stdin.close()
  461. if proc.wait() != 0:
  462. print('fatal: registering repo maintainer keys failed', file=sys.stderr)
  463. sys.exit(1)
  464. print()
  465. with open(os.path.join(home_dot_repo, 'keyring-version'), 'w') as fd:
  466. fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
  467. return True
  468. def _SetConfig(local, name, value):
  469. """Set a git configuration option to the specified value.
  470. """
  471. cmd = [GIT, 'config', name, value]
  472. if subprocess.Popen(cmd, cwd=local).wait() != 0:
  473. raise CloneFailure()
  474. def _InitHttp():
  475. handlers = []
  476. mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  477. try:
  478. import netrc
  479. n = netrc.netrc()
  480. for host in n.hosts:
  481. p = n.hosts[host]
  482. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  483. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  484. except:
  485. pass
  486. handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
  487. handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
  488. if 'http_proxy' in os.environ:
  489. url = os.environ['http_proxy']
  490. handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
  491. if 'REPO_CURL_VERBOSE' in os.environ:
  492. handlers.append(urllib.request.HTTPHandler(debuglevel=1))
  493. handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
  494. urllib.request.install_opener(urllib.request.build_opener(*handlers))
  495. def _Fetch(url, local, src, quiet):
  496. if not quiet:
  497. print('Get %s' % url, file=sys.stderr)
  498. cmd = [GIT, 'fetch']
  499. if quiet:
  500. cmd.append('--quiet')
  501. err = subprocess.PIPE
  502. else:
  503. err = None
  504. cmd.append(src)
  505. cmd.append('+refs/heads/*:refs/remotes/origin/*')
  506. cmd.append('+refs/tags/*:refs/tags/*')
  507. proc = subprocess.Popen(cmd, cwd=local, stderr=err)
  508. if err:
  509. proc.stderr.read()
  510. proc.stderr.close()
  511. if proc.wait() != 0:
  512. raise CloneFailure()
  513. def _DownloadBundle(url, local, quiet):
  514. if not url.endswith('/'):
  515. url += '/'
  516. url += 'clone.bundle'
  517. proc = subprocess.Popen(
  518. [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
  519. cwd=local,
  520. stdout=subprocess.PIPE)
  521. for line in proc.stdout:
  522. line = line.decode('utf-8')
  523. m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
  524. if m:
  525. new_url = m.group(1)
  526. old_url = m.group(2)
  527. if url.startswith(old_url):
  528. url = new_url + url[len(old_url):]
  529. break
  530. proc.stdout.close()
  531. proc.wait()
  532. if not url.startswith('http:') and not url.startswith('https:'):
  533. return False
  534. dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
  535. try:
  536. try:
  537. r = urllib.request.urlopen(url)
  538. except urllib.error.HTTPError as e:
  539. if e.code in [401, 403, 404, 501]:
  540. return False
  541. print('fatal: Cannot get %s' % url, file=sys.stderr)
  542. print('fatal: HTTP error %s' % e.code, file=sys.stderr)
  543. raise CloneFailure()
  544. except urllib.error.URLError as e:
  545. print('fatal: Cannot get %s' % url, file=sys.stderr)
  546. print('fatal: error %s' % e.reason, file=sys.stderr)
  547. raise CloneFailure()
  548. try:
  549. if not quiet:
  550. print('Get %s' % url, file=sys.stderr)
  551. while True:
  552. buf = r.read(8192)
  553. if not buf:
  554. return True
  555. dest.write(buf)
  556. finally:
  557. r.close()
  558. finally:
  559. dest.close()
  560. def _ImportBundle(local):
  561. path = os.path.join(local, '.git', 'clone.bundle')
  562. try:
  563. _Fetch(local, local, path, True)
  564. finally:
  565. os.remove(path)
  566. def _Clone(url, local, quiet, clone_bundle):
  567. """Clones a git repository to a new subdirectory of repodir
  568. """
  569. try:
  570. os.mkdir(local)
  571. except OSError as e:
  572. print('fatal: cannot make %s directory: %s' % (local, e.strerror),
  573. file=sys.stderr)
  574. raise CloneFailure()
  575. cmd = [GIT, 'init', '--quiet']
  576. try:
  577. proc = subprocess.Popen(cmd, cwd=local)
  578. except OSError as e:
  579. print(file=sys.stderr)
  580. print("fatal: '%s' is not available" % GIT, file=sys.stderr)
  581. print('fatal: %s' % e, file=sys.stderr)
  582. print(file=sys.stderr)
  583. print('Please make sure %s is installed and in your path.' % GIT,
  584. file=sys.stderr)
  585. raise CloneFailure()
  586. if proc.wait() != 0:
  587. print('fatal: could not create %s' % local, file=sys.stderr)
  588. raise CloneFailure()
  589. _InitHttp()
  590. _SetConfig(local, 'remote.origin.url', url)
  591. _SetConfig(local,
  592. 'remote.origin.fetch',
  593. '+refs/heads/*:refs/remotes/origin/*')
  594. if clone_bundle and _DownloadBundle(url, local, quiet):
  595. _ImportBundle(local)
  596. _Fetch(url, local, 'origin', quiet)
  597. def _Verify(cwd, branch, quiet):
  598. """Verify the branch has been signed by a tag.
  599. """
  600. cmd = [GIT, 'describe', 'origin/%s' % branch]
  601. proc = subprocess.Popen(cmd,
  602. stdout=subprocess.PIPE,
  603. stderr=subprocess.PIPE,
  604. cwd=cwd)
  605. cur = proc.stdout.read().strip().decode('utf-8')
  606. proc.stdout.close()
  607. proc.stderr.read()
  608. proc.stderr.close()
  609. if proc.wait() != 0 or not cur:
  610. print(file=sys.stderr)
  611. print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
  612. raise CloneFailure()
  613. m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
  614. if m:
  615. cur = m.group(1)
  616. if not quiet:
  617. print(file=sys.stderr)
  618. print("info: Ignoring branch '%s'; using tagged release '%s'"
  619. % (branch, cur), file=sys.stderr)
  620. print(file=sys.stderr)
  621. env = os.environ.copy()
  622. try:
  623. env['GNUPGHOME'] = gpg_dir
  624. except UnicodeEncodeError:
  625. env['GNUPGHOME'] = gpg_dir.encode()
  626. cmd = [GIT, 'tag', '-v', cur]
  627. proc = subprocess.Popen(cmd,
  628. stdout=subprocess.PIPE,
  629. stderr=subprocess.PIPE,
  630. cwd=cwd,
  631. env=env)
  632. out = proc.stdout.read().decode('utf-8')
  633. proc.stdout.close()
  634. err = proc.stderr.read().decode('utf-8')
  635. proc.stderr.close()
  636. if proc.wait() != 0:
  637. print(file=sys.stderr)
  638. print(out, file=sys.stderr)
  639. print(err, file=sys.stderr)
  640. print(file=sys.stderr)
  641. raise CloneFailure()
  642. return '%s^0' % cur
  643. def _Checkout(cwd, branch, rev, quiet):
  644. """Checkout an upstream branch into the repository and track it.
  645. """
  646. cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
  647. if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
  648. raise CloneFailure()
  649. _SetConfig(cwd, 'branch.default.remote', 'origin')
  650. _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
  651. cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
  652. if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
  653. raise CloneFailure()
  654. cmd = [GIT, 'read-tree', '--reset', '-u']
  655. if not quiet:
  656. cmd.append('-v')
  657. cmd.append('HEAD')
  658. if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
  659. raise CloneFailure()
  660. def _FindRepo():
  661. """Look for a repo installation, starting at the current directory.
  662. """
  663. curdir = os.getcwd()
  664. repo = None
  665. olddir = None
  666. while curdir != '/' \
  667. and curdir != olddir \
  668. and not repo:
  669. repo = os.path.join(curdir, repodir, REPO_MAIN)
  670. if not os.path.isfile(repo):
  671. repo = None
  672. olddir = curdir
  673. curdir = os.path.dirname(curdir)
  674. return (repo, os.path.join(curdir, repodir))
  675. class _Options(object):
  676. help = 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 not a.startswith('-'):
  686. cmd = a
  687. arg = args[i + 1:]
  688. break
  689. return cmd, opt, arg
  690. def _Usage():
  691. gitc_usage = ""
  692. if get_gitc_manifest_dir():
  693. gitc_usage = " gitc-init Initialize a GITC Client.\n"
  694. print(
  695. """usage: repo COMMAND [ARGS]
  696. repo is not yet installed. Use "repo init" to install it here.
  697. The most commonly used repo commands are:
  698. init Install repo in the current working directory
  699. """ + gitc_usage +
  700. """ help Display detailed help on a command
  701. For access to the full online help, install repo ("repo init").
  702. """)
  703. sys.exit(0)
  704. def _Help(args):
  705. if args:
  706. if args[0] == 'init':
  707. init_optparse.print_help()
  708. sys.exit(0)
  709. elif args[0] == 'gitc-init':
  710. _GitcInitOptions(init_optparse)
  711. init_optparse.print_help()
  712. sys.exit(0)
  713. else:
  714. print("error: '%s' is not a bootstrap command.\n"
  715. ' For access to online help, install repo ("repo init").'
  716. % args[0], file=sys.stderr)
  717. else:
  718. _Usage()
  719. sys.exit(1)
  720. def _NotInstalled():
  721. print('error: repo is not installed. Use "repo init" to install it here.',
  722. file=sys.stderr)
  723. sys.exit(1)
  724. def _NoCommands(cmd):
  725. print("""error: command '%s' requires repo to be installed first.
  726. Use "repo init" to install it here.""" % cmd, file=sys.stderr)
  727. sys.exit(1)
  728. def _RunSelf(wrapper_path):
  729. my_dir = os.path.dirname(wrapper_path)
  730. my_main = os.path.join(my_dir, 'main.py')
  731. my_git = os.path.join(my_dir, '.git')
  732. if os.path.isfile(my_main) and os.path.isdir(my_git):
  733. for name in ['git_config.py',
  734. 'project.py',
  735. 'subcmds']:
  736. if not os.path.exists(os.path.join(my_dir, name)):
  737. return None, None
  738. return my_main, my_git
  739. return None, None
  740. def _SetDefaultsTo(gitdir):
  741. global REPO_URL
  742. global REPO_REV
  743. REPO_URL = gitdir
  744. proc = subprocess.Popen([GIT,
  745. '--git-dir=%s' % gitdir,
  746. 'symbolic-ref',
  747. 'HEAD'],
  748. stdout=subprocess.PIPE,
  749. stderr=subprocess.PIPE)
  750. REPO_REV = proc.stdout.read().strip().decode('utf-8')
  751. proc.stdout.close()
  752. proc.stderr.read()
  753. proc.stderr.close()
  754. if proc.wait() != 0:
  755. print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
  756. sys.exit(1)
  757. def main(orig_args):
  758. cmd, opt, args = _ParseArguments(orig_args)
  759. repo_main, rel_repo_dir = None, None
  760. # Don't use the local repo copy, make sure to switch to the gitc client first.
  761. if cmd != 'gitc-init':
  762. repo_main, rel_repo_dir = _FindRepo()
  763. wrapper_path = os.path.abspath(__file__)
  764. my_main, my_git = _RunSelf(wrapper_path)
  765. cwd = os.getcwd()
  766. if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
  767. print('error: repo cannot be used in the GITC local manifest directory.'
  768. '\nIf you want to work on this GITC client please rerun this '
  769. 'command from the corresponding client under /gitc/',
  770. file=sys.stderr)
  771. sys.exit(1)
  772. if not repo_main:
  773. if opt.help:
  774. _Usage()
  775. if cmd == 'help':
  776. _Help(args)
  777. if not cmd:
  778. _NotInstalled()
  779. if cmd == 'init' or cmd == 'gitc-init':
  780. if my_git:
  781. _SetDefaultsTo(my_git)
  782. try:
  783. _Init(args, gitc_init=(cmd == 'gitc-init'))
  784. except CloneFailure:
  785. path = os.path.join(repodir, S_repo)
  786. print("fatal: cloning the git-repo repository failed, will remove "
  787. "'%s' " % path, file=sys.stderr)
  788. shutil.rmtree(path, ignore_errors=True)
  789. sys.exit(1)
  790. repo_main, rel_repo_dir = _FindRepo()
  791. else:
  792. _NoCommands(cmd)
  793. if my_main:
  794. repo_main = my_main
  795. ver_str = '.'.join(map(str, VERSION))
  796. me = [sys.executable, repo_main,
  797. '--repo-dir=%s' % rel_repo_dir,
  798. '--wrapper-version=%s' % ver_str,
  799. '--wrapper-path=%s' % wrapper_path,
  800. '--']
  801. me.extend(orig_args)
  802. me.extend(extra_args)
  803. exec_command(me)
  804. print("fatal: unable to start %s" % repo_main, file=sys.stderr)
  805. sys.exit(148)
  806. if __name__ == '__main__':
  807. main(sys.argv[1:])