Skip to content

Commit 0d6d8f3

Browse files
fmeumaignasrickeylev
authored
fix: support runfiles.CurrentRepository with non-hermetic sys.path (#1634)
When using Python 3.10 or earlier, the first `sys.path` entry is the directory containing the script. This can result in modules being loaded from the source root rather than the runfiles root, which the runfiles library previously didn't support. Fixes #1631 --------- Co-authored-by: Ignas Anikevicius <[email protected]> Co-authored-by: Richard Levasseur <[email protected]>
1 parent 519574c commit 0d6d8f3

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,10 @@ A brief description of the categories of changes:
6767
cause warnings by default. In order to see the warnings for diagnostic purposes
6868
set the env var `RULES_PYTHON_REPO_DEBUG_VERBOSITY` to one of `INFO`, `DEBUG` or `TRACE`.
6969
Fixes [#1818](https://github.com/bazelbuild/rules_python/issues/1818).
70+
* (runfiles) Make runfiles lookups work for the situation of Bazel 7,
71+
Python 3.9 (or earlier, where safepath isn't present), and the Rlocation call
72+
in the same directory as the main file.
73+
Fixes [#1631](https://github.com/bazelbuild/rules_python/issues/1631).
7074

7175
### Added
7276
* (rules) `PYTHONSAFEPATH` is inherited from the calling environment to allow

python/runfiles/runfiles.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,20 @@ def CurrentRepository(self, frame: int = 1) -> str:
247247
raise ValueError("failed to determine caller's file path") from exc
248248
caller_runfiles_path = os.path.relpath(caller_path, self._python_runfiles_root)
249249
if caller_runfiles_path.startswith(".." + os.path.sep):
250+
# With Python 3.10 and earlier, sys.path contains the directory
251+
# of the script, which can result in a module being loaded from
252+
# outside the runfiles tree. In this case, assume that the module is
253+
# located in the main repository.
254+
# With Python 3.11 and higher, the Python launcher sets
255+
# PYTHONSAFEPATH, which prevents this behavior.
256+
# TODO: This doesn't cover the case of a script being run from an
257+
# external repository, which could be heuristically detected
258+
# by parsing the script's path.
259+
if (
260+
sys.version_info.minor <= 10
261+
and sys.path[0] != self._python_runfiles_root
262+
):
263+
return ""
250264
raise ValueError(
251265
"{} does not lie under the runfiles root {}".format(
252266
caller_path, self._python_runfiles_root

0 commit comments

Comments
 (0)