repo 22 KB

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