run_tool.bzl 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. # Exceptions. See /LICENSE for license information.
  3. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. """Supports running a tool from the install filegroup."""
  5. _RUN_TOOL_TMPL = """#!/usr/bin/env python3
  6. import os
  7. import sys
  8. # These will be relative locations in bazel-out.
  9. _SCRIPT_LOCATION = "{0}"
  10. _TOOL_LOCATION = "{1}"
  11. # Make sure we have the expected structure.
  12. if not __file__.endswith(_SCRIPT_LOCATION):
  13. exit(
  14. "Unable to figure out path:\\n"
  15. f" __file__: {{__file__}}\\n"
  16. f" script: {{_SCRIPT_LOCATION}}\\n"
  17. )
  18. # Run the tool using the absolute path, forwarding arguments.
  19. tool_path = __file__.removesuffix(_SCRIPT_LOCATION) + _TOOL_LOCATION
  20. os.execv(tool_path, [tool_path] + sys.argv[1:])
  21. """
  22. def _run_tool_impl(ctx):
  23. content = _RUN_TOOL_TMPL.format(ctx.outputs.executable.path, ctx.file.tool.path)
  24. ctx.actions.write(
  25. output = ctx.outputs.executable,
  26. is_executable = True,
  27. content = content,
  28. )
  29. return [
  30. DefaultInfo(
  31. runfiles = ctx.runfiles(files = ctx.files.data),
  32. ),
  33. RunEnvironmentInfo(environment = ctx.attr.env),
  34. ]
  35. run_tool = rule(
  36. doc = "Helper for running a tool in a filegroup.",
  37. implementation = _run_tool_impl,
  38. attrs = {
  39. "data": attr.label_list(allow_files = True),
  40. "env": attr.string_dict(),
  41. "tool": attr.label(
  42. allow_single_file = True,
  43. executable = True,
  44. cfg = "target",
  45. mandatory = True,
  46. ),
  47. },
  48. executable = True,
  49. )