From 91d1072a775706c9502ebe33d0ceb7f9f01e4498 Mon Sep 17 00:00:00 2001 From: Richard Levasseur Date: Wed, 9 Apr 2025 00:44:13 -0700 Subject: [PATCH] fix: fixes to prepare for making bootstrap=script the default for Linux --- .bazelignore | 1 + CHANGELOG.md | 11 ++- examples/pip_repository_annotations/.bazelrc | 1 + .../pip_repository_annotations_test.py | 25 ++--- gazelle/WORKSPACE | 2 + python/config_settings/BUILD.bazel | 16 +++- python/private/flags.bzl | 32 ++++++- python/private/get_local_runtime_info.py | 1 + python/private/local_runtime_repo.bzl | 14 +++ python/private/py_executable.bzl | 27 +++++- python/private/py_runtime_info.bzl | 26 ++++- python/private/py_runtime_rule.bzl | 12 +++ python/private/runtime_env_toolchain.bzl | 2 + .../runtime_env_toolchain_interpreter.sh | 26 ++++- python/private/site_init_template.py | 24 +++++ python/private/stage1_bootstrap_template.sh | 94 ++++++++++++++----- python/private/stage2_bootstrap_template.py | 19 ++++ .../integration/local_toolchains/BUILD.bazel | 2 + tests/integration/local_toolchains/test.py | 53 +++++++++-- tests/runtime_env_toolchain/BUILD.bazel | 4 + 20 files changed, 336 insertions(+), 56 deletions(-) diff --git a/.bazelignore b/.bazelignore index e10af2035d..fb999097f5 100644 --- a/.bazelignore +++ b/.bazelignore @@ -25,6 +25,7 @@ examples/pip_parse/bazel-pip_parse examples/pip_parse_vendored/bazel-pip_parse_vendored examples/pip_repository_annotations/bazel-pip_repository_annotations examples/py_proto_library/bazel-py_proto_library +gazelle/bazel-gazelle tests/integration/compile_pip_requirements/bazel-compile_pip_requirements tests/integration/ignore_root_user_error/bazel-ignore_root_user_error tests/integration/local_toolchains/bazel-local_toolchains diff --git a/CHANGELOG.md b/CHANGELOG.md index 47ccd2459a..8e4fed74ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,7 +72,7 @@ Unreleased changes template. * (toolchains) Previously [#2636](https://github.com/bazel-contrib/rules_python/pull/2636) changed the semantics of `ignore_root_user_error` from "ignore" to "warning". This is now flipped back to ignoring the issue, and will only emit a warning when the attribute is set - `False`. + `False`. * (pypi) The PyPI extension will no longer write the lock file entries as the extension has been marked reproducible. Fixes [#2434](https://github.com/bazel-contrib/rules_python/issues/2434). @@ -81,6 +81,10 @@ Unreleased changes template. [PR #2746](https://github.com/bazel-contrib/rules_python/pull/2746). * (rules) {attr}`py_binary.srcs` and {attr}`py_test.srcs` is no longer mandatory when `main_module` is specified (for `--bootstrap_impl=script`) +* (rules) On Windows, {obj}`--bootstrap_impl=system_python` is forced. This + allows setting `--bootstrap_impl=script` in bazelrc for mixed-platform + environments. + [20250317]: https://github.com/astral-sh/python-build-standalone/releases/tag/20250317 @@ -102,6 +106,11 @@ Unreleased changes template. * (packaging) An empty `requires_file` is treated as if it were omitted, resulting in a valid `METADATA` file. * (rules) py_wheel and sphinxdocs rules now propagate `target_compatible_with` to all targets they create. [PR #2788](https://github.com/bazel-contrib/rules_python/pull/2788). +* Fixes when using {obj}`--bootstrap_impl=script`: + * `compile_pip_requirements` is now works with it + * The `sys._base_executable` value will reflect the underlying interpreter, + not venv interpreter. + * The {obj}`//python/runtime_env_toolchains:all` toolchain now works with it. {#v0-0-0-added} ### Added diff --git a/examples/pip_repository_annotations/.bazelrc b/examples/pip_repository_annotations/.bazelrc index c16c5a24f2..9397bd31b8 100644 --- a/examples/pip_repository_annotations/.bazelrc +++ b/examples/pip_repository_annotations/.bazelrc @@ -5,4 +5,5 @@ try-import %workspace%/user.bazelrc # is in examples/bzlmod as the `whl_mods` feature. common --noenable_bzlmod common --enable_workspace +common --legacy_external_runfiles=false common --incompatible_python_disallow_native_rules diff --git a/examples/pip_repository_annotations/pip_repository_annotations_test.py b/examples/pip_repository_annotations/pip_repository_annotations_test.py index e41dd4f0f6..219be1ba03 100644 --- a/examples/pip_repository_annotations/pip_repository_annotations_test.py +++ b/examples/pip_repository_annotations/pip_repository_annotations_test.py @@ -21,7 +21,7 @@ import unittest from pathlib import Path -from rules_python.python.runfiles import runfiles +from python.runfiles import runfiles class PipRepositoryAnnotationsTest(unittest.TestCase): @@ -34,11 +34,7 @@ def wheel_pkg_dir(self) -> str: def test_build_content_and_data(self): r = runfiles.Create() - rpath = r.Rlocation( - "pip_repository_annotations_example/external/{}/generated_file.txt".format( - self.wheel_pkg_dir() - ) - ) + rpath = r.Rlocation("{}/generated_file.txt".format(self.wheel_pkg_dir())) generated_file = Path(rpath) self.assertTrue(generated_file.exists()) @@ -47,11 +43,7 @@ def test_build_content_and_data(self): def test_copy_files(self): r = runfiles.Create() - rpath = r.Rlocation( - "pip_repository_annotations_example/external/{}/copied_content/file.txt".format( - self.wheel_pkg_dir() - ) - ) + rpath = r.Rlocation("{}/copied_content/file.txt".format(self.wheel_pkg_dir())) copied_file = Path(rpath) self.assertTrue(copied_file.exists()) @@ -61,7 +53,7 @@ def test_copy_files(self): def test_copy_executables(self): r = runfiles.Create() rpath = r.Rlocation( - "pip_repository_annotations_example/external/{}/copied_content/executable{}".format( + "{}/copied_content/executable{}".format( self.wheel_pkg_dir(), ".exe" if platform.system() == "windows" else ".py", ) @@ -82,7 +74,7 @@ def test_data_exclude_glob(self): current_wheel_version = "0.38.4" r = runfiles.Create() - dist_info_dir = "pip_repository_annotations_example/external/{}/site-packages/wheel-{}.dist-info".format( + dist_info_dir = "{}/site-packages/wheel-{}.dist-info".format( self.wheel_pkg_dir(), current_wheel_version, ) @@ -113,11 +105,8 @@ def test_extra(self): # This test verifies that annotations work correctly for pip packages with extras # specified, in this case requests[security]. r = runfiles.Create() - rpath = r.Rlocation( - "pip_repository_annotations_example/external/{}/generated_file.txt".format( - self.requests_pkg_dir() - ) - ) + path = "{}/generated_file.txt".format(self.requests_pkg_dir()) + rpath = r.Rlocation(path) generated_file = Path(rpath) self.assertTrue(generated_file.exists()) diff --git a/gazelle/WORKSPACE b/gazelle/WORKSPACE index 14a124d5f2..ad428b10cd 100644 --- a/gazelle/WORKSPACE +++ b/gazelle/WORKSPACE @@ -42,6 +42,8 @@ load("//:internal_dev_deps.bzl", "internal_dev_deps") internal_dev_deps() +register_toolchains("@rules_python//python/runtime_env_toolchains:all") + load("//:deps.bzl", _py_gazelle_deps = "gazelle_deps") # gazelle:repository_macro deps.bzl%go_deps diff --git a/python/config_settings/BUILD.bazel b/python/config_settings/BUILD.bazel index 45354e24d9..872d7d1bda 100644 --- a/python/config_settings/BUILD.bazel +++ b/python/config_settings/BUILD.bazel @@ -11,6 +11,7 @@ load( "PrecompileSourceRetentionFlag", "VenvsSitePackages", "VenvsUseDeclareSymlinkFlag", + rp_string_flag = "string_flag", ) load( "//python/private/pypi:flags.bzl", @@ -87,14 +88,27 @@ string_flag( visibility = ["//visibility:public"], ) -string_flag( +rp_string_flag( name = "bootstrap_impl", build_setting_default = BootstrapImplFlag.SYSTEM_PYTHON, + override = select({ + # Windows doesn't yet support bootstrap=script, so force disable it + ":_is_windows": BootstrapImplFlag.SYSTEM_PYTHON, + "//conditions:default": "", + }), values = sorted(BootstrapImplFlag.__members__.values()), # NOTE: Only public because it's an implicit dependency visibility = ["//visibility:public"], ) +# For some reason, @platforms//os:windows can't be directly used +# in the select() for the flag. But it can be used when put behind +# a config_setting(). +config_setting( + name = "_is_windows", + constraint_values = ["@platforms//os:windows"], +) + # This is used for pip and hermetic toolchain resolution. string_flag( name = "py_linux_libc", diff --git a/python/private/flags.bzl b/python/private/flags.bzl index c53e4610ff..40ce63b3b0 100644 --- a/python/private/flags.bzl +++ b/python/private/flags.bzl @@ -35,8 +35,38 @@ AddSrcsToRunfilesFlag = FlagEnum( is_enabled = _AddSrcsToRunfilesFlag_is_enabled, ) +def _string_flag_impl(ctx): + if ctx.attr.override: + value = ctx.attr.override + else: + value = ctx.build_setting_value + + if value not in ctx.attr.values: + fail(( + "Invalid value for {name}: got {value}, must " + + "be one of {allowed}" + ).format( + name = ctx.label, + value = value, + allowed = ctx.attr.values, + )) + + return [ + BuildSettingInfo(value = value), + config_common.FeatureFlagInfo(value = value), + ] + +string_flag = rule( + implementation = _string_flag_impl, + build_setting = config.string(flag = True), + attrs = { + "override": attr.string(), + "values": attr.string_list(), + }, +) + def _bootstrap_impl_flag_get_value(ctx): - return ctx.attr._bootstrap_impl_flag[BuildSettingInfo].value + return ctx.attr._bootstrap_impl_flag[config_common.FeatureFlagInfo].value # buildifier: disable=name-conventions BootstrapImplFlag = enum( diff --git a/python/private/get_local_runtime_info.py b/python/private/get_local_runtime_info.py index 0207f56bef..19db3a2935 100644 --- a/python/private/get_local_runtime_info.py +++ b/python/private/get_local_runtime_info.py @@ -22,6 +22,7 @@ "micro": sys.version_info.micro, "include": sysconfig.get_path("include"), "implementation_name": sys.implementation.name, + "base_executable": sys._base_executable, } config_vars = [ diff --git a/python/private/local_runtime_repo.bzl b/python/private/local_runtime_repo.bzl index fb1a8e29ac..ec0643e497 100644 --- a/python/private/local_runtime_repo.bzl +++ b/python/private/local_runtime_repo.bzl @@ -84,6 +84,20 @@ def _local_runtime_repo_impl(rctx): info = json.decode(exec_result.stdout) logger.info(lambda: _format_get_info_result(info)) + # We use base_executable because we want the path within a Python + # installation directory ("PYTHONHOME"). The problems with sys.executable + # are: + # * If we're in an activated venv, then we don't want the venv's + # `bin/python3` path to be used -- it isn't an actual Python installation. + # * If sys.executable is a wrapper (e.g. pyenv), then (1) it may not be + # located within an actual Python installation directory, and (2) it + # can interfer with Python recognizing when it's within a venv. + # + # In some cases, it may be a symlink (usually e.g. `python3->python3.12`), + # but we don't realpath() it to respect what it has decided is the + # appropriate path. + interpreter_path = info["base_executable"] + # NOTE: Keep in sync with recursive glob in define_local_runtime_toolchain_impl repo_utils.watch_tree(rctx, rctx.path(info["include"])) diff --git a/python/private/py_executable.bzl b/python/private/py_executable.bzl index dd3ad869fa..7a73d759ff 100644 --- a/python/private/py_executable.bzl +++ b/python/private/py_executable.bzl @@ -350,6 +350,7 @@ def _create_executable( main_py = main_py, imports = imports, runtime_details = runtime_details, + venv = venv, ) extra_runfiles = ctx.runfiles([stage2_bootstrap] + venv.files_without_interpreter) zip_main = _create_zip_main( @@ -538,11 +539,14 @@ def _create_venv(ctx, output_prefix, imports, runtime_details): ctx.actions.write(pyvenv_cfg, "") runtime = runtime_details.effective_runtime + venvs_use_declare_symlink_enabled = ( VenvsUseDeclareSymlinkFlag.get_value(ctx) == VenvsUseDeclareSymlinkFlag.YES ) + recreate_venv_at_runtime = False - if not venvs_use_declare_symlink_enabled: + if not venvs_use_declare_symlink_enabled or not runtime.supports_build_time_venv: + recreate_venv_at_runtime = True if runtime.interpreter: interpreter_actual_path = runfiles_root_path(ctx, runtime.interpreter.short_path) else: @@ -557,6 +561,8 @@ def _create_venv(ctx, output_prefix, imports, runtime_details): ctx.actions.write(interpreter, "actual:{}".format(interpreter_actual_path)) elif runtime.interpreter: + # Some wrappers around the interpreter (e.g. pyenv) use the program + # name to decide what to do, so preserve the name. py_exe_basename = paths.basename(runtime.interpreter.short_path) # Even though ctx.actions.symlink() is used, using @@ -594,7 +600,8 @@ def _create_venv(ctx, output_prefix, imports, runtime_details): if "t" in runtime.abi_flags: version += "t" - site_packages = "{}/lib/python{}/site-packages".format(venv, version) + venv_site_packages = "lib/python{}/site-packages".format(version) + site_packages = "{}/{}".format(venv, venv_site_packages) pth = ctx.actions.declare_file("{}/bazel.pth".format(site_packages)) ctx.actions.write(pth, "import _bazel_site_init\n") @@ -616,10 +623,12 @@ def _create_venv(ctx, output_prefix, imports, runtime_details): return struct( interpreter = interpreter, - recreate_venv_at_runtime = not venvs_use_declare_symlink_enabled, + recreate_venv_at_runtime = recreate_venv_at_runtime, # Runfiles root relative path or absolute path interpreter_actual_path = interpreter_actual_path, files_without_interpreter = [pyvenv_cfg, pth, site_init] + site_packages_symlinks, + # string; venv-relative path to the site-packages directory. + venv_site_packages = venv_site_packages, ) def _create_site_packages_symlinks(ctx, site_packages): @@ -716,7 +725,8 @@ def _create_stage2_bootstrap( output_sibling, main_py, imports, - runtime_details): + runtime_details, + venv = None): output = ctx.actions.declare_file( # Prepend with underscore to prevent pytest from trying to # process the bootstrap for files starting with `test_` @@ -741,6 +751,7 @@ def _create_stage2_bootstrap( "%main%": main_py_path, "%main_module%": ctx.attr.main_module, "%target%": str(ctx.label), + "%venv_rel_site_packages%": venv.venv_site_packages if venv else "", "%workspace_name%": ctx.workspace_name, }, is_executable = True, @@ -766,6 +777,12 @@ def _create_stage1_bootstrap( python_binary_actual = venv.interpreter_actual_path if venv else "" + # Runtime may be None on Windows due to the --python_path flag. + if runtime and runtime.supports_build_time_venv: + resolve_python_binary_at_runtime = "0" + else: + resolve_python_binary_at_runtime = "1" + subs = { "%interpreter_args%": "\n".join([ '"{}"'.format(v) @@ -775,7 +792,9 @@ def _create_stage1_bootstrap( "%python_binary%": python_binary_path, "%python_binary_actual%": python_binary_actual, "%recreate_venv_at_runtime%": str(int(venv.recreate_venv_at_runtime)) if venv else "0", + "%resolve_python_binary_at_runtime%": resolve_python_binary_at_runtime, "%target%": str(ctx.label), + "%venv_rel_site_packages%": venv.venv_site_packages if venv else "", "%workspace_name%": ctx.workspace_name, } diff --git a/python/private/py_runtime_info.bzl b/python/private/py_runtime_info.bzl index 4297391068..d2ae17e360 100644 --- a/python/private/py_runtime_info.bzl +++ b/python/private/py_runtime_info.bzl @@ -67,7 +67,8 @@ def _PyRuntimeInfo_init( stage2_bootstrap_template = None, zip_main_template = None, abi_flags = "", - site_init_template = None): + site_init_template = None, + supports_build_time_venv = True): if (interpreter_path and interpreter) or (not interpreter_path and not interpreter): fail("exactly one of interpreter or interpreter_path must be specified") @@ -119,6 +120,7 @@ def _PyRuntimeInfo_init( "site_init_template": site_init_template, "stage2_bootstrap_template": stage2_bootstrap_template, "stub_shebang": stub_shebang, + "supports_build_time_venv": supports_build_time_venv, "zip_main_template": zip_main_template, } @@ -312,6 +314,28 @@ The following substitutions are made during template expansion: "Shebang" expression prepended to the bootstrapping Python stub script used when executing {obj}`py_binary` targets. Does not apply to Windows. +""", + "supports_build_time_venv": """ +:type: bool + +True if this toolchain supports the build-time created virtual environment. +False if not or unknown. If build-time venv creation isn't supported, then binaries may +fallback to non-venv solutions or creating a venv at runtime. + +In order to use the build-time created virtual environment, a toolchain needs +to meet two criteria: +1. Specifying the underlying executable (e.g. `/usr/bin/python3`, as reported by + `sys._base_executable`) for the venv executable (`$venv/bin/python3`, as reported + by `sys.executable`). This typically requires relative symlinking the venv + path to the underlying path at build time, or using the `PYTHONEXECUTABLE` + environment variable (Python 3.11+) at runtime. +2. Having the build-time created site-packages directory + (`/lib/python{version}/site-packages`) recognized by the runtime + interpreter. This typically requires the Python version to be known at + build-time and match at runtime. + +:::{versionadded} VERSION_NEXT_FEATURE +::: """, "zip_main_template": """ :type: File diff --git a/python/private/py_runtime_rule.bzl b/python/private/py_runtime_rule.bzl index a85f5b25f2..6dadcfeac3 100644 --- a/python/private/py_runtime_rule.bzl +++ b/python/private/py_runtime_rule.bzl @@ -130,6 +130,7 @@ def _py_runtime_impl(ctx): zip_main_template = ctx.file.zip_main_template, abi_flags = abi_flags, site_init_template = ctx.file.site_init_template, + supports_build_time_venv = ctx.attr.supports_build_time_venv, )) if not IS_BAZEL_7_OR_HIGHER: @@ -353,6 +354,17 @@ motivation. Does not apply to Windows. """, ), + "supports_build_time_venv": attr.bool( + doc = """ +Whether this runtime supports virtualenvs created at build time. + +See {obj}`PyRuntimeInfo.supports_build_time_venv` for docs. + +:::{versionadded} VERSION_NEXT_FEATURE +::: +""", + default = True, + ), "zip_main_template": attr.label( default = "//python/private:zip_main_template", allow_single_file = True, diff --git a/python/private/runtime_env_toolchain.bzl b/python/private/runtime_env_toolchain.bzl index 2116012c03..54ac1a2313 100644 --- a/python/private/runtime_env_toolchain.bzl +++ b/python/private/runtime_env_toolchain.bzl @@ -45,6 +45,7 @@ def define_runtime_env_toolchain(name): stub_shebang = "#!/usr/bin/env python3", visibility = ["//visibility:private"], tags = ["manual"], + supports_build_time_venv = False, ) # This is a dummy runtime whose interpreter_path triggers the native rule @@ -56,6 +57,7 @@ def define_runtime_env_toolchain(name): python_version = "PY3", visibility = ["//visibility:private"], tags = ["manual"], + supports_build_time_venv = False, ) py_runtime_pair( diff --git a/python/private/runtime_env_toolchain_interpreter.sh b/python/private/runtime_env_toolchain_interpreter.sh index b09bc53e5c..6159d4f38c 100755 --- a/python/private/runtime_env_toolchain_interpreter.sh +++ b/python/private/runtime_env_toolchain_interpreter.sh @@ -53,5 +53,29 @@ documentation for py_runtime_pair \ (https://github.com/bazel-contrib/rules_python/blob/master/docs/python.md#py_runtime_pair)." fi -exec "$PYTHON_BIN" "$@" +# Because this is a wrapper script that invokes Python, it prevents Python from +# detecting virtualenvs like normal (i.e. using the venv symlink to find the +# real interpreter). To work around this, we have to manually detect the venv, +# then trick the interpreter into understanding we're in a virtual env. +self_dir=$(dirname "$0") +if [ -e "$self_dir/pyvenv.cfg" ] || [ -e "$self_dir/../pyvenv.cfg" ]; then + case "$0" in + /*) + venv_bin="$0" + ;; + *) + venv_bin="$PWD/$0" + ;; + esac + # PYTHONEXECUTABLE is also used because `exec -a` doesn't fully trick the + # pyenv wrappers. + # NOTE: The PYTHONEXECUTABLE envvar only works for non-Mac starting in Python 3.11 + export PYTHONEXECUTABLE="$venv_bin" + # Python looks at argv[0] to determine sys.executable, so use exec -a + # to make it think it's the venv's binary, not the actual one invoked. + # NOTE: exec -a isn't strictly posix-compatible, but very widespread + exec -a "$venv_bin" "$PYTHON_BIN" "$@" +else + exec "$PYTHON_BIN" "$@" +fi diff --git a/python/private/site_init_template.py b/python/private/site_init_template.py index 40fb4e4139..6ffde85128 100644 --- a/python/private/site_init_template.py +++ b/python/private/site_init_template.py @@ -124,6 +124,11 @@ def _search_path(name): return None +# NOTE: We do not add _RUNFILES_ROOT to sys.path for two reasons: +# 1. Under workspace, it makes every external repository importable. If a Bazel +# repository matches a Python import name, they conflict. +# 2. Under bzlmod, the repo names in the runfiles directory aren't importable +# Python names, so there's no point in adding the runfiles root to sys.path. def _setup_sys_path(): seen = set(sys.path) python_path_entries = [] @@ -195,5 +200,24 @@ def _maybe_add_path(path): return coverage_setup +# The pyvenv.cfg created for py_binary leaves the `home` key unset. A +# side-effect of this is `sys._base_executable` points to the venv executable, +# not the actual executable. This mostly doesn't matter, but does affect +# using the venv module to create venvs (they point to the venv executable, not +# the actual executable). +def _fixup_sys_base_executable(): + # Must have been set correctly? + if sys.executable != sys._base_executable: + return + # Not in a venv, so don't touch anything. + if sys.prefix == sys.base_prefix: + return + exe = os.path.realpath(sys.executable) + _print_verbose("setting sys._base_executable:", exe) + sys._base_executable = exe + + +_fixup_sys_base_executable() + COVERAGE_SETUP = _setup_sys_path() _print_verbose("DONE") diff --git a/python/private/stage1_bootstrap_template.sh b/python/private/stage1_bootstrap_template.sh index c487624934..d992b55cae 100644 --- a/python/private/stage1_bootstrap_template.sh +++ b/python/private/stage1_bootstrap_template.sh @@ -9,7 +9,8 @@ fi # runfiles-relative path STAGE2_BOOTSTRAP="%stage2_bootstrap%" -# runfiles-relative path to python interpreter to use +# runfiles-relative path to python interpreter to use. +# This is the `bin/python3` path in the binary's venv. PYTHON_BINARY='%python_binary%' # The path that PYTHON_BINARY should symlink to. # runfiles-relative path, absolute path, or single word. @@ -18,8 +19,17 @@ PYTHON_BINARY_ACTUAL="%python_binary_actual%" # 0 or 1 IS_ZIPFILE="%is_zipfile%" -# 0 or 1 +# 0 or 1. +# If 1, then a venv will be created at runtime that replicates what would have +# been the build-time structure. RECREATE_VENV_AT_RUNTIME="%recreate_venv_at_runtime%" +# 0 or 1 +# If 1, then the path to python will be resolved by running +# PYTHON_BINARY_ACTUAL to determine the actual underlying interpreter. +RESOLVE_PYTHON_BINARY_AT_RUNTIME="%resolve_python_binary_at_runtime%" +# venv-relative path to the site-packages +# e.g. lib/python3.12t/site-packages +VENV_REL_SITE_PACKAGES="%venv_rel_site_packages%" # array of strings declare -a INTERPRETER_ARGS_FROM_TARGET=( @@ -152,34 +162,72 @@ elif [[ "$RECREATE_VENV_AT_RUNTIME" == "1" ]]; then fi fi - if [[ "$PYTHON_BINARY_ACTUAL" == /* ]]; then - # An absolute path, i.e. platform runtime, e.g. /usr/bin/python3 - symlink_to=$PYTHON_BINARY_ACTUAL - elif [[ "$PYTHON_BINARY_ACTUAL" == */* ]]; then - # A runfiles-relative path - symlink_to="$RUNFILES_DIR/$PYTHON_BINARY_ACTUAL" - else - # A plain word, e.g. "python3". Symlink to where PATH leads - symlink_to=$(which $PYTHON_BINARY_ACTUAL) - # Guard against trying to symlink to an empty value - if [[ $? -ne 0 ]]; then - echo >&2 "ERROR: Python to use not found on PATH: $PYTHON_BINARY_ACTUAL" - exit 1 - fi - fi - mkdir -p "$venv/bin" # Match the basename; some tools, e.g. pyvenv key off the executable name python_exe="$venv/bin/$(basename $PYTHON_BINARY_ACTUAL)" + if [[ ! -e "$python_exe" ]]; then - ln -s "$symlink_to" "$python_exe" + if [[ "$PYTHON_BINARY_ACTUAL" == /* ]]; then + # An absolute path, i.e. platform runtime, e.g. /usr/bin/python3 + python_exe_actual=$PYTHON_BINARY_ACTUAL + elif [[ "$PYTHON_BINARY_ACTUAL" == */* ]]; then + # A runfiles-relative path + python_exe_actual="$RUNFILES_DIR/$PYTHON_BINARY_ACTUAL" + else + # A plain word, e.g. "python3". Symlink to where PATH leads + python_exe_actual=$(which $PYTHON_BINARY_ACTUAL) + # Guard against trying to symlink to an empty value + if [[ $? -ne 0 ]]; then + echo >&2 "ERROR: Python to use not found on PATH: $PYTHON_BINARY_ACTUAL" + exit 1 + fi + fi + + runfiles_venv="$RUNFILES_DIR/$(dirname $(dirname $PYTHON_BINARY))" + # When RESOLVE_PYTHON_BINARY_AT_RUNTIME is true, it means the toolchain + # has thrown two complications at us: + # 1. The build-time assumption of the Python version may not match the + # runtime Python version. The site-packages directory path includes the + # Python version, so when the versions don't match, the runtime won't + # find it. + # 2. The interpreter might be a wrapper script, which interferes with Python's + # ability to detect when it's within a venv. Starting in Python 3.11, + # the PYTHONEXECUTABLE environment variable can fix this, but due to (1), + # we don't know if that is supported without running Python. + # To fix (1), we symlink the desired site-packages path to the build-time + # directory. Hopefully the version mismatch is OK :D. + # To fix (2), we determine the actual underlying interpreter and symlink + # to that. + if [[ "$RESOLVE_PYTHON_BINARY_AT_RUNTIME" == "1" ]]; then + { + read -r resolved_py_exe + read -r resolved_site_packages + } < <("$python_exe_actual" -I <