repo 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. #!/bin/sh
  2. ## repo default configuration
  3. ##
  4. REPO_URL='https://code.google.com/p/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, 13)
  28. # increment this if the MAINTAINER_KEYS block is modified
  29. KEYRING_VERSION = (1,0)
  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. AwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEBZTDV6SD1xl1GEAn0x/OKQpy7qI
  45. 6G73NJviU0IUMtftAKCFMUhGb/0bZvQ8Rm3QCUpWHyEIu7kEDQRI97ogEBAA2wI6
  46. 5fs9y/rMwD6dkD/vK9v4C9mOn1IL5JCPYMJBVSci+9ED4ChzYvfq7wOcj9qIvaE0
  47. GwCt2ar7Q56me5J+byhSb32Rqsw/r3Vo5cZMH80N4cjesGuSXOGyEWTe4HYoxnHv
  48. gF4EKI2LK7xfTUcxMtlyn52sUpkfKsCpUhFvdmbAiJE+jCkQZr1Z8u2KphV79Ou+
  49. P1N5IXY/XWOlq48Qf4MWCYlJFrB07xjUjLKMPDNDnm58L5byDrP/eHysKexpbakL
  50. xCmYyfT6DV1SWLblpd2hie0sL3YejdtuBMYMS2rI7Yxb8kGuqkz+9l1qhwJtei94
  51. 5MaretDy/d/JH/pRYkRf7L+ke7dpzrP+aJmcz9P1e6gq4NJsWejaALVASBiioqNf
  52. QmtqSVzF1wkR5avZkFHuYvj6V/t1RrOZTXxkSk18KFMJRBZrdHFCWbc5qrVxUB6e
  53. N5pja0NFIUCigLBV1c6I2DwiuboMNh18VtJJh+nwWeez/RueN4ig59gRTtkcc0PR
  54. 35tX2DR8+xCCFVW/NcJ4PSePYzCuuLvp1vEDHnj41R52Fz51hgddT4rBsp0nL+5I
  55. socSOIIezw8T9vVzMY4ArCKFAVu2IVyBcahTfBS8q5EM63mONU6UVJEozfGljiMw
  56. xuQ7JwKcw0AUEKTKG7aBgBaTAgT8TOevpvlw91cAAwUP/jRkyVi/0WAb0qlEaq/S
  57. ouWxX1faR+vU3b+Y2/DGjtXQMzG0qpetaTHC/AxxHpgt/dCkWI6ljYDnxgPLwG0a
  58. Oasm94BjZc6vZwf1opFZUKsjOAAxRxNZyjUJKe4UZVuMTk6zo27Nt3LMnc0FO47v
  59. FcOjRyquvgNOS818irVHUf12waDx8gszKxQTTtFxU5/ePB2jZmhP6oXSe4K/LG5T
  60. +WBRPDrHiGPhCzJRzm9BP0lTnGCAj3o9W90STZa65RK7IaYpC8TB35JTBEbrrNCp
  61. w6lzd74LnNEp5eMlKDnXzUAgAH0yzCQeMl7t33QCdYx2hRs2wtTQSjGfAiNmj/WW
  62. Vl5Jn+2jCDnRLenKHwVRFsBX2e0BiRWt/i9Y8fjorLCXVj4z+7yW6DawdLkJorEo
  63. p3v5ILwfC7hVx4jHSnOgZ65L9s8EQdVr1ckN9243yta7rNgwfcqb60ILMFF1BRk/
  64. 0V7wCL+68UwwiQDvyMOQuqkysKLSDCLb7BFcyA7j6KG+5hpsREstFX2wK1yKeraz
  65. 5xGrFy8tfAaeBMIQ17gvFSp/suc9DYO0ICK2BISzq+F+ZiAKsjMYOBNdH/h0zobQ
  66. HTHs37+/QLMomGEGKZMWi0dShU2J5mNRQu3Hhxl3hHDVbt5CeJBb26aQcQrFz69W
  67. zE3GNvmJosh6leayjtI9P2A6iEkEGBECAAkFAkj3uiACGwwACgkQFlMNXpIPXGWp
  68. TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2
  69. =CMiZ
  70. -----END PGP PUBLIC KEY BLOCK-----
  71. """
  72. GIT = 'git' # our git command
  73. MIN_GIT_VERSION = (1, 5, 4) # minimum supported git version
  74. repodir = '.repo' # name of repo's private directory
  75. S_repo = 'repo' # special repo reposiory
  76. S_manifests = 'manifests' # special manifest repository
  77. REPO_MAIN = S_repo + '/main.py' # main script
  78. import optparse
  79. import os
  80. import re
  81. import readline
  82. import subprocess
  83. import sys
  84. import urllib2
  85. home_dot_repo = os.path.expanduser('~/.repoconfig')
  86. gpg_dir = os.path.join(home_dot_repo, 'gnupg')
  87. extra_args = []
  88. init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
  89. # Logging
  90. group = init_optparse.add_option_group('Logging options')
  91. group.add_option('-q', '--quiet',
  92. dest="quiet", action="store_true", default=False,
  93. help="be quiet")
  94. # Manifest
  95. group = init_optparse.add_option_group('Manifest options')
  96. group.add_option('-u', '--manifest-url',
  97. dest='manifest_url',
  98. help='manifest repository location', metavar='URL')
  99. group.add_option('-b', '--manifest-branch',
  100. dest='manifest_branch',
  101. help='manifest branch or revision', metavar='REVISION')
  102. group.add_option('-m', '--manifest-name',
  103. dest='manifest_name',
  104. help='initial manifest file', metavar='NAME.xml')
  105. group.add_option('--mirror',
  106. dest='mirror', action='store_true',
  107. help='mirror the forrest')
  108. group.add_option('--reference',
  109. dest='reference',
  110. help='location of mirror directory', metavar='DIR')
  111. group.add_option('--depth', type='int', default=None,
  112. dest='depth',
  113. help='create a shallow clone with given depth; see git clone')
  114. # Tool
  115. group = init_optparse.add_option_group('repo Version options')
  116. group.add_option('--repo-url',
  117. dest='repo_url',
  118. help='repo repository location', metavar='URL')
  119. group.add_option('--repo-branch',
  120. dest='repo_branch',
  121. help='repo branch or revision', metavar='REVISION')
  122. group.add_option('--no-repo-verify',
  123. dest='no_repo_verify', action='store_true',
  124. help='do not verify repo source code')
  125. class CloneFailure(Exception):
  126. """Indicate the remote clone of repo itself failed.
  127. """
  128. def _Init(args):
  129. """Installs repo by cloning it over the network.
  130. """
  131. opt, args = init_optparse.parse_args(args)
  132. if args or not opt.manifest_url:
  133. init_optparse.print_usage()
  134. sys.exit(1)
  135. url = opt.repo_url
  136. if not url:
  137. url = REPO_URL
  138. extra_args.append('--repo-url=%s' % url)
  139. branch = opt.repo_branch
  140. if not branch:
  141. branch = REPO_REV
  142. extra_args.append('--repo-branch=%s' % branch)
  143. if branch.startswith('refs/heads/'):
  144. branch = branch[len('refs/heads/'):]
  145. if branch.startswith('refs/'):
  146. print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
  147. raise CloneFailure()
  148. if not os.path.isdir(repodir):
  149. try:
  150. os.mkdir(repodir)
  151. except OSError, e:
  152. print >>sys.stderr, \
  153. 'fatal: cannot make %s directory: %s' % (
  154. repodir, e.strerror)
  155. # Don't faise CloneFailure; that would delete the
  156. # name. Instead exit immediately.
  157. #
  158. sys.exit(1)
  159. _CheckGitVersion()
  160. try:
  161. if _NeedSetupGnuPG():
  162. can_verify = _SetupGnuPG(opt.quiet)
  163. else:
  164. can_verify = True
  165. dst = os.path.abspath(os.path.join(repodir, S_repo))
  166. _Clone(url, dst, opt.quiet)
  167. if can_verify and not opt.no_repo_verify:
  168. rev = _Verify(dst, branch, opt.quiet)
  169. else:
  170. rev = 'refs/remotes/origin/%s^0' % branch
  171. _Checkout(dst, branch, rev, opt.quiet)
  172. except CloneFailure:
  173. if opt.quiet:
  174. print >>sys.stderr, \
  175. 'fatal: repo init failed; run without --quiet to see why'
  176. raise
  177. def _CheckGitVersion():
  178. cmd = [GIT, '--version']
  179. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  180. ver_str = proc.stdout.read().strip()
  181. proc.stdout.close()
  182. proc.wait()
  183. if not ver_str.startswith('git version '):
  184. print >>sys.stderr, 'error: "%s" unsupported' % ver_str
  185. raise CloneFailure()
  186. ver_str = ver_str[len('git version '):].strip()
  187. ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
  188. if ver_act < MIN_GIT_VERSION:
  189. need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
  190. print >>sys.stderr, 'fatal: git %s or later required' % need
  191. raise CloneFailure()
  192. def _NeedSetupGnuPG():
  193. if not os.path.isdir(home_dot_repo):
  194. return True
  195. kv = os.path.join(home_dot_repo, 'keyring-version')
  196. if not os.path.exists(kv):
  197. return True
  198. kv = open(kv).read()
  199. if not kv:
  200. return True
  201. kv = tuple(map(lambda x: int(x), kv.split('.')))
  202. if kv < KEYRING_VERSION:
  203. return True
  204. return False
  205. def _SetupGnuPG(quiet):
  206. if not os.path.isdir(home_dot_repo):
  207. try:
  208. os.mkdir(home_dot_repo)
  209. except OSError, e:
  210. print >>sys.stderr, \
  211. 'fatal: cannot make %s directory: %s' % (
  212. home_dot_repo, e.strerror)
  213. sys.exit(1)
  214. if not os.path.isdir(gpg_dir):
  215. try:
  216. os.mkdir(gpg_dir, 0700)
  217. except OSError, e:
  218. print >>sys.stderr, \
  219. 'fatal: cannot make %s directory: %s' % (
  220. gpg_dir, e.strerror)
  221. sys.exit(1)
  222. env = os.environ.copy()
  223. env['GNUPGHOME'] = gpg_dir.encode()
  224. cmd = ['gpg', '--import']
  225. try:
  226. proc = subprocess.Popen(cmd,
  227. env = env,
  228. stdin = subprocess.PIPE)
  229. except OSError, e:
  230. if not quiet:
  231. print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
  232. print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
  233. print >>sys.stderr
  234. return False
  235. proc.stdin.write(MAINTAINER_KEYS)
  236. proc.stdin.close()
  237. if proc.wait() != 0:
  238. print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
  239. sys.exit(1)
  240. print
  241. fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
  242. fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
  243. fd.close()
  244. return True
  245. def _SetConfig(local, name, value):
  246. """Set a git configuration option to the specified value.
  247. """
  248. cmd = [GIT, 'config', name, value]
  249. if subprocess.Popen(cmd, cwd = local).wait() != 0:
  250. raise CloneFailure()
  251. def _InitHttp():
  252. handlers = []
  253. mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
  254. try:
  255. import netrc
  256. n = netrc.netrc()
  257. for host in n.hosts:
  258. p = n.hosts[host]
  259. mgr.add_password(None, 'http://%s/' % host, p[0], p[2])
  260. mgr.add_password(None, 'https://%s/' % host, p[0], p[2])
  261. except:
  262. pass
  263. handlers.append(urllib2.HTTPBasicAuthHandler(mgr))
  264. if 'http_proxy' in os.environ:
  265. url = os.environ['http_proxy']
  266. handlers.append(urllib2.ProxyHandler({'http': url, 'https': url}))
  267. if 'REPO_CURL_VERBOSE' in os.environ:
  268. handlers.append(urllib2.HTTPHandler(debuglevel=1))
  269. handlers.append(urllib2.HTTPSHandler(debuglevel=1))
  270. urllib2.install_opener(urllib2.build_opener(*handlers))
  271. def _Fetch(url, local, src, quiet):
  272. if not quiet:
  273. print >>sys.stderr, 'Get %s' % url
  274. cmd = [GIT, 'fetch']
  275. if quiet:
  276. cmd.append('--quiet')
  277. err = subprocess.PIPE
  278. else:
  279. err = None
  280. cmd.append(src)
  281. cmd.append('+refs/heads/*:refs/remotes/origin/*')
  282. cmd.append('refs/tags/*:refs/tags/*')
  283. proc = subprocess.Popen(cmd, cwd = local, stderr = err)
  284. if err:
  285. proc.stderr.read()
  286. proc.stderr.close()
  287. if proc.wait() != 0:
  288. raise CloneFailure()
  289. def _DownloadBundle(url, local, quiet):
  290. if not url.endswith('/'):
  291. url += '/'
  292. url += 'clone.bundle'
  293. proc = subprocess.Popen(
  294. [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
  295. cwd = local,
  296. stdout = subprocess.PIPE)
  297. for line in proc.stdout:
  298. m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
  299. if m:
  300. new_url = m.group(1)
  301. old_url = m.group(2)
  302. if url.startswith(old_url):
  303. url = new_url + url[len(old_url):]
  304. break
  305. proc.stdout.close()
  306. proc.wait()
  307. if not url.startswith('http:') and not url.startswith('https:'):
  308. return False
  309. dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
  310. try:
  311. try:
  312. r = urllib2.urlopen(url)
  313. except urllib2.HTTPError, e:
  314. if e.code == 404:
  315. return False
  316. print >>sys.stderr, 'fatal: Cannot get %s' % url
  317. print >>sys.stderr, 'fatal: HTTP error %s' % e.code
  318. raise CloneFailure()
  319. except urllib2.URLError, e:
  320. print >>sys.stderr, 'fatal: Cannot get %s' % url
  321. print >>sys.stderr, 'fatal: error %s' % e.reason
  322. raise CloneFailure()
  323. try:
  324. if not quiet:
  325. print >>sys.stderr, 'Get %s' % url
  326. while True:
  327. buf = r.read(8192)
  328. if buf == '':
  329. return True
  330. dest.write(buf)
  331. finally:
  332. r.close()
  333. finally:
  334. dest.close()
  335. def _ImportBundle(local):
  336. path = os.path.join(local, '.git', 'clone.bundle')
  337. try:
  338. _Fetch(local, local, path, True)
  339. finally:
  340. os.remove(path)
  341. def _Clone(url, local, quiet):
  342. """Clones a git repository to a new subdirectory of repodir
  343. """
  344. try:
  345. os.mkdir(local)
  346. except OSError, e:
  347. print >>sys.stderr, \
  348. 'fatal: cannot make %s directory: %s' \
  349. % (local, e.strerror)
  350. raise CloneFailure()
  351. cmd = [GIT, 'init', '--quiet']
  352. try:
  353. proc = subprocess.Popen(cmd, cwd = local)
  354. except OSError, e:
  355. print >>sys.stderr
  356. print >>sys.stderr, "fatal: '%s' is not available" % GIT
  357. print >>sys.stderr, 'fatal: %s' % e
  358. print >>sys.stderr
  359. print >>sys.stderr, 'Please make sure %s is installed'\
  360. ' and in your path.' % GIT
  361. raise CloneFailure()
  362. if proc.wait() != 0:
  363. print >>sys.stderr, 'fatal: could not create %s' % local
  364. raise CloneFailure()
  365. _InitHttp()
  366. _SetConfig(local, 'remote.origin.url', url)
  367. _SetConfig(local, 'remote.origin.fetch',
  368. '+refs/heads/*:refs/remotes/origin/*')
  369. if _DownloadBundle(url, local, quiet):
  370. _ImportBundle(local)
  371. else:
  372. _Fetch(url, local, 'origin', quiet)
  373. def _Verify(cwd, branch, quiet):
  374. """Verify the branch has been signed by a tag.
  375. """
  376. cmd = [GIT, 'describe', 'origin/%s' % branch]
  377. proc = subprocess.Popen(cmd,
  378. stdout=subprocess.PIPE,
  379. stderr=subprocess.PIPE,
  380. cwd = cwd)
  381. cur = proc.stdout.read().strip()
  382. proc.stdout.close()
  383. proc.stderr.read()
  384. proc.stderr.close()
  385. if proc.wait() != 0 or not cur:
  386. print >>sys.stderr
  387. print >>sys.stderr,\
  388. "fatal: branch '%s' has not been signed" \
  389. % branch
  390. raise CloneFailure()
  391. m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
  392. if m:
  393. cur = m.group(1)
  394. if not quiet:
  395. print >>sys.stderr
  396. print >>sys.stderr, \
  397. "info: Ignoring branch '%s'; using tagged release '%s'" \
  398. % (branch, cur)
  399. print >>sys.stderr
  400. env = os.environ.copy()
  401. env['GNUPGHOME'] = gpg_dir.encode()
  402. cmd = [GIT, 'tag', '-v', cur]
  403. proc = subprocess.Popen(cmd,
  404. stdout = subprocess.PIPE,
  405. stderr = subprocess.PIPE,
  406. cwd = cwd,
  407. env = env)
  408. out = proc.stdout.read()
  409. proc.stdout.close()
  410. err = proc.stderr.read()
  411. proc.stderr.close()
  412. if proc.wait() != 0:
  413. print >>sys.stderr
  414. print >>sys.stderr, out
  415. print >>sys.stderr, err
  416. print >>sys.stderr
  417. raise CloneFailure()
  418. return '%s^0' % cur
  419. def _Checkout(cwd, branch, rev, quiet):
  420. """Checkout an upstream branch into the repository and track it.
  421. """
  422. cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
  423. if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
  424. raise CloneFailure()
  425. _SetConfig(cwd, 'branch.default.remote', 'origin')
  426. _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
  427. cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
  428. if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
  429. raise CloneFailure()
  430. cmd = [GIT, 'read-tree', '--reset', '-u']
  431. if not quiet:
  432. cmd.append('-v')
  433. cmd.append('HEAD')
  434. if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
  435. raise CloneFailure()
  436. def _FindRepo():
  437. """Look for a repo installation, starting at the current directory.
  438. """
  439. dir = os.getcwd()
  440. repo = None
  441. olddir = None
  442. while dir != '/' \
  443. and dir != olddir \
  444. and not repo:
  445. repo = os.path.join(dir, repodir, REPO_MAIN)
  446. if not os.path.isfile(repo):
  447. repo = None
  448. olddir = dir
  449. dir = os.path.dirname(dir)
  450. return (repo, os.path.join(dir, repodir))
  451. class _Options:
  452. help = False
  453. def _ParseArguments(args):
  454. cmd = None
  455. opt = _Options()
  456. arg = []
  457. for i in xrange(0, len(args)):
  458. a = args[i]
  459. if a == '-h' or a == '--help':
  460. opt.help = True
  461. elif not a.startswith('-'):
  462. cmd = a
  463. arg = args[i + 1:]
  464. break
  465. return cmd, opt, arg
  466. def _Usage():
  467. print >>sys.stderr,\
  468. """usage: repo COMMAND [ARGS]
  469. repo is not yet installed. Use "repo init" to install it here.
  470. The most commonly used repo commands are:
  471. init Install repo in the current working directory
  472. help Display detailed help on a command
  473. For access to the full online help, install repo ("repo init").
  474. """
  475. sys.exit(1)
  476. def _Help(args):
  477. if args:
  478. if args[0] == 'init':
  479. init_optparse.print_help()
  480. sys.exit(0)
  481. else:
  482. print >>sys.stderr,\
  483. "error: '%s' is not a bootstrap command.\n"\
  484. ' For access to online help, install repo ("repo init").'\
  485. % args[0]
  486. else:
  487. _Usage()
  488. sys.exit(1)
  489. def _NotInstalled():
  490. print >>sys.stderr,\
  491. 'error: repo is not installed. Use "repo init" to install it here.'
  492. sys.exit(1)
  493. def _NoCommands(cmd):
  494. print >>sys.stderr,\
  495. """error: command '%s' requires repo to be installed first.
  496. Use "repo init" to install it here.""" % cmd
  497. sys.exit(1)
  498. def _RunSelf(wrapper_path):
  499. my_dir = os.path.dirname(wrapper_path)
  500. my_main = os.path.join(my_dir, 'main.py')
  501. my_git = os.path.join(my_dir, '.git')
  502. if os.path.isfile(my_main) and os.path.isdir(my_git):
  503. for name in ['git_config.py',
  504. 'project.py',
  505. 'subcmds']:
  506. if not os.path.exists(os.path.join(my_dir, name)):
  507. return None, None
  508. return my_main, my_git
  509. return None, None
  510. def _SetDefaultsTo(gitdir):
  511. global REPO_URL
  512. global REPO_REV
  513. REPO_URL = gitdir
  514. proc = subprocess.Popen([GIT,
  515. '--git-dir=%s' % gitdir,
  516. 'symbolic-ref',
  517. 'HEAD'],
  518. stdout = subprocess.PIPE,
  519. stderr = subprocess.PIPE)
  520. REPO_REV = proc.stdout.read().strip()
  521. proc.stdout.close()
  522. proc.stderr.read()
  523. proc.stderr.close()
  524. if proc.wait() != 0:
  525. print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
  526. sys.exit(1)
  527. def main(orig_args):
  528. main, dir = _FindRepo()
  529. cmd, opt, args = _ParseArguments(orig_args)
  530. wrapper_path = os.path.abspath(__file__)
  531. my_main, my_git = _RunSelf(wrapper_path)
  532. if not main:
  533. if opt.help:
  534. _Usage()
  535. if cmd == 'help':
  536. _Help(args)
  537. if not cmd:
  538. _NotInstalled()
  539. if cmd == 'init':
  540. if my_git:
  541. _SetDefaultsTo(my_git)
  542. try:
  543. _Init(args)
  544. except CloneFailure:
  545. for root, dirs, files in os.walk(repodir, topdown=False):
  546. for name in files:
  547. os.remove(os.path.join(root, name))
  548. for name in dirs:
  549. os.rmdir(os.path.join(root, name))
  550. os.rmdir(repodir)
  551. sys.exit(1)
  552. main, dir = _FindRepo()
  553. else:
  554. _NoCommands(cmd)
  555. if my_main:
  556. main = my_main
  557. ver_str = '.'.join(map(lambda x: str(x), VERSION))
  558. me = [main,
  559. '--repo-dir=%s' % dir,
  560. '--wrapper-version=%s' % ver_str,
  561. '--wrapper-path=%s' % wrapper_path,
  562. '--']
  563. me.extend(orig_args)
  564. me.extend(extra_args)
  565. try:
  566. os.execv(main, me)
  567. except OSError, e:
  568. print >>sys.stderr, "fatal: unable to start %s" % main
  569. print >>sys.stderr, "fatal: %s" % e
  570. sys.exit(148)
  571. if __name__ == '__main__':
  572. main(sys.argv[1:])