repo 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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. # 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. _gitc_manifest_dir = None
  248. def get_gitc_manifest_dir():
  249. global _gitc_manifest_dir
  250. if _gitc_manifest_dir is None:
  251. _gitc_manifest_dir = ''
  252. try:
  253. with open(GITC_CONFIG_FILE, 'r') as gitc_config:
  254. for line in gitc_config:
  255. match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
  256. if match:
  257. _gitc_manifest_dir = match.group('gitc_manifest_dir')
  258. except IOError:
  259. pass
  260. return _gitc_manifest_dir
  261. def gitc_parse_clientdir(gitc_fs_path):
  262. """Parse a path in the GITC FS and return its client name.
  263. @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
  264. @returns: The GITC client name
  265. """
  266. if gitc_fs_path == GITC_FS_ROOT_DIR:
  267. return None
  268. if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
  269. manifest_dir = get_gitc_manifest_dir()
  270. if manifest_dir == '':
  271. return None
  272. if manifest_dir[-1] != '/':
  273. manifest_dir += '/'
  274. if gitc_fs_path == manifest_dir:
  275. return None
  276. if not gitc_fs_path.startswith(manifest_dir):
  277. return None
  278. return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
  279. return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]
  280. class CloneFailure(Exception):
  281. """Indicate the remote clone of repo itself failed.
  282. """
  283. def _Init(args, gitc_init=False):
  284. """Installs repo by cloning it over the network.
  285. """
  286. if gitc_init:
  287. _GitcInitOptions(init_optparse)
  288. opt, args = init_optparse.parse_args(args)
  289. if args:
  290. init_optparse.print_usage()
  291. sys.exit(1)
  292. url = opt.repo_url
  293. if not url:
  294. url = REPO_URL
  295. extra_args.append('--repo-url=%s' % url)
  296. branch = opt.repo_branch
  297. if not branch:
  298. branch = REPO_REV
  299. extra_args.append('--repo-branch=%s' % branch)
  300. if branch.startswith('refs/heads/'):
  301. branch = branch[len('refs/heads/'):]
  302. if branch.startswith('refs/'):
  303. print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
  304. raise CloneFailure()
  305. try:
  306. if gitc_init:
  307. gitc_manifest_dir = get_gitc_manifest_dir()
  308. if not gitc_manifest_dir:
  309. print('fatal: GITC filesystem is not available. Exiting...',
  310. file=sys.stderr)
  311. sys.exit(1)
  312. gitc_client = opt.gitc_client
  313. if not gitc_client:
  314. gitc_client = gitc_parse_clientdir(os.getcwd())
  315. if not gitc_client:
  316. print('fatal: GITC client (-c) is required.', file=sys.stderr)
  317. sys.exit(1)
  318. client_dir = os.path.join(gitc_manifest_dir, gitc_client)
  319. if not os.path.exists(client_dir):
  320. os.makedirs(client_dir)
  321. os.chdir(client_dir)
  322. if os.path.exists(repodir):
  323. # This GITC Client has already initialized repo so continue.
  324. return
  325. os.mkdir(repodir)
  326. except OSError as e:
  327. if e.errno != errno.EEXIST:
  328. print('fatal: cannot make %s directory: %s'
  329. % (repodir, e.strerror), file=sys.stderr)
  330. # Don't raise CloneFailure; that would delete the
  331. # name. Instead exit immediately.
  332. #
  333. sys.exit(1)
  334. _CheckGitVersion()
  335. try:
  336. if opt.no_repo_verify:
  337. do_verify = False
  338. else:
  339. if NeedSetupGnuPG():
  340. do_verify = SetupGnuPG(opt.quiet)
  341. else:
  342. do_verify = True
  343. dst = os.path.abspath(os.path.join(repodir, S_repo))
  344. _Clone(url, dst, opt.quiet, not opt.no_clone_bundle)
  345. if do_verify:
  346. rev = _Verify(dst, branch, opt.quiet)
  347. else:
  348. rev = 'refs/remotes/origin/%s^0' % branch
  349. _Checkout(dst, branch, rev, opt.quiet)
  350. if not os.path.isfile(os.path.join(dst, 'repo')):
  351. print("warning: '%s' does not look like a git-repo repository, is "
  352. "REPO_URL set correctly?" % url, file=sys.stderr)
  353. except CloneFailure:
  354. if opt.quiet:
  355. print('fatal: repo init failed; run without --quiet to see why',
  356. file=sys.stderr)
  357. raise
  358. # The git version info broken down into components for easy analysis.
  359. # Similar to Python's sys.version_info.
  360. GitVersion = collections.namedtuple(
  361. 'GitVersion', ('major', 'minor', 'micro', 'full'))
  362. def ParseGitVersion(ver_str=None):
  363. if ver_str is None:
  364. # Load the version ourselves.
  365. ver_str = _GetGitVersion()
  366. if not ver_str.startswith('git version '):
  367. return None
  368. full_version = ver_str[len('git version '):].strip()
  369. num_ver_str = full_version.split('-')[0]
  370. to_tuple = []
  371. for num_str in num_ver_str.split('.')[:3]:
  372. if num_str.isdigit():
  373. to_tuple.append(int(num_str))
  374. else:
  375. to_tuple.append(0)
  376. to_tuple.append(full_version)
  377. return GitVersion(*to_tuple)
  378. def _GetGitVersion():
  379. cmd = [GIT, '--version']
  380. try:
  381. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  382. except OSError as e:
  383. print(file=sys.stderr)
  384. print("fatal: '%s' is not available" % GIT, file=sys.stderr)
  385. print('fatal: %s' % e, file=sys.stderr)
  386. print(file=sys.stderr)
  387. print('Please make sure %s is installed and in your path.' % GIT,
  388. file=sys.stderr)
  389. raise
  390. ver_str = proc.stdout.read().strip()
  391. proc.stdout.close()
  392. proc.wait()
  393. return ver_str.decode('utf-8')
  394. def _CheckGitVersion():
  395. try:
  396. ver_act = ParseGitVersion()
  397. except OSError:
  398. raise CloneFailure()
  399. if ver_act is None:
  400. print('fatal: unable to detect git version', file=sys.stderr)
  401. raise CloneFailure()
  402. if ver_act < MIN_GIT_VERSION:
  403. need = '.'.join(map(str, MIN_GIT_VERSION))
  404. print('fatal: git %s or later required' % need, file=sys.stderr)
  405. raise CloneFailure()
  406. def NeedSetupGnuPG():
  407. if not os.path.isdir(home_dot_repo):
  408. return True
  409. kv = os.path.join(home_dot_repo, 'keyring-version')
  410. if not os.path.exists(kv):
  411. return True
  412. kv = open(kv).read()
  413. if not kv:
  414. return True
  415. kv = tuple(map(int, kv.split('.')))
  416. if kv < KEYRING_VERSION:
  417. return True
  418. return False
  419. def SetupGnuPG(quiet):
  420. try:
  421. os.mkdir(home_dot_repo)
  422. except OSError as e:
  423. if e.errno != errno.EEXIST:
  424. print('fatal: cannot make %s directory: %s'
  425. % (home_dot_repo, e.strerror), file=sys.stderr)
  426. sys.exit(1)
  427. try:
  428. os.mkdir(gpg_dir, stat.S_IRWXU)
  429. except OSError as e:
  430. if e.errno != errno.EEXIST:
  431. print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
  432. file=sys.stderr)
  433. sys.exit(1)
  434. env = os.environ.copy()
  435. try:
  436. env['GNUPGHOME'] = gpg_dir
  437. except UnicodeEncodeError:
  438. env['GNUPGHOME'] = gpg_dir.encode()
  439. cmd = ['gpg', '--import']
  440. try:
  441. proc = subprocess.Popen(cmd,
  442. env=env,
  443. stdin=subprocess.PIPE)
  444. except OSError as e:
  445. if not quiet:
  446. print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
  447. print('warning: Installing it is strongly encouraged.', file=sys.stderr)
  448. print(file=sys.stderr)
  449. return False
  450. proc.stdin.write(MAINTAINER_KEYS.encode('utf-8'))
  451. proc.stdin.close()
  452. if proc.wait() != 0:
  453. print('fatal: registering repo maintainer keys failed', file=sys.stderr)
  454. sys.exit(1)
  455. print()
  456. with open(os.path.join(home_dot_repo, 'keyring-version'), 'w') as fd:
  457. fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
  458. return True
  459. def _SetConfig(local, name, value):
  460. """Set a git configuration option to the specified value.
  461. """
  462. cmd = [GIT, 'config', name, value]
  463. if subprocess.Popen(cmd, cwd=local).wait() != 0:
  464. raise CloneFailure()
  465. def _InitHttp():
  466. handlers = []
  467. mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  468. try:
  469. import netrc
  470. n = netrc.netrc()
  471. for host in n.hosts:
  472. p = n.hosts[host]
  473. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  474. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  475. except:
  476. pass
  477. handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
  478. handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
  479. if 'http_proxy' in os.environ:
  480. url = os.environ['http_proxy']
  481. handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
  482. if 'REPO_CURL_VERBOSE' in os.environ:
  483. handlers.append(urllib.request.HTTPHandler(debuglevel=1))
  484. handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
  485. urllib.request.install_opener(urllib.request.build_opener(*handlers))
  486. def _Fetch(url, local, src, quiet):
  487. if not quiet:
  488. print('Get %s' % url, file=sys.stderr)
  489. cmd = [GIT, 'fetch']
  490. if quiet:
  491. cmd.append('--quiet')
  492. err = subprocess.PIPE
  493. else:
  494. err = None
  495. cmd.append(src)
  496. cmd.append('+refs/heads/*:refs/remotes/origin/*')
  497. cmd.append('+refs/tags/*:refs/tags/*')
  498. proc = subprocess.Popen(cmd, cwd=local, stderr=err)
  499. if err:
  500. proc.stderr.read()
  501. proc.stderr.close()
  502. if proc.wait() != 0:
  503. raise CloneFailure()
  504. def _DownloadBundle(url, local, quiet):
  505. if not url.endswith('/'):
  506. url += '/'
  507. url += 'clone.bundle'
  508. proc = subprocess.Popen(
  509. [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
  510. cwd=local,
  511. stdout=subprocess.PIPE)
  512. for line in proc.stdout:
  513. line = line.decode('utf-8')
  514. m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
  515. if m:
  516. new_url = m.group(1)
  517. old_url = m.group(2)
  518. if url.startswith(old_url):
  519. url = new_url + url[len(old_url):]
  520. break
  521. proc.stdout.close()
  522. proc.wait()
  523. if not url.startswith('http:') and not url.startswith('https:'):
  524. return False
  525. dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
  526. try:
  527. try:
  528. r = urllib.request.urlopen(url)
  529. except urllib.error.HTTPError as e:
  530. if e.code in [401, 403, 404, 501]:
  531. return False
  532. print('fatal: Cannot get %s' % url, file=sys.stderr)
  533. print('fatal: HTTP error %s' % e.code, file=sys.stderr)
  534. raise CloneFailure()
  535. except urllib.error.URLError as e:
  536. print('fatal: Cannot get %s' % url, file=sys.stderr)
  537. print('fatal: error %s' % e.reason, file=sys.stderr)
  538. raise CloneFailure()
  539. try:
  540. if not quiet:
  541. print('Get %s' % url, file=sys.stderr)
  542. while True:
  543. buf = r.read(8192)
  544. if not buf:
  545. return True
  546. dest.write(buf)
  547. finally:
  548. r.close()
  549. finally:
  550. dest.close()
  551. def _ImportBundle(local):
  552. path = os.path.join(local, '.git', 'clone.bundle')
  553. try:
  554. _Fetch(local, local, path, True)
  555. finally:
  556. os.remove(path)
  557. def _Clone(url, local, quiet, clone_bundle):
  558. """Clones a git repository to a new subdirectory of repodir
  559. """
  560. try:
  561. os.mkdir(local)
  562. except OSError as e:
  563. print('fatal: cannot make %s directory: %s' % (local, e.strerror),
  564. file=sys.stderr)
  565. raise CloneFailure()
  566. cmd = [GIT, 'init', '--quiet']
  567. try:
  568. proc = subprocess.Popen(cmd, cwd=local)
  569. except OSError as e:
  570. print(file=sys.stderr)
  571. print("fatal: '%s' is not available" % GIT, file=sys.stderr)
  572. print('fatal: %s' % e, file=sys.stderr)
  573. print(file=sys.stderr)
  574. print('Please make sure %s is installed and in your path.' % GIT,
  575. file=sys.stderr)
  576. raise CloneFailure()
  577. if proc.wait() != 0:
  578. print('fatal: could not create %s' % local, file=sys.stderr)
  579. raise CloneFailure()
  580. _InitHttp()
  581. _SetConfig(local, 'remote.origin.url', url)
  582. _SetConfig(local,
  583. 'remote.origin.fetch',
  584. '+refs/heads/*:refs/remotes/origin/*')
  585. if clone_bundle and _DownloadBundle(url, local, quiet):
  586. _ImportBundle(local)
  587. _Fetch(url, local, 'origin', quiet)
  588. def _Verify(cwd, branch, quiet):
  589. """Verify the branch has been signed by a tag.
  590. """
  591. cmd = [GIT, 'describe', 'origin/%s' % branch]
  592. proc = subprocess.Popen(cmd,
  593. stdout=subprocess.PIPE,
  594. stderr=subprocess.PIPE,
  595. cwd=cwd)
  596. cur = proc.stdout.read().strip().decode('utf-8')
  597. proc.stdout.close()
  598. proc.stderr.read()
  599. proc.stderr.close()
  600. if proc.wait() != 0 or not cur:
  601. print(file=sys.stderr)
  602. print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
  603. raise CloneFailure()
  604. m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
  605. if m:
  606. cur = m.group(1)
  607. if not quiet:
  608. print(file=sys.stderr)
  609. print("info: Ignoring branch '%s'; using tagged release '%s'"
  610. % (branch, cur), file=sys.stderr)
  611. print(file=sys.stderr)
  612. env = os.environ.copy()
  613. try:
  614. env['GNUPGHOME'] = gpg_dir
  615. except UnicodeEncodeError:
  616. env['GNUPGHOME'] = gpg_dir.encode()
  617. cmd = [GIT, 'tag', '-v', cur]
  618. proc = subprocess.Popen(cmd,
  619. stdout=subprocess.PIPE,
  620. stderr=subprocess.PIPE,
  621. cwd=cwd,
  622. env=env)
  623. out = proc.stdout.read().decode('utf-8')
  624. proc.stdout.close()
  625. err = proc.stderr.read().decode('utf-8')
  626. proc.stderr.close()
  627. if proc.wait() != 0:
  628. print(file=sys.stderr)
  629. print(out, file=sys.stderr)
  630. print(err, file=sys.stderr)
  631. print(file=sys.stderr)
  632. raise CloneFailure()
  633. return '%s^0' % cur
  634. def _Checkout(cwd, branch, rev, quiet):
  635. """Checkout an upstream branch into the repository and track it.
  636. """
  637. cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
  638. if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
  639. raise CloneFailure()
  640. _SetConfig(cwd, 'branch.default.remote', 'origin')
  641. _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
  642. cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
  643. if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
  644. raise CloneFailure()
  645. cmd = [GIT, 'read-tree', '--reset', '-u']
  646. if not quiet:
  647. cmd.append('-v')
  648. cmd.append('HEAD')
  649. if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
  650. raise CloneFailure()
  651. def _FindRepo():
  652. """Look for a repo installation, starting at the current directory.
  653. """
  654. curdir = os.getcwd()
  655. repo = None
  656. olddir = None
  657. while curdir != '/' \
  658. and curdir != olddir \
  659. and not repo:
  660. repo = os.path.join(curdir, repodir, REPO_MAIN)
  661. if not os.path.isfile(repo):
  662. repo = None
  663. olddir = curdir
  664. curdir = os.path.dirname(curdir)
  665. return (repo, os.path.join(curdir, repodir))
  666. class _Options(object):
  667. help = False
  668. def _ParseArguments(args):
  669. cmd = None
  670. opt = _Options()
  671. arg = []
  672. for i in range(len(args)):
  673. a = args[i]
  674. if a == '-h' or a == '--help':
  675. opt.help = True
  676. elif not a.startswith('-'):
  677. cmd = a
  678. arg = args[i + 1:]
  679. break
  680. return cmd, opt, arg
  681. def _Usage():
  682. gitc_usage = ""
  683. if get_gitc_manifest_dir():
  684. gitc_usage = " gitc-init Initialize a GITC Client.\n"
  685. print(
  686. """usage: repo COMMAND [ARGS]
  687. repo is not yet installed. Use "repo init" to install it here.
  688. The most commonly used repo commands are:
  689. init Install repo in the current working directory
  690. """ + gitc_usage +
  691. """ help Display detailed help on a command
  692. For access to the full online help, install repo ("repo init").
  693. """)
  694. sys.exit(0)
  695. def _Help(args):
  696. if args:
  697. if args[0] == 'init':
  698. init_optparse.print_help()
  699. sys.exit(0)
  700. elif args[0] == 'gitc-init':
  701. _GitcInitOptions(init_optparse)
  702. init_optparse.print_help()
  703. sys.exit(0)
  704. else:
  705. print("error: '%s' is not a bootstrap command.\n"
  706. ' For access to online help, install repo ("repo init").'
  707. % args[0], file=sys.stderr)
  708. else:
  709. _Usage()
  710. sys.exit(1)
  711. def _NotInstalled():
  712. print('error: repo is not installed. Use "repo init" to install it here.',
  713. file=sys.stderr)
  714. sys.exit(1)
  715. def _NoCommands(cmd):
  716. print("""error: command '%s' requires repo to be installed first.
  717. Use "repo init" to install it here.""" % cmd, file=sys.stderr)
  718. sys.exit(1)
  719. def _RunSelf(wrapper_path):
  720. my_dir = os.path.dirname(wrapper_path)
  721. my_main = os.path.join(my_dir, 'main.py')
  722. my_git = os.path.join(my_dir, '.git')
  723. if os.path.isfile(my_main) and os.path.isdir(my_git):
  724. for name in ['git_config.py',
  725. 'project.py',
  726. 'subcmds']:
  727. if not os.path.exists(os.path.join(my_dir, name)):
  728. return None, None
  729. return my_main, my_git
  730. return None, None
  731. def _SetDefaultsTo(gitdir):
  732. global REPO_URL
  733. global REPO_REV
  734. REPO_URL = gitdir
  735. proc = subprocess.Popen([GIT,
  736. '--git-dir=%s' % gitdir,
  737. 'symbolic-ref',
  738. 'HEAD'],
  739. stdout=subprocess.PIPE,
  740. stderr=subprocess.PIPE)
  741. REPO_REV = proc.stdout.read().strip().decode('utf-8')
  742. proc.stdout.close()
  743. proc.stderr.read()
  744. proc.stderr.close()
  745. if proc.wait() != 0:
  746. print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
  747. sys.exit(1)
  748. def main(orig_args):
  749. cmd, opt, args = _ParseArguments(orig_args)
  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 not cmd:
  770. _NotInstalled()
  771. if cmd == 'init' or cmd == 'gitc-init':
  772. if my_git:
  773. _SetDefaultsTo(my_git)
  774. try:
  775. _Init(args, gitc_init=(cmd == 'gitc-init'))
  776. except CloneFailure:
  777. path = os.path.join(repodir, S_repo)
  778. print("fatal: cloning the git-repo repository failed, will remove "
  779. "'%s' " % path, file=sys.stderr)
  780. shutil.rmtree(path, ignore_errors=True)
  781. sys.exit(1)
  782. repo_main, rel_repo_dir = _FindRepo()
  783. else:
  784. _NoCommands(cmd)
  785. if my_main:
  786. repo_main = my_main
  787. ver_str = '.'.join(map(str, VERSION))
  788. me = [sys.executable, repo_main,
  789. '--repo-dir=%s' % rel_repo_dir,
  790. '--wrapper-version=%s' % ver_str,
  791. '--wrapper-path=%s' % wrapper_path,
  792. '--']
  793. me.extend(orig_args)
  794. me.extend(extra_args)
  795. exec_command(me)
  796. print("fatal: unable to start %s" % repo_main, file=sys.stderr)
  797. sys.exit(148)
  798. if __name__ == '__main__':
  799. main(sys.argv[1:])