repo 29 KB

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