repo 28 KB

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