scripts_utils.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. """Utilities for scripts."""
  2. __copyright__ = """
  3. Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  4. Exceptions. See /LICENSE for license information.
  5. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. """
  7. from enum import Enum
  8. import fcntl
  9. import hashlib
  10. import os
  11. from pathlib import Path
  12. import platform
  13. import shutil
  14. import time
  15. from typing import Dict, Optional
  16. import urllib.request
  17. _BAZEL_TOOLS_URL = (
  18. "https://github.com/bazelbuild/buildtools/releases/download/v6.3.3/"
  19. )
  20. """Version SHAs.
  21. Gather shas with:
  22. for f in buildozer buildifier; do
  23. echo \"$f\": {
  24. for v in darwin-amd64 darwin-arm64 linux-amd64 linux-arm64 \
  25. windows-amd64.exe
  26. do
  27. echo "\"$v\": \"$(wget -q -O - https://github.com/bazelbuild/buildtools/releases/download/v6.3.3/$f-$v | sha256sum | cut -d ' ' -f1)\", # noqa: E501"
  28. done
  29. echo },
  30. done
  31. """
  32. _BAZEL_TOOLS_VERSION_SHAS = {
  33. "buildozer": {
  34. "darwin-amd64": "9b0bbecb3745250e5ad5a9c36da456699cb55e52999451c3c74047d2b1f0085f", # noqa: E501
  35. "darwin-arm64": "085928dd4deffa1a7fd38c66c4475e37326b2d4942408e8e3d993953ae4c626c", # noqa: E501
  36. "linux-amd64": "1dcdc668d7c775e5bca2d43ac37e036468ca4d139a78fe48ae207d41411c5100", # noqa: E501
  37. "linux-arm64": "94b96d6a3c52d6ef416f0eb96c8a9fe7f6a0757f0458cc8cf190dfc4a5c2d8e7", # noqa: E501
  38. "windows-amd64.exe": "fc1c4f5de391ec6d66f2119c5bd6131d572ae35e92ddffe720e42b619ab158e0", # noqa: E501
  39. },
  40. "buildifier": {
  41. "darwin-amd64": "3c36a3217bd793815a907a8e5bf81c291e2d35d73c6073914640a5f42e65f73f", # noqa: E501
  42. "darwin-arm64": "9bb366432d515814766afcf6f9010294c13876686fbbe585d5d6b4ff0ca3e982", # noqa: E501
  43. "linux-amd64": "42f798ec532c58e34401985043e660cb19d5ae994e108d19298c7d229547ffca", # noqa: E501
  44. "linux-arm64": "6a03a1cf525045cb686fc67cd5d64cface5092ebefca3c4c93fb6e97c64e07db", # noqa: E501
  45. "windows-amd64.exe": "2761bebc7392d47c2862c43d85201d93efa57249ed09405fd82708867caa787b", # noqa: E501
  46. },
  47. }
  48. _TARGET_DETERMINATOR_URL = "https://github.com/bazel-contrib/target-determinator/releases/download/v0.23.0/" # noqa: E501
  49. """Version SHAs.
  50. Gather shas with:
  51. for v in darwin.amd64 darwin.arm64 linux.amd64 linux.arm64 \
  52. windows.amd64.exe
  53. do
  54. echo "\"$v\": \"$(wget -q -O - https://github.com/bazel-contrib/target-determinator/releases/download/v0.23.0/target-determinator.$v | sha256sum | cut -d ' ' -f1)\", # noqa: E501"
  55. done
  56. """
  57. _TARGET_DETERMINATOR_SHAS = {
  58. "darwin.amd64": "aba6dce8a978d2174b37dd1355eecba86db93be1ff77742d0753d8efd6a8a316", # noqa: E501
  59. "darwin.arm64": "6c3c308dcfc651408ed5490245ea3e0180fc49d4cc9b762ab84a4b979bcb07b8", # noqa: E501
  60. "linux.amd64": "5200dbca0dd4980690d5060cf8e04abac927efaca143567c51fe24cf973364d2", # noqa: E501
  61. "linux.arm64": "3c04f8bb2742219eb3415c6d675dcfe9175745eb7b1d6c3706085a9987f9f719", # noqa: E501
  62. "windows.amd64.exe": "3aea5bd52fdf29bfe6995ffcacc2b2c2299af02dc58f1039022ff758b58214c3", # noqa: E501
  63. }
  64. class Release(Enum):
  65. BUILDOZER = "buildozer"
  66. BUILDIFIER = "buildifier"
  67. def chdir_repo_root() -> None:
  68. """Change the working directory to the repository root.
  69. This is done so that scripts run from a consistent directory.
  70. """
  71. os.chdir(Path(__file__).parent.parent)
  72. def _get_hash(file: Path) -> str:
  73. """Returns the sha256 of a file."""
  74. digest = hashlib.sha256()
  75. with file.open("rb") as f:
  76. while True:
  77. chunk = f.read(1024 * 64)
  78. if not chunk:
  79. break
  80. digest.update(chunk)
  81. return digest.hexdigest()
  82. def _download(url: str, local_path: Path) -> Optional[int]:
  83. """Downloads the URL to the path. Returns an HTTP error code on failure."""
  84. with urllib.request.urlopen(url) as response:
  85. if response.code != 200:
  86. return int(response.code)
  87. with local_path.open("wb") as f:
  88. shutil.copyfileobj(response, f)
  89. return None
  90. def _get_cached_binary(name: str, url: str, want_hash: str) -> str:
  91. cache_dir = Path.home().joinpath(".cache", "carbon-lang-scripts")
  92. cache_dir.mkdir(parents=True, exist_ok=True)
  93. # Hold a lock while checksumming and downloading the path. Otherwise,
  94. # parallel runs by pre-commit may conflict with one another with
  95. # simultaneous downloads.
  96. with open(cache_dir.joinpath(f"{name}.lock"), "w") as lock_file:
  97. fcntl.lockf(lock_file.fileno(), fcntl.LOCK_EX)
  98. # Check if there's a cached file that can be used.
  99. local_path = cache_dir.joinpath(name)
  100. if local_path.is_file() and want_hash == _get_hash(local_path):
  101. return str(local_path)
  102. # Download the file.
  103. retries = 5
  104. while True:
  105. err = _download(url, local_path)
  106. if err is None:
  107. break
  108. retries -= 1
  109. if retries == 0:
  110. exit(f"Failed to download {url}: HTTP {err}.")
  111. time.sleep(1)
  112. local_path.chmod(0o755)
  113. # Verify the downloaded hash.
  114. found_hash = _get_hash(local_path)
  115. if want_hash != found_hash:
  116. exit(
  117. f"Downloaded {url} but found sha256 "
  118. f"{found_hash} ({local_path.stat().st_size} bytes), wanted "
  119. f"{want_hash}"
  120. )
  121. return str(local_path)
  122. def _get_machine() -> str:
  123. machine = platform.machine()
  124. if machine == "x86_64":
  125. machine = "amd64"
  126. elif machine == "aarch64":
  127. machine = "arm64"
  128. return machine
  129. def _get_platform_ext() -> str:
  130. if platform.system() == "Windows":
  131. return ".exe"
  132. else:
  133. return ""
  134. def _select_hash(hashes: Dict[str, str], version: str) -> str:
  135. # Ensure the platform version is supported and has a hash.
  136. if version not in hashes:
  137. # If this because a platform support issue, we may need to print errors.
  138. exit(f"No release available for platform: {version}")
  139. return hashes[version]
  140. def get_target_determinator() -> str:
  141. """Install the Bazel target-determinator tool to carbon-lang's cache."""
  142. # Translate platform information into this tool's release binary form.
  143. version = f"{platform.system().lower()}.{_get_machine()}"
  144. ext = _get_platform_ext()
  145. url = f"{_TARGET_DETERMINATOR_URL}/target-determinator.{version}{ext}"
  146. want_hash = _select_hash(_TARGET_DETERMINATOR_SHAS, version)
  147. return _get_cached_binary(f"target-determinator{ext}", url, want_hash)
  148. def get_release(release: Release) -> str:
  149. """Install a Bazel-released tool to carbon-lang's cache.
  150. release: The release to cache.
  151. """
  152. # Translate platform information into Bazel's release form.
  153. version = f"{platform.system().lower()}-{_get_machine()}"
  154. ext = _get_platform_ext()
  155. url = f"{_BAZEL_TOOLS_URL}/{release.value}-{version}{ext}"
  156. want_hash = _select_hash(_BAZEL_TOOLS_VERSION_SHAS[release.value], version)
  157. return _get_cached_binary(f"{release.value}{ext}", url, want_hash)
  158. def locate_bazel() -> str:
  159. """Returns the bazel command.
  160. We use the `BAZEL` environment variable if present. If not, then we try to
  161. use `bazelisk` and then `bazel`.
  162. """
  163. bazel = os.environ.get("BAZEL")
  164. if bazel:
  165. return bazel
  166. for cmd in ("bazelisk", "bazel"):
  167. target = shutil.which(cmd)
  168. if target:
  169. return target
  170. exit("Unable to run Bazel")