Skip to content

Commit

Permalink
create tools/runfiles
Browse files Browse the repository at this point in the history
a (subjectively) improved API for bazel runfiles in Python
  • Loading branch information
cj81499 committed Aug 23, 2024
1 parent 2a9d9b8 commit f6536fc
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 0 deletions.
19 changes: 19 additions & 0 deletions tools/runfiles/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -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",
],
)
29 changes: 29 additions & 0 deletions tools/runfiles/__init__.py
Original file line number Diff line number Diff line change
@@ -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
23 changes: 23 additions & 0 deletions tools/runfiles/runfiles_test.py
Original file line number Diff line number Diff line change
@@ -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))
1 change: 1 addition & 0 deletions tools/runfiles/runfiles_test_data.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello, world!

0 comments on commit f6536fc

Please sign in to comment.