repo 27 KB

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