diff --git a/tools/runfiles/BUILD.bazel b/tools/runfiles/BUILD.bazel new file mode 100644 index 0000000..f89f8c9 --- /dev/null +++ b/tools/runfiles/BUILD.bazel @@ -0,0 +1,19 @@ +load("@rules_python//python:defs.bzl", "py_library", "py_test") + +py_library( + name = "runfiles", + srcs = ["__init__.py"], + visibility = ["//visibility:public"], + deps = ["@rules_python//python/runfiles"], +) + +py_test( + name = "runfiles_test", + size = "small", + srcs = ["runfiles_test.py"], + data = ["runfiles_test_data.txt"], + deps = [ + ":runfiles", + "@pip//pytest", + ], +) diff --git a/tools/runfiles/__init__.py b/tools/runfiles/__init__.py new file mode 100644 index 0000000..48c70b5 --- /dev/null +++ b/tools/runfiles/__init__.py @@ -0,0 +1,29 @@ +from pathlib import Path + +from python.runfiles import Runfiles + +# FIXME: https://github.com/bazelbuild/rules_python/issues/1679 +# from rules_python.python.runfiles import runfiles + +_RUNFILES = Runfiles.Create() + + +def locate(path: str | Path, workspace: str = "__main__") -> Path: + if not isinstance(path, Path): + path = Path(path) + + if path.is_absolute(): + msg = f"{path=} must be a relative path" + raise ValueError(msg) + + located = _RUNFILES.Rlocation(f"{workspace}/{path}") + if located is None: + msg = f"Failed to locate data-dependency. {path=} {workspace=}" + raise ValueError(msg) + + pth = Path(located) + if not pth.exists(): + msg = f"Located data-dependency does not exist. {located=} {path=} {workspace=}" + raise ValueError(msg) + + return pth diff --git a/tools/runfiles/runfiles_test.py b/tools/runfiles/runfiles_test.py new file mode 100644 index 0000000..44cb7f0 --- /dev/null +++ b/tools/runfiles/runfiles_test.py @@ -0,0 +1,23 @@ +import sys + +import pytest + +from tools import runfiles + + +def test_runfiles_happy(): + data = runfiles.locate("tools/runfiles/runfiles_test_data.txt") + assert data.read_text() == "Hello, world!\n" + + +def test_runfiles_error(): + to_locate = "tools/runfiles/does_not_exist.txt" + with pytest.raises( + ValueError, + match=r"^Located data-dependency does not exist.", + ): + runfiles.locate(to_locate) + + +if __name__ == "__main__": + sys.exit(pytest.main(sys.argv)) diff --git a/tools/runfiles/runfiles_test_data.txt b/tools/runfiles/runfiles_test_data.txt new file mode 100644 index 0000000..af5626b --- /dev/null +++ b/tools/runfiles/runfiles_test_data.txt @@ -0,0 +1 @@ +Hello, world!