repo 23 KB

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