repo 28 KB

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