repo 23 KB

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