update_roots.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python3
  2. """Update the roots of the Carbon build used for dependency checking.
  3. The dependency checking cannot use wildcard queries, so we use them here and
  4. then create lists of relevant roots in the build file.
  5. """
  6. __copyright__ = """
  7. Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  8. Exceptions. See /LICENSE for license information.
  9. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  10. """
  11. import os
  12. import shutil
  13. import subprocess
  14. import sys
  15. from pathlib import Path
  16. # Change the working directory to the repository root so that the remaining
  17. # operations reliably operate relative to that root.
  18. os.chdir(Path(__file__).parent.parent)
  19. directory = Path.cwd()
  20. # Use the `BAZEL` environment variable if present. If not, then try to use
  21. # `bazelisk` and then `bazel`.
  22. bazel = os.environ.get("BAZEL")
  23. if not bazel:
  24. bazel = "bazelisk"
  25. if not shutil.which(bazel):
  26. bazel = "bazel"
  27. if not shutil.which(bazel):
  28. sys.exit("Unable to run Bazel")
  29. # Use the `BUILDOZER` environment variable if present. If not, then try to use
  30. # `buildozer`.
  31. buildozer = os.environ.get("BUILDOZER")
  32. if not buildozer:
  33. buildozer = "buildozer"
  34. if not shutil.which(buildozer):
  35. sys.exit("Unable to run Buildozer")
  36. print("Compute non-test C++ root targets...")
  37. non_test_cc_roots_query = subprocess.run(
  38. [
  39. bazel,
  40. "query",
  41. "--noshow_progress",
  42. "--noimplicit_deps",
  43. "--notool_deps",
  44. "--output=minrank",
  45. (
  46. 'let non_tests = kind("cc.* rule", attr(testonly, 0, //...))'
  47. ' in kind("cc.* rule", deps($non_tests))'
  48. ),
  49. ],
  50. check=True,
  51. stdout=subprocess.PIPE,
  52. universal_newlines=True,
  53. ).stdout
  54. ranked_targets = [line.split() for line in non_test_cc_roots_query.splitlines()]
  55. roots = [target for rank, target in ranked_targets if int(rank) == 0]
  56. print("Found roots:\n%s" % "\n".join(roots))
  57. print("Replace non-test C++ roots in the BUILD file...")
  58. buildozer_run = subprocess.run(
  59. [
  60. buildozer,
  61. "remove data",
  62. ]
  63. + ["add data '%s'" % root for root in roots]
  64. + ["//bazel/check_deps:non_test_cc_rules"],
  65. )
  66. if buildozer_run.returncode == 3:
  67. print("No changes needed!")
  68. else:
  69. buildozer_run.check_returncode()
  70. print("Successfully updated roots in the BUILD file!")