repo 23 KB

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