repo 22 KB

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