repo 29 KB

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