repo 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. import datetime
  10. import os
  11. import platform
  12. import shlex
  13. import subprocess
  14. import sys
  15. # Keep basic logic in sync with repo_trace.py.
  16. class Trace(object):
  17. """Trace helper logic."""
  18. REPO_TRACE = 'REPO_TRACE'
  19. def __init__(self):
  20. self.set(os.environ.get(self.REPO_TRACE) == '1')
  21. def set(self, value):
  22. self.enabled = bool(value)
  23. def print(self, *args, **kwargs):
  24. if self.enabled:
  25. print(*args, **kwargs)
  26. trace = Trace()
  27. def exec_command(cmd):
  28. """Execute |cmd| or return None on failure."""
  29. trace.print(':', ' '.join(cmd))
  30. try:
  31. if platform.system() == 'Windows':
  32. ret = subprocess.call(cmd)
  33. sys.exit(ret)
  34. else:
  35. os.execvp(cmd[0], cmd)
  36. except Exception:
  37. pass
  38. def check_python_version():
  39. """Make sure the active Python version is recent enough."""
  40. def reexec(prog):
  41. exec_command([prog] + sys.argv)
  42. MIN_PYTHON_VERSION = (3, 6)
  43. ver = sys.version_info
  44. major = ver.major
  45. minor = ver.minor
  46. # Abort on very old Python 2 versions.
  47. if (major, minor) < (2, 7):
  48. print('repo: error: Your Python version is too old. '
  49. 'Please use Python {}.{} or newer instead.'.format(
  50. *MIN_PYTHON_VERSION), file=sys.stderr)
  51. sys.exit(1)
  52. # Try to re-exec the version specific Python 3 if needed.
  53. if (major, minor) < MIN_PYTHON_VERSION:
  54. # Python makes releases ~once a year, so try our min version +10 to help
  55. # bridge the gap. This is the fallback anyways so perf isn't critical.
  56. min_major, min_minor = MIN_PYTHON_VERSION
  57. for inc in range(0, 10):
  58. reexec('python{}.{}'.format(min_major, min_minor + inc))
  59. # Try the generic Python 3 wrapper, but only if it's new enough. We don't
  60. # want to go from (still supported) Python 2.7 to (unsupported) Python 3.5.
  61. try:
  62. proc = subprocess.Popen(
  63. ['python3', '-c', 'import sys; '
  64. 'print(sys.version_info.major, sys.version_info.minor)'],
  65. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  66. (output, _) = proc.communicate()
  67. python3_ver = tuple(int(x) for x in output.decode('utf-8').split())
  68. except (OSError, subprocess.CalledProcessError):
  69. python3_ver = None
  70. # The python3 version looks like it's new enough, so give it a try.
  71. if python3_ver and python3_ver >= MIN_PYTHON_VERSION:
  72. reexec('python3')
  73. # We're still here, so diagnose things for the user.
  74. if major < 3:
  75. print('repo: warning: Python 2 is no longer supported; '
  76. 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION),
  77. file=sys.stderr)
  78. else:
  79. print('repo: error: Python 3 version is too old; '
  80. 'Please use Python {}.{} or newer.'.format(*MIN_PYTHON_VERSION),
  81. file=sys.stderr)
  82. sys.exit(1)
  83. if __name__ == '__main__':
  84. check_python_version()
  85. # repo default configuration
  86. #
  87. REPO_URL = os.environ.get('REPO_URL', None)
  88. if not REPO_URL:
  89. REPO_URL = 'https://gerrit.googlesource.com/git-repo'
  90. REPO_REV = os.environ.get('REPO_REV')
  91. if not REPO_REV:
  92. REPO_REV = 'stable'
  93. # Copyright (C) 2008 Google Inc.
  94. #
  95. # Licensed under the Apache License, Version 2.0 (the "License");
  96. # you may not use this file except in compliance with the License.
  97. # You may obtain a copy of the License at
  98. #
  99. # http://www.apache.org/licenses/LICENSE-2.0
  100. #
  101. # Unless required by applicable law or agreed to in writing, software
  102. # distributed under the License is distributed on an "AS IS" BASIS,
  103. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  104. # See the License for the specific language governing permissions and
  105. # limitations under the License.
  106. # increment this whenever we make important changes to this script
  107. VERSION = (2, 4)
  108. # increment this if the MAINTAINER_KEYS block is modified
  109. KEYRING_VERSION = (2, 3)
  110. # Each individual key entry is created by using:
  111. # gpg --armor --export keyid
  112. MAINTAINER_KEYS = """
  113. Repo Maintainer <repo@android.kernel.org>
  114. -----BEGIN PGP PUBLIC KEY BLOCK-----
  115. mQGiBEj3ugERBACrLJh/ZPyVSKeClMuznFIrsQ+hpNnmJGw1a9GXKYKk8qHPhAZf
  116. WKtrBqAVMNRLhL85oSlekRz98u41H5si5zcuv+IXJDF5MJYcB8f22wAy15lUqPWi
  117. VCkk1l8qqLiuW0fo+ZkPY5qOgrvc0HW1SmdH649uNwqCbcKb6CxaTxzhOwCgj3AP
  118. xI1WfzLqdJjsm1Nq98L0cLcD/iNsILCuw44PRds3J75YP0pze7YF/6WFMB6QSFGu
  119. aUX1FsTTztKNXGms8i5b2l1B8JaLRWq/jOnZzyl1zrUJhkc0JgyZW5oNLGyWGhKD
  120. Fxp5YpHuIuMImopWEMFIRQNrvlg+YVK8t3FpdI1RY0LYqha8pPzANhEYgSfoVzOb
  121. fbfbA/4ioOrxy8ifSoga7ITyZMA+XbW8bx33WXutO9N7SPKS/AK2JpasSEVLZcON
  122. ae5hvAEGVXKxVPDjJBmIc2cOe7kOKSi3OxLzBqrjS2rnjiP4o0ekhZIe4+ocwVOg
  123. e0PLlH5avCqihGRhpoqDRsmpzSHzJIxtoeb+GgGEX8KkUsVAhbQpUmVwbyBNYWlu
  124. dGFpbmVyIDxyZXBvQGFuZHJvaWQua2VybmVsLm9yZz6IYAQTEQIAIAUCSPe6AQIb
  125. AwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEBZTDV6SD1xl1GEAn0x/OKQpy7qI
  126. 6G73NJviU0IUMtftAKCFMUhGb/0bZvQ8Rm3QCUpWHyEIu7kEDQRI97ogEBAA2wI6
  127. 5fs9y/rMwD6dkD/vK9v4C9mOn1IL5JCPYMJBVSci+9ED4ChzYvfq7wOcj9qIvaE0
  128. GwCt2ar7Q56me5J+byhSb32Rqsw/r3Vo5cZMH80N4cjesGuSXOGyEWTe4HYoxnHv
  129. gF4EKI2LK7xfTUcxMtlyn52sUpkfKsCpUhFvdmbAiJE+jCkQZr1Z8u2KphV79Ou+
  130. P1N5IXY/XWOlq48Qf4MWCYlJFrB07xjUjLKMPDNDnm58L5byDrP/eHysKexpbakL
  131. xCmYyfT6DV1SWLblpd2hie0sL3YejdtuBMYMS2rI7Yxb8kGuqkz+9l1qhwJtei94
  132. 5MaretDy/d/JH/pRYkRf7L+ke7dpzrP+aJmcz9P1e6gq4NJsWejaALVASBiioqNf
  133. QmtqSVzF1wkR5avZkFHuYvj6V/t1RrOZTXxkSk18KFMJRBZrdHFCWbc5qrVxUB6e
  134. N5pja0NFIUCigLBV1c6I2DwiuboMNh18VtJJh+nwWeez/RueN4ig59gRTtkcc0PR
  135. 35tX2DR8+xCCFVW/NcJ4PSePYzCuuLvp1vEDHnj41R52Fz51hgddT4rBsp0nL+5I
  136. socSOIIezw8T9vVzMY4ArCKFAVu2IVyBcahTfBS8q5EM63mONU6UVJEozfGljiMw
  137. xuQ7JwKcw0AUEKTKG7aBgBaTAgT8TOevpvlw91cAAwUP/jRkyVi/0WAb0qlEaq/S
  138. ouWxX1faR+vU3b+Y2/DGjtXQMzG0qpetaTHC/AxxHpgt/dCkWI6ljYDnxgPLwG0a
  139. Oasm94BjZc6vZwf1opFZUKsjOAAxRxNZyjUJKe4UZVuMTk6zo27Nt3LMnc0FO47v
  140. FcOjRyquvgNOS818irVHUf12waDx8gszKxQTTtFxU5/ePB2jZmhP6oXSe4K/LG5T
  141. +WBRPDrHiGPhCzJRzm9BP0lTnGCAj3o9W90STZa65RK7IaYpC8TB35JTBEbrrNCp
  142. w6lzd74LnNEp5eMlKDnXzUAgAH0yzCQeMl7t33QCdYx2hRs2wtTQSjGfAiNmj/WW
  143. Vl5Jn+2jCDnRLenKHwVRFsBX2e0BiRWt/i9Y8fjorLCXVj4z+7yW6DawdLkJorEo
  144. p3v5ILwfC7hVx4jHSnOgZ65L9s8EQdVr1ckN9243yta7rNgwfcqb60ILMFF1BRk/
  145. 0V7wCL+68UwwiQDvyMOQuqkysKLSDCLb7BFcyA7j6KG+5hpsREstFX2wK1yKeraz
  146. 5xGrFy8tfAaeBMIQ17gvFSp/suc9DYO0ICK2BISzq+F+ZiAKsjMYOBNdH/h0zobQ
  147. HTHs37+/QLMomGEGKZMWi0dShU2J5mNRQu3Hhxl3hHDVbt5CeJBb26aQcQrFz69W
  148. zE3GNvmJosh6leayjtI9P2A6iEkEGBECAAkFAkj3uiACGwwACgkQFlMNXpIPXGWp
  149. TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2uQIN
  150. BF5FqOoBEAC8aRtWEtXzeuoQhdFrLTqYs2dy6kl9y+j3DMQYAMs8je582qzUigIO
  151. ZZxq7T/3WQgghsdw9yPvdzlw9tKdet2TJkR1mtBfSjZQrkKwR0pQP4AD7t/90Whu
  152. R8Wlu8ysapE2hLxMH5Y2znRQX2LkUYmk0K2ik9AgZEh3AFEg3YLl2pGnSjeSp3ch
  153. cLX2n/rVZf5LXluZGRG+iov1Ka+8m+UqzohMA1DYNECJW6KPgXsNX++i8/iwZVic
  154. PWzhRJSQC+QiAZNsKT6HNNKs97YCUVzhjBLnRSxRBPkr0hS/VMWY2V4pbASljWyd
  155. GYmlDcxheLne0yjes0bJAdvig5rB42FOV0FCM4bDYOVwKfZ7SpzGCYXxtlwe0XNG
  156. tLW9WA6tICVqNZ/JNiRTBLrsGSkyrEhDPKnIHlHRI5Zux6IHwMVB0lQKHjSop+t6
  157. oyubqWcPCGGYdz2QGQHNz7huC/Zn0wS4hsoiSwPv6HCq3jNyUkOJ7wZ3ouv60p2I
  158. kPurgviVaRaPSKTYdKfkcJOtFeqOh1na5IHkXsD9rNctB7tSgfsm0G6qJIVe3ZmJ
  159. 7QAyHBfuLrAWCq5xS8EHDlvxPdAD8EEsa9T32YxcHKIkxr1eSwrUrKb8cPhWq1pp
  160. Jiylw6G1fZ02VKixqmPC4oFMyg1PO8L2tcQTrnVmZvfFGiaekHKdhQARAQABiQKW
  161. BBgRAgAgFiEEi7mteT6OYVOvD5pEFlMNXpIPXGUFAl5FqOoCGwICQAkQFlMNXpIP
  162. XGXBdCAEGQEKAB0WIQSjShO+jna/9GoMAi2i51qCSquWJAUCXkWo6gAKCRCi51qC
  163. SquWJLzgD/0YEZYS7yKxhP+kk94TcTYMBMSZpU5KFClB77yu4SI1LeXq4ocBT4sp
  164. EPaOsQiIx//j59J67b7CBe4UeRA6D2n0pw+bCKuc731DFi5X9C1zq3a7E67SQ2yd
  165. FbYE2fnpVnMqb62g4sTh7JmdxEtXCWBUWL0OEoWouBW1PkFDHx2kYLC7YpZt3+4t
  166. VtNhSfV8NS6PF8ep3JXHVd2wsC3DQtggeId5GM44o8N0SkwQHNjK8ZD+VZ74ZnhZ
  167. HeyHskomiOC61LrZWQvxD6VqtfnBQ5GvONO8QuhkiFwMMOnpPVj2k7ngSkd5o27K
  168. 6c53ZESOlR4bAfl0i3RZYC9B5KerGkBE3dTgTzmGjOaahl2eLz4LDPdTwMtS+sAU
  169. 1hPPvZTQeYDdV62bOWUyteMoJu354GgZPQ9eItWYixpNCyOGNcJXl6xk3/OuoP6f
  170. MciFV8aMxs/7mUR8q1Ei3X9MKu+bbODYj2rC1tMkLj1OaAJkfvRuYrKsQpoUsn4q
  171. VT9+aciNpU/I7M30watlWo7RfUFI3zaGdMDcMFju1cWt2Un8E3gtscGufzbz1Z5Z
  172. Gak+tCOWUyuYNWX3noit7Dk6+3JGHGaQettldNu2PLM9SbIXd2EaqK/eEv9BS3dd
  173. ItkZwzyZXSaQ9UqAceY1AHskJJ5KVXIRLuhP5jBWWo3fnRMyMYt2nwNBAJ9B9TA8
  174. VlBniwIl5EzCvOFOTGrtewCdHOvr3N3ieypGz1BzyCN9tJMO3G24MwReRal9Fgkr
  175. BgEEAdpHDwEBB0BhPE/je6OuKgWzJ1mnrUmHhn4IMOHp+58+T5kHU3Oy6YjXBBgR
  176. AgAgFiEEi7mteT6OYVOvD5pEFlMNXpIPXGUFAl5FqX0CGwIAgQkQFlMNXpIPXGV2
  177. IAQZFggAHRYhBOH5BA16P22vrIl809O5XaJD5Io5BQJeRal9AAoJENO5XaJD5Io5
  178. MEkA/3uLmiwANOcgE0zB9zga0T/KkYhYOWFx7zRyDhrTf9spAPwIfSBOAGtwxjLO
  179. DCce5OaQJl/YuGHvXq2yx5h7T8pdAZ+PAJ4qfIk2LLSidsplTDXOKhOQAuOqUQCf
  180. cZ7aFsJF4PtcDrfdejyAxbtsSHI=
  181. =82Tj
  182. -----END PGP PUBLIC KEY BLOCK-----
  183. """
  184. GIT = 'git' # our git command
  185. # NB: The version of git that the repo launcher requires may be much older than
  186. # the version of git that the main repo source tree requires. Keeping this at
  187. # an older version also makes it easier for users to upgrade/rollback as needed.
  188. #
  189. # git-1.7 is in (EOL) Ubuntu Precise.
  190. MIN_GIT_VERSION = (1, 7, 2) # minimum supported git version
  191. repodir = '.repo' # name of repo's private directory
  192. S_repo = 'repo' # special repo repository
  193. S_manifests = 'manifests' # special manifest repository
  194. REPO_MAIN = S_repo + '/main.py' # main script
  195. GITC_CONFIG_FILE = '/gitc/.config'
  196. GITC_FS_ROOT_DIR = '/gitc/manifest-rw/'
  197. import collections
  198. import errno
  199. import optparse
  200. import re
  201. import shutil
  202. import stat
  203. if sys.version_info[0] == 3:
  204. import urllib.request
  205. import urllib.error
  206. else:
  207. import imp
  208. import urllib2
  209. urllib = imp.new_module('urllib')
  210. urllib.request = urllib2
  211. urllib.error = urllib2
  212. home_dot_repo = os.path.expanduser('~/.repoconfig')
  213. gpg_dir = os.path.join(home_dot_repo, 'gnupg')
  214. extra_args = []
  215. def GetParser(gitc_init=False):
  216. """Setup the CLI parser."""
  217. if gitc_init:
  218. usage = 'repo gitc-init -u url -c client [options]'
  219. else:
  220. usage = 'repo init -u url [options]'
  221. parser = optparse.OptionParser(usage=usage)
  222. # Logging.
  223. group = parser.add_option_group('Logging options')
  224. group.add_option('-q', '--quiet',
  225. action='store_true', default=False,
  226. help='be quiet')
  227. # Manifest.
  228. group = parser.add_option_group('Manifest options')
  229. group.add_option('-u', '--manifest-url',
  230. help='manifest repository location', metavar='URL')
  231. group.add_option('-b', '--manifest-branch',
  232. help='manifest branch or revision', metavar='REVISION')
  233. group.add_option('-m', '--manifest-name',
  234. help='initial manifest file', metavar='NAME.xml')
  235. cbr_opts = ['--current-branch']
  236. # The gitc-init subcommand allocates -c itself, but a lot of init users
  237. # want -c, so try to satisfy both as best we can.
  238. if not gitc_init:
  239. cbr_opts += ['-c']
  240. group.add_option(*cbr_opts,
  241. dest='current_branch_only', action='store_true',
  242. help='fetch only current manifest branch from server')
  243. group.add_option('--mirror', action='store_true',
  244. help='create a replica of the remote repositories '
  245. 'rather than a client working directory')
  246. group.add_option('--reference',
  247. help='location of mirror directory', metavar='DIR')
  248. group.add_option('--dissociate', action='store_true',
  249. help='dissociate from reference mirrors after clone')
  250. group.add_option('--depth', type='int', default=None,
  251. help='create a shallow clone with given depth; '
  252. 'see git clone')
  253. group.add_option('--partial-clone', action='store_true',
  254. help='perform partial clone (https://git-scm.com/'
  255. 'docs/gitrepository-layout#_code_partialclone_code)')
  256. group.add_option('--clone-filter', action='store', default='blob:none',
  257. help='filter for use with --partial-clone '
  258. '[default: %default]')
  259. group.add_option('--worktree', action='store_true',
  260. help=optparse.SUPPRESS_HELP)
  261. group.add_option('--archive', action='store_true',
  262. help='checkout an archive instead of a git repository for '
  263. 'each project. See git archive.')
  264. group.add_option('--submodules', action='store_true',
  265. help='sync any submodules associated with the manifest repo')
  266. group.add_option('-g', '--groups', default='default',
  267. help='restrict manifest projects to ones with specified '
  268. 'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
  269. metavar='GROUP')
  270. group.add_option('-p', '--platform', default='auto',
  271. help='restrict manifest projects to ones with a specified '
  272. 'platform group [auto|all|none|linux|darwin|...]',
  273. metavar='PLATFORM')
  274. group.add_option('--no-clone-bundle',
  275. dest='clone_bundle', default=True, action='store_false',
  276. help='disable use of /clone.bundle on HTTP/HTTPS')
  277. group.add_option('--no-tags',
  278. dest='tags', default=True, action='store_false',
  279. help="don't fetch tags in the manifest")
  280. # Tool.
  281. group = parser.add_option_group('repo Version options')
  282. group.add_option('--repo-url', metavar='URL',
  283. help='repo repository location ($REPO_URL)')
  284. group.add_option('--repo-branch', metavar='REVISION',
  285. help='repo branch or revision ($REPO_REV)')
  286. group.add_option('--no-repo-verify',
  287. dest='repo_verify', default=True, action='store_false',
  288. help='do not verify repo source code')
  289. # Other.
  290. group = parser.add_option_group('Other options')
  291. group.add_option('--config-name',
  292. action='store_true', default=False,
  293. help='Always prompt for name/e-mail')
  294. # gitc-init specific settings.
  295. if gitc_init:
  296. group = parser.add_option_group('GITC options')
  297. group.add_option('-f', '--manifest-file',
  298. help='Optional manifest file to use for this GITC client.')
  299. group.add_option('-c', '--gitc-client',
  300. help='Name of the gitc_client instance to create or modify.')
  301. return parser
  302. # This is a poor replacement for subprocess.run until we require Python 3.6+.
  303. RunResult = collections.namedtuple(
  304. 'RunResult', ('returncode', 'stdout', 'stderr'))
  305. class RunError(Exception):
  306. """Error when running a command failed."""
  307. def run_command(cmd, **kwargs):
  308. """Run |cmd| and return its output."""
  309. check = kwargs.pop('check', False)
  310. if kwargs.pop('capture_output', False):
  311. kwargs.setdefault('stdout', subprocess.PIPE)
  312. kwargs.setdefault('stderr', subprocess.PIPE)
  313. cmd_input = kwargs.pop('input', None)
  314. def decode(output):
  315. """Decode |output| to text."""
  316. if output is None:
  317. return output
  318. try:
  319. return output.decode('utf-8')
  320. except UnicodeError:
  321. print('repo: warning: Invalid UTF-8 output:\ncmd: %r\n%r' % (cmd, output),
  322. file=sys.stderr)
  323. # TODO(vapier): Once we require Python 3, use 'backslashreplace'.
  324. return output.decode('utf-8', 'replace')
  325. # Run & package the results.
  326. proc = subprocess.Popen(cmd, **kwargs)
  327. (stdout, stderr) = proc.communicate(input=cmd_input)
  328. trace.print(':', ' '.join(cmd))
  329. ret = RunResult(proc.returncode, decode(stdout), decode(stderr))
  330. # If things failed, print useful debugging output.
  331. if check and ret.returncode:
  332. print('repo: error: "%s" failed with exit status %s' %
  333. (cmd[0], ret.returncode), file=sys.stderr)
  334. print(' cwd: %s\n cmd: %r' %
  335. (kwargs.get('cwd', os.getcwd()), cmd), file=sys.stderr)
  336. def _print_output(name, output):
  337. if output:
  338. print(' %s:\n >> %s' % (name, '\n >> '.join(output.splitlines())),
  339. file=sys.stderr)
  340. _print_output('stdout', ret.stdout)
  341. _print_output('stderr', ret.stderr)
  342. raise RunError(ret)
  343. return ret
  344. _gitc_manifest_dir = None
  345. def get_gitc_manifest_dir():
  346. global _gitc_manifest_dir
  347. if _gitc_manifest_dir is None:
  348. _gitc_manifest_dir = ''
  349. try:
  350. with open(GITC_CONFIG_FILE, 'r') as gitc_config:
  351. for line in gitc_config:
  352. match = re.match('gitc_dir=(?P<gitc_manifest_dir>.*)', line)
  353. if match:
  354. _gitc_manifest_dir = match.group('gitc_manifest_dir')
  355. except IOError:
  356. pass
  357. return _gitc_manifest_dir
  358. def gitc_parse_clientdir(gitc_fs_path):
  359. """Parse a path in the GITC FS and return its client name.
  360. @param gitc_fs_path: A subdirectory path within the GITC_FS_ROOT_DIR.
  361. @returns: The GITC client name
  362. """
  363. if gitc_fs_path == GITC_FS_ROOT_DIR:
  364. return None
  365. if not gitc_fs_path.startswith(GITC_FS_ROOT_DIR):
  366. manifest_dir = get_gitc_manifest_dir()
  367. if manifest_dir == '':
  368. return None
  369. if manifest_dir[-1] != '/':
  370. manifest_dir += '/'
  371. if gitc_fs_path == manifest_dir:
  372. return None
  373. if not gitc_fs_path.startswith(manifest_dir):
  374. return None
  375. return gitc_fs_path.split(manifest_dir)[1].split('/')[0]
  376. return gitc_fs_path.split(GITC_FS_ROOT_DIR)[1].split('/')[0]
  377. class CloneFailure(Exception):
  378. """Indicate the remote clone of repo itself failed.
  379. """
  380. def _Init(args, gitc_init=False):
  381. """Installs repo by cloning it over the network.
  382. """
  383. parser = GetParser(gitc_init=gitc_init)
  384. opt, args = parser.parse_args(args)
  385. if args:
  386. parser.print_usage()
  387. sys.exit(1)
  388. url = opt.repo_url
  389. if not url:
  390. url = REPO_URL
  391. extra_args.append('--repo-url=%s' % url)
  392. branch = opt.repo_branch
  393. if not branch:
  394. branch = REPO_REV
  395. extra_args.append('--repo-branch=%s' % branch)
  396. if branch.startswith('refs/heads/'):
  397. branch = branch[len('refs/heads/'):]
  398. if branch.startswith('refs/'):
  399. print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
  400. raise CloneFailure()
  401. try:
  402. if gitc_init:
  403. gitc_manifest_dir = get_gitc_manifest_dir()
  404. if not gitc_manifest_dir:
  405. print('fatal: GITC filesystem is not available. Exiting...',
  406. file=sys.stderr)
  407. sys.exit(1)
  408. gitc_client = opt.gitc_client
  409. if not gitc_client:
  410. gitc_client = gitc_parse_clientdir(os.getcwd())
  411. if not gitc_client:
  412. print('fatal: GITC client (-c) is required.', file=sys.stderr)
  413. sys.exit(1)
  414. client_dir = os.path.join(gitc_manifest_dir, gitc_client)
  415. if not os.path.exists(client_dir):
  416. os.makedirs(client_dir)
  417. os.chdir(client_dir)
  418. if os.path.exists(repodir):
  419. # This GITC Client has already initialized repo so continue.
  420. return
  421. os.mkdir(repodir)
  422. except OSError as e:
  423. if e.errno != errno.EEXIST:
  424. print('fatal: cannot make %s directory: %s'
  425. % (repodir, e.strerror), file=sys.stderr)
  426. # Don't raise CloneFailure; that would delete the
  427. # name. Instead exit immediately.
  428. #
  429. sys.exit(1)
  430. _CheckGitVersion()
  431. try:
  432. if not opt.repo_verify:
  433. do_verify = False
  434. else:
  435. if NeedSetupGnuPG():
  436. do_verify = SetupGnuPG(opt.quiet)
  437. else:
  438. do_verify = True
  439. dst = os.path.abspath(os.path.join(repodir, S_repo))
  440. _Clone(url, dst, opt.quiet, opt.clone_bundle)
  441. if do_verify:
  442. rev = _Verify(dst, branch, opt.quiet)
  443. else:
  444. rev = 'refs/remotes/origin/%s^0' % branch
  445. _Checkout(dst, branch, rev, opt.quiet)
  446. if not os.path.isfile(os.path.join(dst, 'repo')):
  447. print("warning: '%s' does not look like a git-repo repository, is "
  448. "REPO_URL set correctly?" % url, file=sys.stderr)
  449. except CloneFailure:
  450. if opt.quiet:
  451. print('fatal: repo init failed; run without --quiet to see why',
  452. file=sys.stderr)
  453. raise
  454. def run_git(*args, **kwargs):
  455. """Run git and return execution details."""
  456. kwargs.setdefault('capture_output', True)
  457. kwargs.setdefault('check', True)
  458. try:
  459. return run_command([GIT] + list(args), **kwargs)
  460. except OSError as e:
  461. print(file=sys.stderr)
  462. print('repo: error: "%s" is not available' % GIT, file=sys.stderr)
  463. print('repo: error: %s' % e, file=sys.stderr)
  464. print(file=sys.stderr)
  465. print('Please make sure %s is installed and in your path.' % GIT,
  466. file=sys.stderr)
  467. sys.exit(1)
  468. except RunError:
  469. raise CloneFailure()
  470. # The git version info broken down into components for easy analysis.
  471. # Similar to Python's sys.version_info.
  472. GitVersion = collections.namedtuple(
  473. 'GitVersion', ('major', 'minor', 'micro', 'full'))
  474. def ParseGitVersion(ver_str=None):
  475. if ver_str is None:
  476. # Load the version ourselves.
  477. ver_str = run_git('--version').stdout
  478. if not ver_str.startswith('git version '):
  479. return None
  480. full_version = ver_str[len('git version '):].strip()
  481. num_ver_str = full_version.split('-')[0]
  482. to_tuple = []
  483. for num_str in num_ver_str.split('.')[:3]:
  484. if num_str.isdigit():
  485. to_tuple.append(int(num_str))
  486. else:
  487. to_tuple.append(0)
  488. to_tuple.append(full_version)
  489. return GitVersion(*to_tuple)
  490. def _CheckGitVersion():
  491. ver_act = ParseGitVersion()
  492. if ver_act is None:
  493. print('fatal: unable to detect git version', file=sys.stderr)
  494. raise CloneFailure()
  495. if ver_act < MIN_GIT_VERSION:
  496. need = '.'.join(map(str, MIN_GIT_VERSION))
  497. print('fatal: git %s or later required' % need, file=sys.stderr)
  498. raise CloneFailure()
  499. def SetGitTrace2ParentSid(env=None):
  500. """Set up GIT_TRACE2_PARENT_SID for git tracing."""
  501. # We roughly follow the format git itself uses in trace2/tr2_sid.c.
  502. # (1) Be unique (2) be valid filename (3) be fixed length.
  503. #
  504. # Since we always export this variable, we try to avoid more expensive calls.
  505. # e.g. We don't attempt hostname lookups or hashing the results.
  506. if env is None:
  507. env = os.environ
  508. KEY = 'GIT_TRACE2_PARENT_SID'
  509. now = datetime.datetime.utcnow()
  510. value = 'repo-%s-P%08x' % (now.strftime('%Y%m%dT%H%M%SZ'), os.getpid())
  511. # If it's already set, then append ourselves.
  512. if KEY in env:
  513. value = env[KEY] + '/' + value
  514. _setenv(KEY, value, env=env)
  515. def _setenv(key, value, env=None):
  516. """Set |key| in the OS environment |env| to |value|."""
  517. if env is None:
  518. env = os.environ
  519. # Environment handling across systems is messy.
  520. try:
  521. env[key] = value
  522. except UnicodeEncodeError:
  523. env[key] = value.encode()
  524. def NeedSetupGnuPG():
  525. if not os.path.isdir(home_dot_repo):
  526. return True
  527. kv = os.path.join(home_dot_repo, 'keyring-version')
  528. if not os.path.exists(kv):
  529. return True
  530. kv = open(kv).read()
  531. if not kv:
  532. return True
  533. kv = tuple(map(int, kv.split('.')))
  534. if kv < KEYRING_VERSION:
  535. return True
  536. return False
  537. def SetupGnuPG(quiet):
  538. try:
  539. os.mkdir(home_dot_repo)
  540. except OSError as e:
  541. if e.errno != errno.EEXIST:
  542. print('fatal: cannot make %s directory: %s'
  543. % (home_dot_repo, e.strerror), file=sys.stderr)
  544. sys.exit(1)
  545. try:
  546. os.mkdir(gpg_dir, stat.S_IRWXU)
  547. except OSError as e:
  548. if e.errno != errno.EEXIST:
  549. print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
  550. file=sys.stderr)
  551. sys.exit(1)
  552. if not quiet:
  553. print('repo: Updating release signing keys to keyset ver %s' %
  554. ('.'.join(str(x) for x in KEYRING_VERSION),))
  555. # NB: We use --homedir (and cwd below) because some environments (Windows) do
  556. # not correctly handle full native paths. We avoid the issue by changing to
  557. # the right dir with cwd=gpg_dir before executing gpg, and then telling gpg to
  558. # use the cwd (.) as its homedir which leaves the path resolution logic to it.
  559. cmd = ['gpg', '--homedir', '.', '--import']
  560. try:
  561. # gpg can be pretty chatty. Always capture the output and if something goes
  562. # wrong, the builtin check failure will dump stdout & stderr for debugging.
  563. run_command(cmd, stdin=subprocess.PIPE, capture_output=True,
  564. cwd=gpg_dir, check=True,
  565. input=MAINTAINER_KEYS.encode('utf-8'))
  566. except OSError:
  567. if not quiet:
  568. print('warning: gpg (GnuPG) is not available.', file=sys.stderr)
  569. print('warning: Installing it is strongly encouraged.', file=sys.stderr)
  570. print(file=sys.stderr)
  571. return False
  572. with open(os.path.join(home_dot_repo, 'keyring-version'), 'w') as fd:
  573. fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
  574. return True
  575. def _SetConfig(cwd, name, value):
  576. """Set a git configuration option to the specified value.
  577. """
  578. run_git('config', name, value, cwd=cwd)
  579. def _GetRepoConfig(name):
  580. """Read a repo configuration option."""
  581. config = os.path.join(home_dot_repo, 'config')
  582. if not os.path.exists(config):
  583. return None
  584. cmd = ['config', '--file', config, '--get', name]
  585. ret = run_git(*cmd, check=False)
  586. if ret.returncode == 0:
  587. return ret.stdout
  588. elif ret.returncode == 1:
  589. return None
  590. else:
  591. print('repo: error: git %s failed:\n%s' % (' '.join(cmd), ret.stderr),
  592. file=sys.stderr)
  593. raise RunError()
  594. def _InitHttp():
  595. handlers = []
  596. mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  597. try:
  598. import netrc
  599. n = netrc.netrc()
  600. for host in n.hosts:
  601. p = n.hosts[host]
  602. mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
  603. mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
  604. except Exception:
  605. pass
  606. handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
  607. handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))
  608. if 'http_proxy' in os.environ:
  609. url = os.environ['http_proxy']
  610. handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
  611. if 'REPO_CURL_VERBOSE' in os.environ:
  612. handlers.append(urllib.request.HTTPHandler(debuglevel=1))
  613. handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
  614. urllib.request.install_opener(urllib.request.build_opener(*handlers))
  615. def _Fetch(url, cwd, src, quiet):
  616. if not quiet:
  617. print('Get %s' % url, file=sys.stderr)
  618. cmd = ['fetch']
  619. if quiet:
  620. cmd.append('--quiet')
  621. err = subprocess.PIPE
  622. else:
  623. err = None
  624. cmd.append(src)
  625. cmd.append('+refs/heads/*:refs/remotes/origin/*')
  626. cmd.append('+refs/tags/*:refs/tags/*')
  627. run_git(*cmd, stderr=err, cwd=cwd)
  628. def _DownloadBundle(url, cwd, quiet):
  629. if not url.endswith('/'):
  630. url += '/'
  631. url += 'clone.bundle'
  632. ret = run_git('config', '--get-regexp', 'url.*.insteadof', cwd=cwd,
  633. check=False)
  634. for line in ret.stdout.splitlines():
  635. m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
  636. if m:
  637. new_url = m.group(1)
  638. old_url = m.group(2)
  639. if url.startswith(old_url):
  640. url = new_url + url[len(old_url):]
  641. break
  642. if not url.startswith('http:') and not url.startswith('https:'):
  643. return False
  644. dest = open(os.path.join(cwd, '.git', 'clone.bundle'), 'w+b')
  645. try:
  646. try:
  647. r = urllib.request.urlopen(url)
  648. except urllib.error.HTTPError as e:
  649. if e.code in [401, 403, 404, 501]:
  650. return False
  651. print('fatal: Cannot get %s' % url, file=sys.stderr)
  652. print('fatal: HTTP error %s' % e.code, file=sys.stderr)
  653. raise CloneFailure()
  654. except urllib.error.URLError as e:
  655. print('fatal: Cannot get %s' % url, file=sys.stderr)
  656. print('fatal: error %s' % e.reason, file=sys.stderr)
  657. raise CloneFailure()
  658. try:
  659. if not quiet:
  660. print('Get %s' % url, file=sys.stderr)
  661. while True:
  662. buf = r.read(8192)
  663. if not buf:
  664. return True
  665. dest.write(buf)
  666. finally:
  667. r.close()
  668. finally:
  669. dest.close()
  670. def _ImportBundle(cwd):
  671. path = os.path.join(cwd, '.git', 'clone.bundle')
  672. try:
  673. _Fetch(cwd, cwd, path, True)
  674. finally:
  675. os.remove(path)
  676. def _Clone(url, cwd, quiet, clone_bundle):
  677. """Clones a git repository to a new subdirectory of repodir
  678. """
  679. try:
  680. os.mkdir(cwd)
  681. except OSError as e:
  682. print('fatal: cannot make %s directory: %s' % (cwd, e.strerror),
  683. file=sys.stderr)
  684. raise CloneFailure()
  685. run_git('init', '--quiet', cwd=cwd)
  686. _InitHttp()
  687. _SetConfig(cwd, 'remote.origin.url', url)
  688. _SetConfig(cwd,
  689. 'remote.origin.fetch',
  690. '+refs/heads/*:refs/remotes/origin/*')
  691. if clone_bundle and _DownloadBundle(url, cwd, quiet):
  692. _ImportBundle(cwd)
  693. _Fetch(url, cwd, 'origin', quiet)
  694. def _Verify(cwd, branch, quiet):
  695. """Verify the branch has been signed by a tag.
  696. """
  697. try:
  698. ret = run_git('describe', 'origin/%s' % branch, cwd=cwd)
  699. cur = ret.stdout.strip()
  700. except CloneFailure:
  701. print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
  702. raise
  703. m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
  704. if m:
  705. cur = m.group(1)
  706. if not quiet:
  707. print(file=sys.stderr)
  708. print("info: Ignoring branch '%s'; using tagged release '%s'"
  709. % (branch, cur), file=sys.stderr)
  710. print(file=sys.stderr)
  711. env = os.environ.copy()
  712. _setenv('GNUPGHOME', gpg_dir, env)
  713. run_git('tag', '-v', cur, cwd=cwd, env=env)
  714. return '%s^0' % cur
  715. def _Checkout(cwd, branch, rev, quiet):
  716. """Checkout an upstream branch into the repository and track it.
  717. """
  718. run_git('update-ref', 'refs/heads/default', rev, cwd=cwd)
  719. _SetConfig(cwd, 'branch.default.remote', 'origin')
  720. _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
  721. run_git('symbolic-ref', 'HEAD', 'refs/heads/default', cwd=cwd)
  722. cmd = ['read-tree', '--reset', '-u']
  723. if not quiet:
  724. cmd.append('-v')
  725. cmd.append('HEAD')
  726. run_git(*cmd, cwd=cwd)
  727. def _FindRepo():
  728. """Look for a repo installation, starting at the current directory.
  729. """
  730. curdir = os.getcwd()
  731. repo = None
  732. olddir = None
  733. while curdir != '/' \
  734. and curdir != olddir \
  735. and not repo:
  736. repo = os.path.join(curdir, repodir, REPO_MAIN)
  737. if not os.path.isfile(repo):
  738. repo = None
  739. olddir = curdir
  740. curdir = os.path.dirname(curdir)
  741. return (repo, os.path.join(curdir, repodir))
  742. class _Options(object):
  743. help = False
  744. version = False
  745. def _ExpandAlias(name):
  746. """Look up user registered aliases."""
  747. # We don't resolve aliases for existing subcommands. This matches git.
  748. if name in {'gitc-init', 'help', 'init'}:
  749. return name, []
  750. alias = _GetRepoConfig('alias.%s' % (name,))
  751. if alias is None:
  752. return name, []
  753. args = alias.strip().split(' ', 1)
  754. name = args[0]
  755. if len(args) == 2:
  756. args = shlex.split(args[1])
  757. else:
  758. args = []
  759. return name, args
  760. def _ParseArguments(args):
  761. cmd = None
  762. opt = _Options()
  763. arg = []
  764. for i in range(len(args)):
  765. a = args[i]
  766. if a == '-h' or a == '--help':
  767. opt.help = True
  768. elif a == '--version':
  769. opt.version = True
  770. elif a == '--trace':
  771. trace.set(True)
  772. elif not a.startswith('-'):
  773. cmd = a
  774. arg = args[i + 1:]
  775. break
  776. return cmd, opt, arg
  777. def _Usage():
  778. gitc_usage = ""
  779. if get_gitc_manifest_dir():
  780. gitc_usage = " gitc-init Initialize a GITC Client.\n"
  781. print(
  782. """usage: repo COMMAND [ARGS]
  783. repo is not yet installed. Use "repo init" to install it here.
  784. The most commonly used repo commands are:
  785. init Install repo in the current working directory
  786. """ + gitc_usage +
  787. """ help Display detailed help on a command
  788. For access to the full online help, install repo ("repo init").
  789. """)
  790. sys.exit(0)
  791. def _Help(args):
  792. if args:
  793. if args[0] in {'init', 'gitc-init'}:
  794. parser = GetParser(gitc_init=args[0] == 'gitc-init')
  795. parser.print_help()
  796. sys.exit(0)
  797. else:
  798. print("error: '%s' is not a bootstrap command.\n"
  799. ' For access to online help, install repo ("repo init").'
  800. % args[0], file=sys.stderr)
  801. else:
  802. _Usage()
  803. sys.exit(1)
  804. def _Version():
  805. """Show version information."""
  806. print('<repo not installed>')
  807. print('repo launcher version %s' % ('.'.join(str(x) for x in VERSION),))
  808. print(' (from %s)' % (__file__,))
  809. print('git %s' % (ParseGitVersion().full,))
  810. print('Python %s' % sys.version)
  811. sys.exit(0)
  812. def _NotInstalled():
  813. print('error: repo is not installed. Use "repo init" to install it here.',
  814. file=sys.stderr)
  815. sys.exit(1)
  816. def _NoCommands(cmd):
  817. print("""error: command '%s' requires repo to be installed first.
  818. Use "repo init" to install it here.""" % cmd, file=sys.stderr)
  819. sys.exit(1)
  820. def _RunSelf(wrapper_path):
  821. my_dir = os.path.dirname(wrapper_path)
  822. my_main = os.path.join(my_dir, 'main.py')
  823. my_git = os.path.join(my_dir, '.git')
  824. if os.path.isfile(my_main) and os.path.isdir(my_git):
  825. for name in ['git_config.py',
  826. 'project.py',
  827. 'subcmds']:
  828. if not os.path.exists(os.path.join(my_dir, name)):
  829. return None, None
  830. return my_main, my_git
  831. return None, None
  832. def _SetDefaultsTo(gitdir):
  833. global REPO_URL
  834. global REPO_REV
  835. REPO_URL = gitdir
  836. try:
  837. ret = run_git('--git-dir=%s' % gitdir, 'symbolic-ref', 'HEAD')
  838. REPO_REV = ret.stdout.strip()
  839. except CloneFailure:
  840. print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
  841. sys.exit(1)
  842. def main(orig_args):
  843. cmd, opt, args = _ParseArguments(orig_args)
  844. # We run this early as we run some git commands ourselves.
  845. SetGitTrace2ParentSid()
  846. repo_main, rel_repo_dir = None, None
  847. # Don't use the local repo copy, make sure to switch to the gitc client first.
  848. if cmd != 'gitc-init':
  849. repo_main, rel_repo_dir = _FindRepo()
  850. wrapper_path = os.path.abspath(__file__)
  851. my_main, my_git = _RunSelf(wrapper_path)
  852. cwd = os.getcwd()
  853. if get_gitc_manifest_dir() and cwd.startswith(get_gitc_manifest_dir()):
  854. print('error: repo cannot be used in the GITC local manifest directory.'
  855. '\nIf you want to work on this GITC client please rerun this '
  856. 'command from the corresponding client under /gitc/',
  857. file=sys.stderr)
  858. sys.exit(1)
  859. if not repo_main:
  860. # Only expand aliases here since we'll be parsing the CLI ourselves.
  861. # If we had repo_main, alias expansion would happen in main.py.
  862. cmd, alias_args = _ExpandAlias(cmd)
  863. args = alias_args + args
  864. if opt.help:
  865. _Usage()
  866. if cmd == 'help':
  867. _Help(args)
  868. if opt.version or cmd == 'version':
  869. _Version()
  870. if not cmd:
  871. _NotInstalled()
  872. if cmd == 'init' or cmd == 'gitc-init':
  873. if my_git:
  874. _SetDefaultsTo(my_git)
  875. try:
  876. _Init(args, gitc_init=(cmd == 'gitc-init'))
  877. except CloneFailure:
  878. path = os.path.join(repodir, S_repo)
  879. print("fatal: cloning the git-repo repository failed, will remove "
  880. "'%s' " % path, file=sys.stderr)
  881. shutil.rmtree(path, ignore_errors=True)
  882. sys.exit(1)
  883. repo_main, rel_repo_dir = _FindRepo()
  884. else:
  885. _NoCommands(cmd)
  886. if my_main:
  887. repo_main = my_main
  888. ver_str = '.'.join(map(str, VERSION))
  889. me = [sys.executable, repo_main,
  890. '--repo-dir=%s' % rel_repo_dir,
  891. '--wrapper-version=%s' % ver_str,
  892. '--wrapper-path=%s' % wrapper_path,
  893. '--']
  894. me.extend(orig_args)
  895. me.extend(extra_args)
  896. exec_command(me)
  897. print("fatal: unable to start %s" % repo_main, file=sys.stderr)
  898. sys.exit(148)
  899. if __name__ == '__main__':
  900. main(sys.argv[1:])