repo 42 KB

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