repo 29 KB

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