scripts_utils.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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 tempfile
  15. import time
  16. from typing import NamedTuple, Optional
  17. import urllib.request
  18. # The tools we track releases for.
  19. class Release(Enum):
  20. BUILDIFIER = "buildifier"
  21. BUILDOZER = "buildozer"
  22. TARGET_DETERMINATOR = "target-determinator"
  23. class ReleaseInfo(NamedTuple):
  24. # The base URL for downloads. Should include the version.
  25. url: str
  26. # The separator in a binary's name, either `-` or `.`.
  27. separator: str
  28. _BAZEL_TOOLS_URL = (
  29. "https://github.com/bazelbuild/buildtools/releases/download/v7.1.2/"
  30. )
  31. # Structured information per release tool.
  32. _RELEASES = {
  33. Release.BUILDIFIER: ReleaseInfo(_BAZEL_TOOLS_URL, "-"),
  34. Release.BUILDOZER: ReleaseInfo(_BAZEL_TOOLS_URL, "-"),
  35. Release.TARGET_DETERMINATOR: ReleaseInfo(
  36. "https://github.com/bazel-contrib/target-determinator/releases/download/v0.27.0/", # noqa: E501
  37. ".",
  38. ),
  39. }
  40. # Shas for the tools.
  41. #
  42. # To update, change the version in a tool's URL and use
  43. # `calculate_release_shas.py`. This is maintained separate from _RELEASES just
  44. # to make copy-paste updates simpler.
  45. _RELEASE_SHAS = {
  46. Release.BUILDIFIER: {
  47. "darwin-amd64": "687c49c318fb655970cf716eed3c7bfc9caeea4f2931a2fd36593c458de0c537", # noqa: E501
  48. "darwin-arm64": "d0909b645496608fd6dfc67f95d9d3b01d90736d7b8c8ec41e802cb0b7ceae7c", # noqa: E501
  49. "linux-amd64": "28285fe7e39ed23dc1a3a525dfcdccbc96c0034ff1d4277905d2672a71b38f13", # noqa: E501
  50. "linux-arm64": "c22a44eee37b8927167ee6ee67573303f4e31171e7ec3a8ea021a6a660040437", # noqa: E501
  51. "windows-amd64.exe": "a8331515019d8d3e01baa1c76fda19e8e6e3e05532d4b0bce759bd759d0cafb7", # noqa: E501
  52. },
  53. Release.BUILDOZER: {
  54. "darwin-amd64": "90da5cf4f7db73007977a8c6bec23fa7022265978187e1da8df5edc91daf6ee1", # noqa: E501
  55. "darwin-arm64": "bedff301bc51f04da46d2c8900c1753032ea88485af375a9f1b7bed0915558e0", # noqa: E501
  56. "linux-amd64": "8d5c459ab21b411b8be059a8bdf59f0d3eabf9dff943d5eccb80e36e525cc09d", # noqa: E501
  57. "linux-arm64": "a00d1790e8c92c5022d83e345d6629506836d73c23c5338d5f777589bfaed02d", # noqa: E501
  58. "windows-amd64.exe": "3a650e10f07787760889d7e5694924d881265ae2384499fd59ada7c39c02366e", # noqa: E501
  59. },
  60. Release.TARGET_DETERMINATOR: {
  61. "darwin.amd64": "f3ef5abce3499926534237ffa183f54139c4760e376813973b35f8cfa5eb50cf", # noqa: E501
  62. "darwin.arm64": "17ee63f8f34c4f61907cf963ce81463b3be5b0a67b068beb02ab9a8cf7fb13d5", # noqa: E501
  63. "linux.amd64": "65000bba3a5eb1713d93b1e08e33b6fbe5787535664bbc1ba2f4166b0d26d0a1", # noqa: E501
  64. "linux.arm64": "99146eef911873f8dbba722214d4c382ebbeab52b0e030e89314db85b70c8558", # noqa: E501
  65. "windows.amd64.exe": "b59a8122a5b72517c8488a638afb8fc9c78da2eaa3c6e7ecb9638052a3ebc3ee", # noqa: E501
  66. },
  67. }
  68. def chdir_repo_root() -> None:
  69. """Change the working directory to the repository root.
  70. This is done so that scripts run from a consistent directory.
  71. """
  72. os.chdir(Path(__file__).parent.parent)
  73. def _get_hash(file: Path) -> str:
  74. """Returns the sha256 of a file."""
  75. digest = hashlib.sha256()
  76. with file.open("rb") as f:
  77. while True:
  78. chunk = f.read(1024 * 64)
  79. if not chunk:
  80. break
  81. digest.update(chunk)
  82. return digest.hexdigest()
  83. def _download(url: str, local_path: Path) -> Optional[int]:
  84. """Downloads the URL to the path. Returns an HTTP error code on failure."""
  85. with urllib.request.urlopen(url) as response:
  86. if response.code != 200:
  87. return int(response.code)
  88. with local_path.open("wb") as f:
  89. shutil.copyfileobj(response, f)
  90. return None
  91. def _get_cached_binary(name: str, url: str, want_hash: str) -> str:
  92. """Returns the path to the cached binary.
  93. If the matching version is already cached, returns it. Otherwise, downloads
  94. from the URL and verifies the hash matches.
  95. """
  96. cache_dir = Path.home().joinpath(".cache", "carbon-lang-scripts")
  97. cache_dir.mkdir(parents=True, exist_ok=True)
  98. # Hold a lock while checksumming and downloading the path. Otherwise,
  99. # parallel runs by pre-commit may conflict with one another with
  100. # simultaneous downloads.
  101. with open(cache_dir.joinpath(f"{name}.lock"), "w") as lock_file:
  102. fcntl.lockf(lock_file.fileno(), fcntl.LOCK_EX)
  103. # Check if there's a cached file that can be used.
  104. local_path = cache_dir.joinpath(name)
  105. if local_path.is_file() and want_hash == _get_hash(local_path):
  106. return str(local_path)
  107. # Download the file.
  108. retries = 5
  109. while True:
  110. err = _download(url, local_path)
  111. if err is None:
  112. break
  113. retries -= 1
  114. if retries == 0:
  115. exit(f"Failed to download {url}: HTTP {err}.")
  116. time.sleep(1)
  117. local_path.chmod(0o755)
  118. # Verify the downloaded hash.
  119. found_hash = _get_hash(local_path)
  120. if want_hash != found_hash:
  121. exit(
  122. f"Downloaded {url} but found sha256 "
  123. f"{found_hash} ({local_path.stat().st_size} bytes), wanted "
  124. f"{want_hash}"
  125. )
  126. return str(local_path)
  127. def _get_machine() -> str:
  128. machine = platform.machine()
  129. if machine == "x86_64":
  130. machine = "amd64"
  131. elif machine == "aarch64":
  132. machine = "arm64"
  133. return machine
  134. def _get_platform_ext() -> str:
  135. if platform.system() == "Windows":
  136. return ".exe"
  137. else:
  138. return ""
  139. def _select_hash(hashes: dict[str, str], version: str) -> str:
  140. # Ensure the platform version is supported and has a hash.
  141. if version not in hashes:
  142. # If this because a platform support issue, we may need to print errors.
  143. exit(f"No release available for platform: {version}")
  144. return hashes[version]
  145. def get_release(release: Release) -> str:
  146. """Install a tool to carbon-lang's cache and return its path.
  147. release: The release to cache.
  148. """
  149. info = _RELEASES[release]
  150. shas = _RELEASE_SHAS[release]
  151. # Translate platform information into Bazel's release form.
  152. ext = _get_platform_ext()
  153. platform_label = (
  154. f"{platform.system().lower()}{info.separator}{_get_machine()}{ext}"
  155. )
  156. url = f"{info.url}/{release.value}{info.separator}{platform_label}"
  157. want_hash = _select_hash(shas, platform_label)
  158. return _get_cached_binary(f"{release.value}{ext}", url, want_hash)
  159. def calculate_release_shas() -> None:
  160. """Prints sha information for tracked tool releases."""
  161. print("_RELEASE_SHAS = {")
  162. for release, info in _RELEASES.items():
  163. shas = _RELEASE_SHAS[release]
  164. print(f" {release}: {{")
  165. for platform_label in shas.keys():
  166. url = f"{info.url}/{release.value}{info.separator}{platform_label}"
  167. with tempfile.NamedTemporaryFile() as f:
  168. path = Path(f.name)
  169. _download(url, path)
  170. hash = _get_hash(path)
  171. print(f' "{platform_label}": "{hash}", # noqa: E501')
  172. print(" },")
  173. print("}")
  174. def locate_bazel() -> str:
  175. """Returns the bazel command.
  176. We use the `BAZEL` environment variable if present. If not, then we try to
  177. use `bazelisk` and then `bazel`.
  178. """
  179. bazel = os.environ.get("BAZEL")
  180. if bazel:
  181. return bazel
  182. for cmd in ("bazelisk", "bazel"):
  183. target = shutil.which(cmd)
  184. if target:
  185. return target
  186. exit("Unable to run Bazel")