repo 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. #!/bin/sh
  2. ## repo default configuration
  3. ##
  4. REPO_URL='https://gerrit.googlesource.com/git-repo'
  5. REPO_REV='stable'
  6. # Copyright (C) 2008 Google Inc.
  7. #
  8. # Licensed under the Apache License, Version 2.0 (the "License");
  9. # you may not use this file except in compliance with the License.
  10. # You may obtain a copy of the License at
  11. #
  12. # http://www.apache.org/licenses/LICENSE-2.0
  13. #
  14. # Unless required by applicable law or agreed to in writing, software
  15. # distributed under the License is distributed on an "AS IS" BASIS,
  16. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. # See the License for the specific language governing permissions and
  18. # limitations under the License.
  19. magic='--calling-python-from-/bin/sh--'
  20. """exec" python -E "$0" "$@" """#$magic"
  21. if __name__ == '__main__':
  22. import sys
  23. if sys.argv[-1] == '#%s' % magic:
  24. del sys.argv[-1]
  25. del magic
  26. # increment this whenever we make important changes to this script
  27. VERSION = (1, 19)
  28. # increment this if the MAINTAINER_KEYS block is modified
  29. KEYRING_VERSION = (1,1)
  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. e0PLlH5avCqihGRhpoqDRsmpzSHzJIxtoeb+GgGEX8KkUsVAhbQpUmVwbyBNYWlu
  43. dGFpbmVyIDxyZXBvQGFuZHJvaWQua2VybmVsLm9yZz6IYAQTEQIAIAUCSPe6AQIb
  44. AwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEBZTDV6S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W90STZa65RK7IaYpC8TB35JTBEbrrNCp
  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. mQENBFBiLPwBCACvISTASOgFXwADw2GYRH2I2z9RvYkYoZ6ThTTNlMXbbYYKO2Wo
  75. a9LQDNW0TbCEekg5UKk0FD13XOdWaqUt4Gtuvq9c43GRSjMO6NXH+0BjcQ8vUtY2
  76. /W4CYUevwdo4nQ1+1zsOCu1XYe/CReXq0fdugv3hgmRmh3sz1soo37Q44W2frxxg
  77. U7Rz3Da4FjgAL0RQ8qndD+LwRHXTY7H7wYM8V/3cYFZV7pSodd75q3MAXYQLf0ZV
  78. QR1XATu5l1QnXrxgHvz7MmDwb1D+jX3YPKnZveaukigQ6hDHdiVcePBiGXmk8LZC
  79. 2jQkdXeF7Su1ZYpr2nnEHLJ6vOLcCpPGb8gDABEB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rF4Rk97M9UIyKS0RtnfTWykRgDWHIsrtQPoNwsXrWoT
  96. 9LrM2v+1+9mp3vuXnE473/NHxmiWEQH9Ez+O/mOxQ7rSOlqGRiKq/IBZCfioJOtV
  97. fTQeIu/yASZnsLBqr6SJEGwYBoWcyjG++k4fyw8ocOAo4uGDYbxgN7yYfNQ0OH7o
  98. V6pfUgqKLWa/aK7/N1ZHnPdFLD8Xt0Dmy4BPwrKC
  99. =O7am
  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. import optparse
  109. import os
  110. import re
  111. import stat
  112. import subprocess
  113. import sys
  114. try:
  115. import urllib2
  116. except ImportError:
  117. # For python3
  118. import urllib.request
  119. import urllib.error
  120. else:
  121. # For python2
  122. import imp
  123. urllib = imp.new_module('urllib')
  124. urllib.request = urllib2
  125. urllib.error = urllib2
  126. home_dot_repo = os.path.expanduser('~/.repoconfig')
  127. gpg_dir = os.path.join(home_dot_repo, 'gnupg')
  128. extra_args = []
  129. init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
  130. # Logging
  131. group = init_optparse.add_option_group('Logging options')
  132. group.add_option('-q', '--quiet',
  133. dest="quiet", action="store_true", default=False,
  134. help="be quiet")
  135. # Manifest
  136. group = init_optparse.add_option_group('Manifest options')
  137. group.add_option('-u', '--manifest-url',
  138. dest='manifest_url',
  139. help='manifest repository location', metavar='URL')
  140. group.add_option('-b', '--manifest-branch',
  141. dest='manifest_branch',
  142. help='manifest branch or revision', metavar='REVISION')
  143. group.add_option('-m', '--manifest-name',
  144. dest='manifest_name',
  145. help='initial manifest file', metavar='NAME.xml')
  146. group.add_option('--mirror',
  147. dest='mirror', action='store_true',
  148. help='mirror the forrest')
  149. group.add_option('--reference',
  150. dest='reference',
  151. help='location of mirror directory', metavar='DIR')
  152. group.add_option('--depth', type='int', default=None,
  153. dest='depth',
  154. help='create a shallow clone with given depth; see git clone')
  155. group.add_option('-g', '--groups',
  156. dest='groups', default='default',
  157. help='restrict manifest projects to ones with a specified group',
  158. metavar='GROUP')
  159. group.add_option('-p', '--platform',
  160. dest='platform', default="auto",
  161. help='restrict manifest projects to ones with a specified '
  162. 'platform group [auto|all|none|linux|darwin|...]',
  163. metavar='PLATFORM')
  164. # Tool
  165. group = init_optparse.add_option_group('repo Version options')
  166. group.add_option('--repo-url',
  167. dest='repo_url',
  168. help='repo repository location', metavar='URL')
  169. group.add_option('--repo-branch',
  170. dest='repo_branch',
  171. help='repo branch or revision', metavar='REVISION')
  172. group.add_option('--no-repo-verify',
  173. dest='no_repo_verify', action='store_true',
  174. help='do not verify repo source code')
  175. # Other
  176. group = init_optparse.add_option_group('Other options')
  177. group.add_option('--config-name',
  178. dest='config_name', action="store_true", default=False,
  179. help='Always prompt for name/e-mail')
  180. class CloneFailure(Exception):
  181. """Indicate the remote clone of repo itself failed.
  182. """
  183. def _Init(args):
  184. """Installs repo by cloning it over the network.
  185. """
  186. opt, args = init_optparse.parse_args(args)
  187. if args:
  188. init_optparse.print_usage()
  189. sys.exit(1)
  190. url = opt.repo_url
  191. if not url:
  192. url = REPO_URL
  193. extra_args.append('--repo-url=%s' % url)
  194. branch = opt.repo_branch
  195. if not branch:
  196. branch = REPO_REV
  197. extra_args.append('--repo-branch=%s' % branch)
  198. if branch.startswith('refs/heads/'):
  199. branch = branch[len('refs/heads/'):]
  200. if branch.startswith('refs/'):
  201. print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
  202. raise CloneFailure()
  203. if not os.path.isdir(repodir):
  204. try:
  205. os.mkdir(repodir)
  206. except OSError as e:
  207. print >>sys.stderr, \
  208. 'fatal: cannot make %s directory: %s' % (
  209. repodir, e.strerror)
  210. # Don't faise CloneFailure; that would delete the
  211. # name. Instead exit immediately.
  212. #
  213. sys.exit(1)
  214. _CheckGitVersion()
  215. try:
  216. if NeedSetupGnuPG():
  217. can_verify = SetupGnuPG(opt.quiet)
  218. else:
  219. can_verify = True
  220. dst = os.path.abspath(os.path.join(repodir, S_repo))
  221. _Clone(url, dst, opt.quiet)
  222. if can_verify and not opt.no_repo_verify:
  223. rev = _Verify(dst, branch, opt.quiet)
  224. else:
  225. rev = 'refs/remotes/origin/%s^0' % branch
  226. _Checkout(dst, branch, rev, opt.quiet)
  227. except CloneFailure:
  228. if opt.quiet:
  229. print >>sys.stderr, \
  230. 'fatal: repo init failed; run without --quiet to see why'
  231. raise
  232. def _CheckGitVersion():
  233. cmd = [GIT, '--version']
  234. try:
  235. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  236. except OSError as e:
  237. print >>sys.stderr
  238. print >>sys.stderr, "fatal: '%s' is not available" % GIT
  239. print >>sys.stderr, 'fatal: %s' % e
  240. print >>sys.stderr
  241. print >>sys.stderr, 'Please make sure %s is installed'\
  242. ' and in your path.' % GIT
  243. raise CloneFailure()
  244. ver_str = proc.stdout.read().strip()
  245. proc.stdout.close()
  246. proc.wait()
  247. if not ver_str.startswith('git version '):
  248. print >>sys.stderr, 'error: "%s" unsupported' % ver_str
  249. raise CloneFailure()
  250. ver_str = ver_str[len('git version '):].strip()
  251. ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
  252. if ver_act < MIN_GIT_VERSION:
  253. need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
  254. print >>sys.stderr, 'fatal: git %s or later required' % need
  255. raise CloneFailure()
  256. def NeedSetupGnuPG():
  257. if not os.path.isdir(home_dot_repo):
  258. return True
  259. kv = os.path.join(home_dot_repo, 'keyring-version')
  260. if not os.path.exists(kv):
  261. return True
  262. kv = open(kv).read()
  263. if not kv:
  264. return True
  265. kv = tuple(map(lambda x: int(x), kv.split('.')))
  266. if kv < KEYRING_VERSION:
  267. return True
  268. return False
  269. def SetupGnuPG(quiet):
  270. if not os.path.isdir(home_dot_repo):
  271. try:
  272. os.mkdir(home_dot_repo)
  273. except OSError as e:
  274. print >>sys.stderr, \
  275. 'fatal: cannot make %s directory: %s' % (
  276. home_dot_repo, e.strerror)
  277. sys.exit(1)
  278. if not os.path.isdir(gpg_dir):
  279. try:
  280. os.mkdir(gpg_dir, stat.S_IRWXU)
  281. except OSError as e:
  282. print >>sys.stderr, \
  283. 'fatal: cannot make %s directory: %s' % (
  284. gpg_dir, e.strerror)
  285. sys.exit(1)
  286. env = os.environ.copy()
  287. env['GNUPGHOME'] = gpg_dir.encode()
  288. cmd = ['gpg', '--import']
  289. try:
  290. proc = subprocess.Popen(cmd,
  291. env = env,
  292. stdin = subprocess.PIPE)
  293. except OSError as e:
  294. if not quiet:
  295. print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
  296. print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
  297. print >>sys.stderr
  298. return False
  299. proc.stdin.write(MAINTAINER_KEYS)
  300. proc.stdin.close()
  301. if proc.wait() != 0:
  302. print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
  303. sys.exit(1)
  304. print
  305. fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
  306. fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
  307. fd.close()
  308. return True
  309. def _SetConfig(local, name, value):
  310. """Set a git configuration option to the specified value.
  311. """
  312. cmd = [GIT, 'config', name, value]
  313. if subprocess.Popen(cmd, cwd = local).wait() != 0:
  314. raise CloneFailure()
  315. def _InitHttp():
  316. handlers = []
  317. mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  318. try:
  319. import netrc
  320. n = netrc.netrc()
  321. for host in n.hosts:
  322. p = n.hosts[host]
  323. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  324. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  325. except:
  326. pass
  327. handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
  328. handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
  329. if 'http_proxy' in os.environ:
  330. url = os.environ['http_proxy']
  331. handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
  332. if 'REPO_CURL_VERBOSE' in os.environ:
  333. handlers.append(urllib.request.HTTPHandler(debuglevel=1))
  334. handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
  335. urllib.request.install_opener(urllib.request.build_opener(*handlers))
  336. def _Fetch(url, local, src, quiet):
  337. if not quiet:
  338. print >>sys.stderr, 'Get %s' % url
  339. cmd = [GIT, 'fetch']
  340. if quiet:
  341. cmd.append('--quiet')
  342. err = subprocess.PIPE
  343. else:
  344. err = None
  345. cmd.append(src)
  346. cmd.append('+refs/heads/*:refs/remotes/origin/*')
  347. cmd.append('refs/tags/*:refs/tags/*')
  348. proc = subprocess.Popen(cmd, cwd = local, stderr = err)
  349. if err:
  350. proc.stderr.read()
  351. proc.stderr.close()
  352. if proc.wait() != 0:
  353. raise CloneFailure()
  354. def _DownloadBundle(url, local, quiet):
  355. if not url.endswith('/'):
  356. url += '/'
  357. url += 'clone.bundle'
  358. proc = subprocess.Popen(
  359. [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
  360. cwd = local,
  361. stdout = subprocess.PIPE)
  362. for line in proc.stdout:
  363. m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
  364. if m:
  365. new_url = m.group(1)
  366. old_url = m.group(2)
  367. if url.startswith(old_url):
  368. url = new_url + url[len(old_url):]
  369. break
  370. proc.stdout.close()
  371. proc.wait()
  372. if not url.startswith('http:') and not url.startswith('https:'):
  373. return False
  374. dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
  375. try:
  376. try:
  377. r = urllib.request.urlopen(url)
  378. except urllib.error.HTTPError as e:
  379. if e.code == 404:
  380. return False
  381. print >>sys.stderr, 'fatal: Cannot get %s' % url
  382. print >>sys.stderr, 'fatal: HTTP error %s' % e.code
  383. raise CloneFailure()
  384. except urllib.error.URLError as e:
  385. print >>sys.stderr, 'fatal: Cannot get %s' % url
  386. print >>sys.stderr, 'fatal: error %s' % e.reason
  387. raise CloneFailure()
  388. try:
  389. if not quiet:
  390. print >>sys.stderr, 'Get %s' % url
  391. while True:
  392. buf = r.read(8192)
  393. if buf == '':
  394. return True
  395. dest.write(buf)
  396. finally:
  397. r.close()
  398. finally:
  399. dest.close()
  400. def _ImportBundle(local):
  401. path = os.path.join(local, '.git', 'clone.bundle')
  402. try:
  403. _Fetch(local, local, path, True)
  404. finally:
  405. os.remove(path)
  406. def _Clone(url, local, quiet):
  407. """Clones a git repository to a new subdirectory of repodir
  408. """
  409. try:
  410. os.mkdir(local)
  411. except OSError as e:
  412. print >>sys.stderr, \
  413. 'fatal: cannot make %s directory: %s' \
  414. % (local, e.strerror)
  415. raise CloneFailure()
  416. cmd = [GIT, 'init', '--quiet']
  417. try:
  418. proc = subprocess.Popen(cmd, cwd = local)
  419. except OSError as e:
  420. print >>sys.stderr
  421. print >>sys.stderr, "fatal: '%s' is not available" % GIT
  422. print >>sys.stderr, 'fatal: %s' % e
  423. print >>sys.stderr
  424. print >>sys.stderr, 'Please make sure %s is installed'\
  425. ' and in your path.' % GIT
  426. raise CloneFailure()
  427. if proc.wait() != 0:
  428. print >>sys.stderr, 'fatal: could not create %s' % local
  429. raise CloneFailure()
  430. _InitHttp()
  431. _SetConfig(local, 'remote.origin.url', url)
  432. _SetConfig(local, 'remote.origin.fetch',
  433. '+refs/heads/*:refs/remotes/origin/*')
  434. if _DownloadBundle(url, local, quiet):
  435. _ImportBundle(local)
  436. else:
  437. _Fetch(url, local, 'origin', quiet)
  438. def _Verify(cwd, branch, quiet):
  439. """Verify the branch has been signed by a tag.
  440. """
  441. cmd = [GIT, 'describe', 'origin/%s' % branch]
  442. proc = subprocess.Popen(cmd,
  443. stdout=subprocess.PIPE,
  444. stderr=subprocess.PIPE,
  445. cwd = cwd)
  446. cur = proc.stdout.read().strip()
  447. proc.stdout.close()
  448. proc.stderr.read()
  449. proc.stderr.close()
  450. if proc.wait() != 0 or not cur:
  451. print >>sys.stderr
  452. print >>sys.stderr,\
  453. "fatal: branch '%s' has not been signed" \
  454. % branch
  455. raise CloneFailure()
  456. m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
  457. if m:
  458. cur = m.group(1)
  459. if not quiet:
  460. print >>sys.stderr
  461. print >>sys.stderr, \
  462. "info: Ignoring branch '%s'; using tagged release '%s'" \
  463. % (branch, cur)
  464. print >>sys.stderr
  465. env = os.environ.copy()
  466. env['GNUPGHOME'] = gpg_dir.encode()
  467. cmd = [GIT, 'tag', '-v', cur]
  468. proc = subprocess.Popen(cmd,
  469. stdout = subprocess.PIPE,
  470. stderr = subprocess.PIPE,
  471. cwd = cwd,
  472. env = env)
  473. out = proc.stdout.read()
  474. proc.stdout.close()
  475. err = proc.stderr.read()
  476. proc.stderr.close()
  477. if proc.wait() != 0:
  478. print >>sys.stderr
  479. print >>sys.stderr, out
  480. print >>sys.stderr, err
  481. print >>sys.stderr
  482. raise CloneFailure()
  483. return '%s^0' % cur
  484. def _Checkout(cwd, branch, rev, quiet):
  485. """Checkout an upstream branch into the repository and track it.
  486. """
  487. cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
  488. if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
  489. raise CloneFailure()
  490. _SetConfig(cwd, 'branch.default.remote', 'origin')
  491. _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
  492. cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
  493. if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
  494. raise CloneFailure()
  495. cmd = [GIT, 'read-tree', '--reset', '-u']
  496. if not quiet:
  497. cmd.append('-v')
  498. cmd.append('HEAD')
  499. if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
  500. raise CloneFailure()
  501. def _FindRepo():
  502. """Look for a repo installation, starting at the current directory.
  503. """
  504. curdir = os.getcwd()
  505. repo = None
  506. olddir = None
  507. while curdir != '/' \
  508. and curdir != olddir \
  509. and not repo:
  510. repo = os.path.join(curdir, repodir, REPO_MAIN)
  511. if not os.path.isfile(repo):
  512. repo = None
  513. olddir = curdir
  514. curdir = os.path.dirname(curdir)
  515. return (repo, os.path.join(curdir, repodir))
  516. class _Options:
  517. help = False
  518. def _ParseArguments(args):
  519. cmd = None
  520. opt = _Options()
  521. arg = []
  522. for i in xrange(0, len(args)):
  523. a = args[i]
  524. if a == '-h' or a == '--help':
  525. opt.help = True
  526. elif not a.startswith('-'):
  527. cmd = a
  528. arg = args[i + 1:]
  529. break
  530. return cmd, opt, arg
  531. def _Usage():
  532. print >>sys.stderr,\
  533. """usage: repo COMMAND [ARGS]
  534. repo is not yet installed. Use "repo init" to install it here.
  535. The most commonly used repo commands are:
  536. init Install repo in the current working directory
  537. help Display detailed help on a command
  538. For access to the full online help, install repo ("repo init").
  539. """
  540. sys.exit(1)
  541. def _Help(args):
  542. if args:
  543. if args[0] == 'init':
  544. init_optparse.print_help()
  545. sys.exit(0)
  546. else:
  547. print >>sys.stderr,\
  548. "error: '%s' is not a bootstrap command.\n"\
  549. ' For access to online help, install repo ("repo init").'\
  550. % args[0]
  551. else:
  552. _Usage()
  553. sys.exit(1)
  554. def _NotInstalled():
  555. print >>sys.stderr,\
  556. 'error: repo is not installed. Use "repo init" to install it here.'
  557. sys.exit(1)
  558. def _NoCommands(cmd):
  559. print >>sys.stderr,\
  560. """error: command '%s' requires repo to be installed first.
  561. Use "repo init" to install it here.""" % cmd
  562. sys.exit(1)
  563. def _RunSelf(wrapper_path):
  564. my_dir = os.path.dirname(wrapper_path)
  565. my_main = os.path.join(my_dir, 'main.py')
  566. my_git = os.path.join(my_dir, '.git')
  567. if os.path.isfile(my_main) and os.path.isdir(my_git):
  568. for name in ['git_config.py',
  569. 'project.py',
  570. 'subcmds']:
  571. if not os.path.exists(os.path.join(my_dir, name)):
  572. return None, None
  573. return my_main, my_git
  574. return None, None
  575. def _SetDefaultsTo(gitdir):
  576. global REPO_URL
  577. global REPO_REV
  578. REPO_URL = gitdir
  579. proc = subprocess.Popen([GIT,
  580. '--git-dir=%s' % gitdir,
  581. 'symbolic-ref',
  582. 'HEAD'],
  583. stdout = subprocess.PIPE,
  584. stderr = subprocess.PIPE)
  585. REPO_REV = proc.stdout.read().strip()
  586. proc.stdout.close()
  587. proc.stderr.read()
  588. proc.stderr.close()
  589. if proc.wait() != 0:
  590. print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
  591. sys.exit(1)
  592. def main(orig_args):
  593. repo_main, rel_repo_dir = _FindRepo()
  594. cmd, opt, args = _ParseArguments(orig_args)
  595. wrapper_path = os.path.abspath(__file__)
  596. my_main, my_git = _RunSelf(wrapper_path)
  597. if not repo_main:
  598. if opt.help:
  599. _Usage()
  600. if cmd == 'help':
  601. _Help(args)
  602. if not cmd:
  603. _NotInstalled()
  604. if cmd == 'init':
  605. if my_git:
  606. _SetDefaultsTo(my_git)
  607. try:
  608. _Init(args)
  609. except CloneFailure:
  610. for root, dirs, files in os.walk(repodir, topdown=False):
  611. for name in files:
  612. os.remove(os.path.join(root, name))
  613. for name in dirs:
  614. os.rmdir(os.path.join(root, name))
  615. os.rmdir(repodir)
  616. sys.exit(1)
  617. repo_main, rel_repo_dir = _FindRepo()
  618. else:
  619. _NoCommands(cmd)
  620. if my_main:
  621. repo_main = my_main
  622. ver_str = '.'.join(map(lambda x: str(x), VERSION))
  623. me = [repo_main,
  624. '--repo-dir=%s' % rel_repo_dir,
  625. '--wrapper-version=%s' % ver_str,
  626. '--wrapper-path=%s' % wrapper_path,
  627. '--']
  628. me.extend(orig_args)
  629. me.extend(extra_args)
  630. try:
  631. os.execv(repo_main, me)
  632. except OSError as e:
  633. print >>sys.stderr, "fatal: unable to start %s" % repo_main
  634. print >>sys.stderr, "fatal: %s" % e
  635. sys.exit(148)
  636. if __name__ == '__main__':
  637. main(sys.argv[1:])