repo 27 KB

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