scripts_utils.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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 Optional
  16. import urllib.request
  17. _URL = "https://github.com/bazelbuild/buildtools/releases/download/4.2.5/"
  18. """Version SHAs.
  19. Gather shas with:
  20. for f in buildozer buildifier; do
  21. echo \"$f\": {
  22. for v in darwin-amd64 darwin-arm64 linux-amd64 linux-arm64 \
  23. windows-amd64.exe
  24. do
  25. echo "\"$v\": \"$(wget -q -O - https://github.com/bazelbuild/buildtools/releases/download/4.2.5/$f-$v | sha256sum | cut -d ' ' -f1)\", # noqa: E501"
  26. done
  27. echo },
  28. done
  29. """
  30. _VERSION_SHAS = {
  31. "buildozer": {
  32. "darwin-amd64": "3fe671620e6cb7d2386f9da09c1de8de88b02b9dd9275cdecd8b9e417f74df1b", # noqa: E501
  33. "darwin-arm64": "ff4d297023fe3e0fd14113c78f04cef55289ca5bfe5e45a916be738b948dc743", # noqa: E501
  34. "linux-amd64": "e8e39b71c52318a9030dd9fcb9bbfd968d0e03e59268c60b489e6e6fc1595d7b", # noqa: E501
  35. "linux-arm64": "96227142969540def1d23a9e8225524173390d23f3d7fd56ce9c4436953f02fc", # noqa: E501
  36. "windows-amd64.exe": "2a9a7176cbd3b2f0ef989502128efbafd3b156ddabae93b9c979cd4017ffa300", # noqa: E501
  37. },
  38. "buildifier": {
  39. "darwin-amd64": "757f246040aceb2c9550d02ef5d1f22d3ef1ff53405fe76ef4c6239ef1ea2cc1", # noqa: E501
  40. "darwin-arm64": "4cf02e051f6cda18765935cb6e77cc938cf8b405064589a50fe9582f82c7edaf", # noqa: E501
  41. "linux-amd64": "f94e71b22925aff76ce01a49e1c6c6d31f521bbbccff047b81f2ea01fd01a945", # noqa: E501
  42. "linux-arm64": "2113d79e45efb51e2b3013c8737cb66cadae3fd89bd7e820438cb06201e50874", # noqa: E501
  43. "windows-amd64.exe": "4185a40d3154cacbe8b79f570b94e2c6f74fc9e317362b7d028c2e6c94edf9ba", # noqa: E501
  44. },
  45. }
  46. class Release(Enum):
  47. BUILDOZER = "buildozer"
  48. BUILDIFIER = "buildifier"
  49. def chdir_repo_root() -> None:
  50. """Change the working directory to the repository root.
  51. This is done so that scripts run from a consistent directory.
  52. """
  53. os.chdir(Path(__file__).parent.parent)
  54. def _get_hash(file: Path) -> str:
  55. """Returns the sha256 of a file."""
  56. digest = hashlib.sha256()
  57. with file.open("rb") as f:
  58. while True:
  59. chunk = f.read(1024 * 64)
  60. if not chunk:
  61. break
  62. digest.update(chunk)
  63. return digest.hexdigest()
  64. def _download(url: str, local_path: Path) -> Optional[int]:
  65. """Downloads the URL to the path. Returns an HTTP error code on failure."""
  66. with urllib.request.urlopen(url) as response:
  67. if response.code != 200:
  68. return int(response.code)
  69. with local_path.open("wb") as f:
  70. shutil.copyfileobj(response, f)
  71. return None
  72. def get_release(release: Release) -> str:
  73. """Install a file to carbon-lang's cache.
  74. release: The release to cache.
  75. """
  76. cache_dir = Path.home().joinpath(".cache", "carbon-lang-scripts")
  77. cache_dir.mkdir(parents=True, exist_ok=True)
  78. # Translate platform information into Bazel's release form.
  79. machine = platform.machine()
  80. if machine == "x86_64":
  81. machine = "amd64"
  82. version = f"{platform.system().lower()}-{machine}"
  83. # Get ready to add .exe for Windows.
  84. ext = ""
  85. if platform.system() == "Windows":
  86. ext = ".exe"
  87. # Ensure the platform is supported, and grab its hash.
  88. if version not in _VERSION_SHAS[release.value]:
  89. # If this because a platform support issue, we may need to print errors.
  90. exit(f"No {release.value} release available for platform: {version}")
  91. want_hash = _VERSION_SHAS[release.value][version]
  92. # Hold a lock while checksumming and downloading the path. Otherwise,
  93. # parallel runs by pre-commit may conflict with one another with
  94. # simultaneous downloads.
  95. with open(cache_dir.joinpath(f"{release.value}.lock"), "w") as lock_file:
  96. fcntl.lockf(lock_file.fileno(), fcntl.LOCK_EX)
  97. # Check if there's a cached file that can be used.
  98. local_path = cache_dir.joinpath(f"{release.value}{ext}")
  99. if local_path.is_file() and want_hash == _get_hash(local_path):
  100. return str(local_path)
  101. # Download the file.
  102. url = f"{_URL}/{release.value}-{version}{ext}"
  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(
  111. f"Failed to download {release.value}-{version}: HTTP {err}."
  112. )
  113. time.sleep(1)
  114. local_path.chmod(0o755)
  115. # Verify the downloaded hash.
  116. found_hash = _get_hash(local_path)
  117. if want_hash != found_hash:
  118. exit(
  119. f"Downloaded {release.value}-{version} but found sha256 "
  120. f"{found_hash} ({local_path.stat().st_size} bytes), wanted "
  121. f"{want_hash}"
  122. )
  123. return str(local_path)
  124. def locate_bazel() -> str:
  125. """Returns the bazel command.
  126. We use the `BAZEL` environment variable if present. If not, then we try to
  127. use `bazelisk` and then `bazel`.
  128. """
  129. bazel = os.environ.get("BAZEL")
  130. if bazel:
  131. return bazel
  132. for cmd in ("bazelisk", "bazel"):
  133. target = shutil.which(cmd)
  134. if target:
  135. return target
  136. exit("Unable to run Bazel")