From d2c2d715e17356acf60920d3269de0e174effc73 Mon Sep 17 00:00:00 2001 From: Keith Smiley Date: Wed, 4 Dec 2024 19:16:32 +0000 Subject: [PATCH] Fix absolute label use in main attribute of py_test In rules_python you can specify a file from another package like: ```bzl main = "//path/to:file.py", ``` This didn't work in rules_py since it was taking the main as a string to manipulate. This appears closer to me to the upstream logic that was mirrored, so maybe this was changed for another reason --- examples/pytest/BUILD.bazel | 18 ++++++++++++++++++ examples/pytest/__init__.py | 0 examples/pytest/main_test.py | 1 + py/private/py_executable.bzl | 5 ++--- 4 files changed, 21 insertions(+), 3 deletions(-) create mode 100644 examples/pytest/__init__.py create mode 100644 examples/pytest/main_test.py diff --git a/examples/pytest/BUILD.bazel b/examples/pytest/BUILD.bazel index 9256da54..e1cf1060 100644 --- a/examples/pytest/BUILD.bazel +++ b/examples/pytest/BUILD.bazel @@ -38,3 +38,21 @@ py_test( shard_count = 2, deps = ["@pypi_pytest//:pkg"], ) + +py_test( + name = "absolute_main_test", + srcs = [ + "__init__.py", + "main_test.py", + ], + main = "//examples/pytest:main_test.py", +) + +py_test( + name = "main_with_colon_test", + srcs = [ + "__init__.py", + "main_test.py", + ], + main = ":main_test.py", +) diff --git a/examples/pytest/__init__.py b/examples/pytest/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/pytest/main_test.py b/examples/pytest/main_test.py new file mode 100644 index 00000000..8a113993 --- /dev/null +++ b/examples/pytest/main_test.py @@ -0,0 +1 @@ +print("loaded as main!") diff --git a/py/private/py_executable.bzl b/py/private/py_executable.bzl index f9e5370a..a0809dae 100644 --- a/py/private/py_executable.bzl +++ b/py/private/py_executable.bzl @@ -25,8 +25,7 @@ def _determine_main(ctx): Artifact; the main file. If one can't be found, an error is raised. """ if ctx.attr.main: - # Deviation from rules_python: allow a leading colon, e.g. `main = ":my_target"` - proposed_main = ctx.attr.main.removeprefix(":") + proposed_main = ctx.attr.main.label.name if not proposed_main.endswith(".py"): fail("main {} must end in '.py'".format(proposed_main)) else: @@ -87,7 +86,7 @@ determine_main = rule( implementation = _determine_main_impl, attrs = { "target_name": attr.string(mandatory = True, doc = "The name of the py_binary or py_test we are finding a main for"), - "main": attr.string(doc = "Hint the user supplied as the main"), + "main": attr.label(doc = "Hint the user supplied as the main", allow_single_file = True), "srcs": attr.label_list(allow_files = True), }, )