scripts_utils.py 5.1 KB

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