repo 20 KB

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