Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions news/add_runfiles_raise_api.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
(runfiles) Added {obj}`Runfiles.CreateOrRaise` to return a `Runfiles` instance
or raise an error if runfiles cannot be found.
12 changes: 11 additions & 1 deletion python/runfiles/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,17 @@ with open(r.Rlocation("my_workspace/path/to/my/data.txt"), "r") as f:

Here `my_workspace` is the name you specified via `module(name = "...")` in your `MODULE.bazel` file (with `--enable_bzlmod`, default as of Bazel 7) or `workspace(name = "...")` in `WORKSPACE` (with `--noenable_bzlmod`).

The code above creates a manifest- or directory-based implementation based on the environment variables in `os.environ`. See `Runfiles.Create()` for more info.
The code above creates a manifest- or directory-based implementation based on
the environment variables in `os.environ`. See `Runfiles.Create()` for more
info.

Alternatively, `Runfiles.CreateOrRaise()` can be used to raise an error
instead of returning `None` if runfiles cannot be found:

```python
r = Runfiles.CreateOrRaise()
```


If you want to explicitly create a manifest- or directory-based
implementation, you can do so as follows:
Expand Down
49 changes: 49 additions & 0 deletions python/runfiles/runfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,46 @@ def Create(env: Optional[Dict[str, str]] = None) -> Optional["Runfiles"]:

return None

# TODO: Update return type to Self when 3.11 is the min version
# https://peps.python.org/pep-0673/
@staticmethod
def CreateOrRaise(env: Optional[Dict[str, str]] = None) -> "Runfiles":
"""Returns a new `Runfiles` instance, or raises an error.

The returned object is either:
- manifest-based, meaning it looks up runfile paths from a manifest
file, or
- directory-based, meaning it looks up runfile paths under a given
directory path

If `env` contains "RUNFILES_MANIFEST_FILE" with non-empty value, this
method returns a manifest-based implementation. The object eagerly
reads and caches the whole manifest file upon instantiation; this may
be relevant for performance consideration.

Otherwise, if `env` contains "RUNFILES_DIR" with non-empty value
(checked in this priority order), this method returns a directory-based
implementation.

If neither cases apply, this method raises a `RuntimeError`.

Args:
env: {string: string}; optional; the map of environment variables. If
None, this function uses the environment variable map of this
process.
Raises:
RuntimeError: if runfiles cannot be found.

:::{versionadded} VERSION_NEXT_FEATURE
:::
"""
runfiles = Runfiles.Create(env=env)
if runfiles is None:
raise RuntimeError(
"Cannot create Runfiles: $RUNFILES_MANIFEST_FILE and $RUNFILES_DIR are both unset or empty"
)
return runfiles


# Support legacy imports by defining a private symbol.
_Runfiles = Runfiles
Expand All @@ -743,3 +783,12 @@ def CreateDirectoryBased(runfiles_dir_path: str) -> Runfiles:

def Create(env: Optional[Dict[str, str]] = None) -> Optional[Runfiles]:
return Runfiles.Create(env)


def CreateOrRaise(env: Optional[Dict[str, str]] = None) -> Runfiles:
"""Refer to `Runfiles.CreateOrRaise`.

:::{versionadded} VERSION_NEXT_FEATURE
:::
"""
return Runfiles.CreateOrRaise(env)
56 changes: 56 additions & 0 deletions tests/runfiles/runfiles_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,62 @@ def testFailsToCreateAnyRunfilesBecauseEnvvarsAreNotDefined(self) -> None:
self.assertIsNone(runfiles.Create({"TEST_SRCDIR": "always ignored"}))
self.assertIsNone(runfiles.Create({"FOO": "bar"}))

def testCreatesManifestBasedRunfilesWithCreateOrRaise(self) -> None:
with _MockFile(contents=["a/b c/d"]) as mf:
r = runfiles.CreateOrRaise(
{
"RUNFILES_MANIFEST_FILE": mf.Path(),
"RUNFILES_DIR": "ignored when RUNFILES_MANIFEST_FILE has a value",
"TEST_SRCDIR": "always ignored",
}
)
self.assertEqual(r.Rlocation("a/b"), "c/d")
self.assertIsNone(r.Rlocation("foo"))

r_class = runfiles.Runfiles.CreateOrRaise(
{
"RUNFILES_MANIFEST_FILE": mf.Path(),
}
)
self.assertEqual(r_class.Rlocation("a/b"), "c/d")

def testCreatesDirectoryBasedRunfilesWithCreateOrRaise(self) -> None:
r = runfiles.CreateOrRaise(
{
"RUNFILES_DIR": "runfiles/dir",
"TEST_SRCDIR": "always ignored",
}
)
self.assertEqual(r.Rlocation("a/b"), "runfiles/dir/a/b")
self.assertEqual(r.Rlocation("foo"), "runfiles/dir/foo")

r_class = runfiles.Runfiles.CreateOrRaise(
{
"RUNFILES_DIR": "runfiles/dir",
}
)
self.assertEqual(r_class.Rlocation("a/b"), "runfiles/dir/a/b")

def testFailsToCreateManifestBasedBecauseManifestDoesNotExistWithCreateOrRaise(
self,
) -> None:
def _Run():
runfiles.CreateOrRaise({"RUNFILES_MANIFEST_FILE": "non-existing path"})

self.assertRaisesRegex(IOError, "non-existing path", _Run)

def testFailsToCreateAnyRunfilesWithCreateOrRaise(self) -> None:
with self.assertRaises(RuntimeError):
runfiles.CreateOrRaise({"TEST_SRCDIR": "always ignored"})
with self.assertRaises(RuntimeError):
runfiles.CreateOrRaise({"FOO": "bar"})
with self.assertRaises(RuntimeError):
runfiles.CreateOrRaise({})
with self.assertRaises(RuntimeError):
runfiles.Runfiles.CreateOrRaise({"TEST_SRCDIR": "always ignored"})
with self.assertRaises(RuntimeError):
runfiles.Runfiles.CreateOrRaise({})

def testManifestBasedRlocation(self) -> None:
with _MockFile(
contents=[
Expand Down