repo_launcher 44 KB

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