repo 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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, 16)
  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. group.add_option('-g', '--groups',
  115. dest='groups', default='default',
  116. help='restrict manifest projects to ones with a specified group',
  117. metavar='GROUP')
  118. # Tool
  119. group = init_optparse.add_option_group('repo Version options')
  120. group.add_option('--repo-url',
  121. dest='repo_url',
  122. help='repo repository location', metavar='URL')
  123. group.add_option('--repo-branch',
  124. dest='repo_branch',
  125. help='repo branch or revision', metavar='REVISION')
  126. group.add_option('--no-repo-verify',
  127. dest='no_repo_verify', action='store_true',
  128. help='do not verify repo source code')
  129. # Other
  130. group = init_optparse.add_option_group('Other options')
  131. group.add_option('--config-name',
  132. dest='config_name', action="store_true", default=False,
  133. help='Always prompt for name/e-mail')
  134. class CloneFailure(Exception):
  135. """Indicate the remote clone of repo itself failed.
  136. """
  137. def _Init(args):
  138. """Installs repo by cloning it over the network.
  139. """
  140. opt, args = init_optparse.parse_args(args)
  141. if args:
  142. init_optparse.print_usage()
  143. sys.exit(1)
  144. url = opt.repo_url
  145. if not url:
  146. url = REPO_URL
  147. extra_args.append('--repo-url=%s' % url)
  148. branch = opt.repo_branch
  149. if not branch:
  150. branch = REPO_REV
  151. extra_args.append('--repo-branch=%s' % branch)
  152. if branch.startswith('refs/heads/'):
  153. branch = branch[len('refs/heads/'):]
  154. if branch.startswith('refs/'):
  155. print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
  156. raise CloneFailure()
  157. if not os.path.isdir(repodir):
  158. try:
  159. os.mkdir(repodir)
  160. except OSError, e:
  161. print >>sys.stderr, \
  162. 'fatal: cannot make %s directory: %s' % (
  163. repodir, e.strerror)
  164. # Don't faise CloneFailure; that would delete the
  165. # name. Instead exit immediately.
  166. #
  167. sys.exit(1)
  168. _CheckGitVersion()
  169. try:
  170. if _NeedSetupGnuPG():
  171. can_verify = _SetupGnuPG(opt.quiet)
  172. else:
  173. can_verify = True
  174. dst = os.path.abspath(os.path.join(repodir, S_repo))
  175. _Clone(url, dst, opt.quiet)
  176. if can_verify and not opt.no_repo_verify:
  177. rev = _Verify(dst, branch, opt.quiet)
  178. else:
  179. rev = 'refs/remotes/origin/%s^0' % branch
  180. _Checkout(dst, branch, rev, opt.quiet)
  181. except CloneFailure:
  182. if opt.quiet:
  183. print >>sys.stderr, \
  184. 'fatal: repo init failed; run without --quiet to see why'
  185. raise
  186. def _CheckGitVersion():
  187. cmd = [GIT, '--version']
  188. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  189. ver_str = proc.stdout.read().strip()
  190. proc.stdout.close()
  191. proc.wait()
  192. if not ver_str.startswith('git version '):
  193. print >>sys.stderr, 'error: "%s" unsupported' % ver_str
  194. raise CloneFailure()
  195. ver_str = ver_str[len('git version '):].strip()
  196. ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
  197. if ver_act < MIN_GIT_VERSION:
  198. need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
  199. print >>sys.stderr, 'fatal: git %s or later required' % need
  200. raise CloneFailure()
  201. def _NeedSetupGnuPG():
  202. if not os.path.isdir(home_dot_repo):
  203. return True
  204. kv = os.path.join(home_dot_repo, 'keyring-version')
  205. if not os.path.exists(kv):
  206. return True
  207. kv = open(kv).read()
  208. if not kv:
  209. return True
  210. kv = tuple(map(lambda x: int(x), kv.split('.')))
  211. if kv < KEYRING_VERSION:
  212. return True
  213. return False
  214. def _SetupGnuPG(quiet):
  215. if not os.path.isdir(home_dot_repo):
  216. try:
  217. os.mkdir(home_dot_repo)
  218. except OSError, e:
  219. print >>sys.stderr, \
  220. 'fatal: cannot make %s directory: %s' % (
  221. home_dot_repo, e.strerror)
  222. sys.exit(1)
  223. if not os.path.isdir(gpg_dir):
  224. try:
  225. os.mkdir(gpg_dir, 0700)
  226. except OSError, e:
  227. print >>sys.stderr, \
  228. 'fatal: cannot make %s directory: %s' % (
  229. gpg_dir, e.strerror)
  230. sys.exit(1)
  231. env = os.environ.copy()
  232. env['GNUPGHOME'] = gpg_dir.encode()
  233. cmd = ['gpg', '--import']
  234. try:
  235. proc = subprocess.Popen(cmd,
  236. env = env,
  237. stdin = subprocess.PIPE)
  238. except OSError, e:
  239. if not quiet:
  240. print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
  241. print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
  242. print >>sys.stderr
  243. return False
  244. proc.stdin.write(MAINTAINER_KEYS)
  245. proc.stdin.close()
  246. if proc.wait() != 0:
  247. print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
  248. sys.exit(1)
  249. print
  250. fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
  251. fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
  252. fd.close()
  253. return True
  254. def _SetConfig(local, name, value):
  255. """Set a git configuration option to the specified value.
  256. """
  257. cmd = [GIT, 'config', name, value]
  258. if subprocess.Popen(cmd, cwd = local).wait() != 0:
  259. raise CloneFailure()
  260. def _InitHttp():
  261. handlers = []
  262. mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
  263. try:
  264. import netrc
  265. n = netrc.netrc()
  266. for host in n.hosts:
  267. p = n.hosts[host]
  268. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  269. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  270. except:
  271. pass
  272. handlers.append(urllib2.HTTPBasicAuthHandler(mgr))
  273. handlers.append(urllib2.HTTPDigestAuthHandler(mgr))
  274. if 'http_proxy' in os.environ:
  275. url = os.environ['http_proxy']
  276. handlers.append(urllib2.ProxyHandler({'http': url, 'https': url}))
  277. if 'REPO_CURL_VERBOSE' in os.environ:
  278. handlers.append(urllib2.HTTPHandler(debuglevel=1))
  279. handlers.append(urllib2.HTTPSHandler(debuglevel=1))
  280. urllib2.install_opener(urllib2.build_opener(*handlers))
  281. def _Fetch(url, local, src, quiet):
  282. if not quiet:
  283. print >>sys.stderr, 'Get %s' % url
  284. cmd = [GIT, 'fetch']
  285. if quiet:
  286. cmd.append('--quiet')
  287. err = subprocess.PIPE
  288. else:
  289. err = None
  290. cmd.append(src)
  291. cmd.append('+refs/heads/*:refs/remotes/origin/*')
  292. cmd.append('refs/tags/*:refs/tags/*')
  293. proc = subprocess.Popen(cmd, cwd = local, stderr = err)
  294. if err:
  295. proc.stderr.read()
  296. proc.stderr.close()
  297. if proc.wait() != 0:
  298. raise CloneFailure()
  299. def _DownloadBundle(url, local, quiet):
  300. if not url.endswith('/'):
  301. url += '/'
  302. url += 'clone.bundle'
  303. proc = subprocess.Popen(
  304. [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
  305. cwd = local,
  306. stdout = subprocess.PIPE)
  307. for line in proc.stdout:
  308. m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
  309. if m:
  310. new_url = m.group(1)
  311. old_url = m.group(2)
  312. if url.startswith(old_url):
  313. url = new_url + url[len(old_url):]
  314. break
  315. proc.stdout.close()
  316. proc.wait()
  317. if not url.startswith('http:') and not url.startswith('https:'):
  318. return False
  319. dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
  320. try:
  321. try:
  322. r = urllib2.urlopen(url)
  323. except urllib2.HTTPError, e:
  324. if e.code == 404:
  325. return False
  326. print >>sys.stderr, 'fatal: Cannot get %s' % url
  327. print >>sys.stderr, 'fatal: HTTP error %s' % e.code
  328. raise CloneFailure()
  329. except urllib2.URLError, e:
  330. print >>sys.stderr, 'fatal: Cannot get %s' % url
  331. print >>sys.stderr, 'fatal: error %s' % e.reason
  332. raise CloneFailure()
  333. try:
  334. if not quiet:
  335. print >>sys.stderr, 'Get %s' % url
  336. while True:
  337. buf = r.read(8192)
  338. if buf == '':
  339. return True
  340. dest.write(buf)
  341. finally:
  342. r.close()
  343. finally:
  344. dest.close()
  345. def _ImportBundle(local):
  346. path = os.path.join(local, '.git', 'clone.bundle')
  347. try:
  348. _Fetch(local, local, path, True)
  349. finally:
  350. os.remove(path)
  351. def _Clone(url, local, quiet):
  352. """Clones a git repository to a new subdirectory of repodir
  353. """
  354. try:
  355. os.mkdir(local)
  356. except OSError, e:
  357. print >>sys.stderr, \
  358. 'fatal: cannot make %s directory: %s' \
  359. % (local, e.strerror)
  360. raise CloneFailure()
  361. cmd = [GIT, 'init', '--quiet']
  362. try:
  363. proc = subprocess.Popen(cmd, cwd = local)
  364. except OSError, e:
  365. print >>sys.stderr
  366. print >>sys.stderr, "fatal: '%s' is not available" % GIT
  367. print >>sys.stderr, 'fatal: %s' % e
  368. print >>sys.stderr
  369. print >>sys.stderr, 'Please make sure %s is installed'\
  370. ' and in your path.' % GIT
  371. raise CloneFailure()
  372. if proc.wait() != 0:
  373. print >>sys.stderr, 'fatal: could not create %s' % local
  374. raise CloneFailure()
  375. _InitHttp()
  376. _SetConfig(local, 'remote.origin.url', url)
  377. _SetConfig(local, 'remote.origin.fetch',
  378. '+refs/heads/*:refs/remotes/origin/*')
  379. if _DownloadBundle(url, local, quiet):
  380. _ImportBundle(local)
  381. else:
  382. _Fetch(url, local, 'origin', quiet)
  383. def _Verify(cwd, branch, quiet):
  384. """Verify the branch has been signed by a tag.
  385. """
  386. cmd = [GIT, 'describe', 'origin/%s' % branch]
  387. proc = subprocess.Popen(cmd,
  388. stdout=subprocess.PIPE,
  389. stderr=subprocess.PIPE,
  390. cwd = cwd)
  391. cur = proc.stdout.read().strip()
  392. proc.stdout.close()
  393. proc.stderr.read()
  394. proc.stderr.close()
  395. if proc.wait() != 0 or not cur:
  396. print >>sys.stderr
  397. print >>sys.stderr,\
  398. "fatal: branch '%s' has not been signed" \
  399. % branch
  400. raise CloneFailure()
  401. m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
  402. if m:
  403. cur = m.group(1)
  404. if not quiet:
  405. print >>sys.stderr
  406. print >>sys.stderr, \
  407. "info: Ignoring branch '%s'; using tagged release '%s'" \
  408. % (branch, cur)
  409. print >>sys.stderr
  410. env = os.environ.copy()
  411. env['GNUPGHOME'] = gpg_dir.encode()
  412. cmd = [GIT, 'tag', '-v', cur]
  413. proc = subprocess.Popen(cmd,
  414. stdout = subprocess.PIPE,
  415. stderr = subprocess.PIPE,
  416. cwd = cwd,
  417. env = env)
  418. out = proc.stdout.read()
  419. proc.stdout.close()
  420. err = proc.stderr.read()
  421. proc.stderr.close()
  422. if proc.wait() != 0:
  423. print >>sys.stderr
  424. print >>sys.stderr, out
  425. print >>sys.stderr, err
  426. print >>sys.stderr
  427. raise CloneFailure()
  428. return '%s^0' % cur
  429. def _Checkout(cwd, branch, rev, quiet):
  430. """Checkout an upstream branch into the repository and track it.
  431. """
  432. cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
  433. if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
  434. raise CloneFailure()
  435. _SetConfig(cwd, 'branch.default.remote', 'origin')
  436. _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
  437. cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
  438. if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
  439. raise CloneFailure()
  440. cmd = [GIT, 'read-tree', '--reset', '-u']
  441. if not quiet:
  442. cmd.append('-v')
  443. cmd.append('HEAD')
  444. if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
  445. raise CloneFailure()
  446. def _FindRepo():
  447. """Look for a repo installation, starting at the current directory.
  448. """
  449. dir = os.getcwd()
  450. repo = None
  451. olddir = None
  452. while dir != '/' \
  453. and dir != olddir \
  454. and not repo:
  455. repo = os.path.join(dir, repodir, REPO_MAIN)
  456. if not os.path.isfile(repo):
  457. repo = None
  458. olddir = dir
  459. dir = os.path.dirname(dir)
  460. return (repo, os.path.join(dir, repodir))
  461. class _Options:
  462. help = False
  463. def _ParseArguments(args):
  464. cmd = None
  465. opt = _Options()
  466. arg = []
  467. for i in xrange(0, len(args)):
  468. a = args[i]
  469. if a == '-h' or a == '--help':
  470. opt.help = True
  471. elif not a.startswith('-'):
  472. cmd = a
  473. arg = args[i + 1:]
  474. break
  475. return cmd, opt, arg
  476. def _Usage():
  477. print >>sys.stderr,\
  478. """usage: repo COMMAND [ARGS]
  479. repo is not yet installed. Use "repo init" to install it here.
  480. The most commonly used repo commands are:
  481. init Install repo in the current working directory
  482. help Display detailed help on a command
  483. For access to the full online help, install repo ("repo init").
  484. """
  485. sys.exit(1)
  486. def _Help(args):
  487. if args:
  488. if args[0] == 'init':
  489. init_optparse.print_help()
  490. sys.exit(0)
  491. else:
  492. print >>sys.stderr,\
  493. "error: '%s' is not a bootstrap command.\n"\
  494. ' For access to online help, install repo ("repo init").'\
  495. % args[0]
  496. else:
  497. _Usage()
  498. sys.exit(1)
  499. def _NotInstalled():
  500. print >>sys.stderr,\
  501. 'error: repo is not installed. Use "repo init" to install it here.'
  502. sys.exit(1)
  503. def _NoCommands(cmd):
  504. print >>sys.stderr,\
  505. """error: command '%s' requires repo to be installed first.
  506. Use "repo init" to install it here.""" % cmd
  507. sys.exit(1)
  508. def _RunSelf(wrapper_path):
  509. my_dir = os.path.dirname(wrapper_path)
  510. my_main = os.path.join(my_dir, 'main.py')
  511. my_git = os.path.join(my_dir, '.git')
  512. if os.path.isfile(my_main) and os.path.isdir(my_git):
  513. for name in ['git_config.py',
  514. 'project.py',
  515. 'subcmds']:
  516. if not os.path.exists(os.path.join(my_dir, name)):
  517. return None, None
  518. return my_main, my_git
  519. return None, None
  520. def _SetDefaultsTo(gitdir):
  521. global REPO_URL
  522. global REPO_REV
  523. REPO_URL = gitdir
  524. proc = subprocess.Popen([GIT,
  525. '--git-dir=%s' % gitdir,
  526. 'symbolic-ref',
  527. 'HEAD'],
  528. stdout = subprocess.PIPE,
  529. stderr = subprocess.PIPE)
  530. REPO_REV = proc.stdout.read().strip()
  531. proc.stdout.close()
  532. proc.stderr.read()
  533. proc.stderr.close()
  534. if proc.wait() != 0:
  535. print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
  536. sys.exit(1)
  537. def main(orig_args):
  538. main, dir = _FindRepo()
  539. cmd, opt, args = _ParseArguments(orig_args)
  540. wrapper_path = os.path.abspath(__file__)
  541. my_main, my_git = _RunSelf(wrapper_path)
  542. if not main:
  543. if opt.help:
  544. _Usage()
  545. if cmd == 'help':
  546. _Help(args)
  547. if not cmd:
  548. _NotInstalled()
  549. if cmd == 'init':
  550. if my_git:
  551. _SetDefaultsTo(my_git)
  552. try:
  553. _Init(args)
  554. except CloneFailure:
  555. for root, dirs, files in os.walk(repodir, topdown=False):
  556. for name in files:
  557. os.remove(os.path.join(root, name))
  558. for name in dirs:
  559. os.rmdir(os.path.join(root, name))
  560. os.rmdir(repodir)
  561. sys.exit(1)
  562. main, dir = _FindRepo()
  563. else:
  564. _NoCommands(cmd)
  565. if my_main:
  566. main = my_main
  567. ver_str = '.'.join(map(lambda x: str(x), VERSION))
  568. me = [main,
  569. '--repo-dir=%s' % dir,
  570. '--wrapper-version=%s' % ver_str,
  571. '--wrapper-path=%s' % wrapper_path,
  572. '--']
  573. me.extend(orig_args)
  574. me.extend(extra_args)
  575. try:
  576. os.execv(main, me)
  577. except OSError, e:
  578. print >>sys.stderr, "fatal: unable to start %s" % main
  579. print >>sys.stderr, "fatal: %s" % e
  580. sys.exit(148)
  581. if __name__ == '__main__':
  582. main(sys.argv[1:])