repo 22 KB

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