From 7adc3156b7967572d286efd1ab3746a28872bbd4 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Tue, 19 Dec 2023 10:57:06 +0100 Subject: [PATCH 1/2] Fix `runfiles.CurrentRepository` with non-hermetic `sys.path` 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. --- python/runfiles/runfiles.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/python/runfiles/runfiles.py b/python/runfiles/runfiles.py index 22409792f5..b3b42da80b 100644 --- a/python/runfiles/runfiles.py +++ b/python/runfiles/runfiles.py @@ -247,6 +247,20 @@ def CurrentRepository(self, frame: int = 1) -> str: raise ValueError("failed to determine caller's file path") from exc caller_runfiles_path = os.path.relpath(caller_path, self._python_runfiles_root) if caller_runfiles_path.startswith(".." + os.path.sep): + # With Python 3.10 and earlier, sys.path contains the directory + # of the script, which can result in a module being loaded from + # outside the runfiles tree. In this case, assume that the module is + # located in the main repository. + # With Python 3.11 and higher, the Python launcher sets + # PYTHONSAFEPATH, which prevents this behavior. + # TODO: This doesn't cover the case of a script being run from an + # external repository, which could be heuristically detected + # by parsing the script's path. + if ( + sys.version_info.minor <= 10 + and sys.path[0] != self._python_runfiles_root + ): + return "" raise ValueError( "{} does not lie under the runfiles root {}".format( caller_path, self._python_runfiles_root From e52ead4f8cd2e502ffc5da7db976bd43b2c612c1 Mon Sep 17 00:00:00 2001 From: Richard Levasseur Date: Thu, 15 Aug 2024 12:13:12 -0700 Subject: [PATCH 2/2] add changelog entry --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c87e76e5be..4bef1840e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,6 +67,10 @@ A brief description of the categories of changes: cause warnings by default. In order to see the warnings for diagnostic purposes set the env var `RULES_PYTHON_REPO_DEBUG_VERBOSITY` to one of `INFO`, `DEBUG` or `TRACE`. Fixes [#1818](https://github.com/bazelbuild/rules_python/issues/1818). +* (runfiles) Make runfiles lookups work for the situation of Bazel 7, + Python 3.9 (or earlier, where safepath isn't present), and the Rlocation call + in the same directory as the main file. + Fixes [#1631](https://github.com/bazelbuild/rules_python/issues/1631). ### Added * (rules) `PYTHONSAFEPATH` is inherited from the calling environment to allow