repo 28 KB

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