repo 22 KB

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