-
-
Notifications
You must be signed in to change notification settings - Fork 636
feat: provide access to arbitrary interpreters #2507
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
rickeylev
merged 42 commits into
bazel-contrib:main
from
philsc:unreviewed/philsc/interpreter
Feb 16, 2025
Merged
Changes from 32 commits
Commits
Show all changes
42 commits
Select commit
Hold shift + click to select a range
f12f5c3
wip: helper to run an arbitrary interpreter or interpreter from a binary
rickeylev 7507626
Basic REPL support
philsc 9730855
experiment with site packages
philsc 2c3fc1b
Merge remote-tracking branch 'upstream/main' into HEAD
philsc f819bb0
Merge remote-tracking branch 'rickeylev/feat.tools.run' into HEAD
philsc 286b4f1
consolidate files a bit
philsc 314447d
revert REPL-related things
philsc 3fb3236
Merge remote-tracking branch 'upstream/main' into HEAD
philsc e07a528
add integration test
philsc 91d66df
add some docs
philsc c71629f
rename to :python and incorporate readme feedback
philsc 2ee2311
move implementation to //python/private
philsc 620bf31
Add a test using transitions instead of an integration test
philsc d4b7978
Add python_src tests
philsc c2f927f
Merge remote-tracking branch 'upstream/main' into HEAD
philsc 7ede58a
black
philsc 8cd6de0
delete integration test
philsc 8c2495b
delete unused files
philsc d7bce25
delete unused files
philsc d0c8304
delete unused files
philsc 63924fe
revert unused changes
philsc 94d5ee3
pre-commit
philsc 8e935f4
Fix Windows hopefully
philsc d39a0a1
fixup
philsc abcc5e9
fix: Enable location expansion for `sh_py_run_test`
philsc 0c365e9
Merge commit 'abcc5e9d' into HEAD
philsc 81b26c6
buildifier fixes hopefully
philsc cfd96c8
delete superfluous runfiles
philsc 46b8f89
Merge remote-tracking branch 'upstream/main' into HEAD
philsc cadfc9a
get remote execution working
philsc 155489f
incorporate feedback
philsc 83a774d
buildifier
philsc 4d15a73
explore using ctx.actions.declare_symlink
philsc 0b8920d
Merge remote-tracking branch 'origin/main' into HEAD
philsc 77a75d7
revert unnecessary change
philsc 5eae601
Merge remote-tracking branch 'origin/main' into HEAD
philsc ddcf738
incorporate feedback
philsc faa37b3
add missing file
philsc 682762d
lint
philsc 69d647b
add docstring
philsc ebe1842
simplify the code a bit
philsc ccf7715
use full runfiles path; add basic docs
rickeylev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
load("//python/private:interpreter.bzl", _interpreter_binary = "interpreter_binary") | ||
|
||
filegroup( | ||
name = "distribution", | ||
srcs = glob(["**"]), | ||
visibility = ["//:__subpackages__"], | ||
) | ||
|
||
_interpreter_binary( | ||
name = "python", | ||
binary = ":python_src", | ||
visibility = ["//visibility:public"], | ||
) | ||
|
||
# The user can modify this flag to source different interpreters for the | ||
# `python` target above. | ||
label_flag( | ||
name = "python_src", | ||
build_setting_default = "//python:none", | ||
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
# Copyright 2025 The Bazel Authors. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
"""Implementation of the rules to access the underlying Python interpreter.""" | ||
|
||
load("@bazel_skylib//lib:paths.bzl", "paths") | ||
load("//python:py_runtime_info.bzl", "PyRuntimeInfo") | ||
load(":sentinel.bzl", "SentinelInfo") | ||
load(":toolchain_types.bzl", "TARGET_TOOLCHAIN_TYPE") | ||
|
||
def _interpreter_binary_impl(ctx): | ||
if SentinelInfo in ctx.attr.binary: | ||
toolchain = ctx.toolchains[TARGET_TOOLCHAIN_TYPE] | ||
runtime = toolchain.py3_runtime | ||
else: | ||
runtime = ctx.attr.binary[PyRuntimeInfo] | ||
|
||
# NOTE: We name the output filename after the underlying file name | ||
# because of things like pyenv: they use $0 to determine what to | ||
# re-exec. If it's not a recognized name, then they fail. | ||
if runtime.interpreter: | ||
executable = ctx.actions.declare_file(runtime.interpreter.basename) | ||
ctx.actions.expand_template( | ||
template = ctx.file._template, | ||
output = executable, | ||
substitutions = { | ||
"%target_file%": runtime.interpreter.short_path, | ||
rickeylev marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
}, | ||
is_executable = True, | ||
) | ||
philsc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
else: | ||
executable = ctx.actions.declare_symlink(paths.basename(runtime.interpreter_path)) | ||
ctx.actions.symlink(output = executable, target_path = runtime.interpreter_path) | ||
|
||
return [ | ||
DefaultInfo( | ||
executable = executable, | ||
runfiles = ctx.runfiles([executable], transitive_files = runtime.files).merge_all([ | ||
ctx.attr._bash_runfiles[DefaultInfo].default_runfiles, | ||
]), | ||
), | ||
] | ||
|
||
interpreter_binary = rule( | ||
implementation = _interpreter_binary_impl, | ||
toolchains = [TARGET_TOOLCHAIN_TYPE], | ||
executable = True, | ||
attrs = { | ||
"binary": attr.label( | ||
mandatory = True, | ||
), | ||
"_bash_runfiles": attr.label( | ||
default = "@bazel_tools//tools/bash/runfiles", | ||
), | ||
"_template": attr.label( | ||
default = "//python/private:interpreter_tmpl.sh", | ||
allow_single_file = True, | ||
), | ||
}, | ||
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
#!/bin/bash | ||
|
||
# --- begin runfiles.bash initialization v3 --- | ||
# Copy-pasted from the Bazel Bash runfiles library v3. | ||
set -uo pipefail; set +e; f=bazel_tools/tools/bash/runfiles/runfiles.bash | ||
# shellcheck disable=SC1090 | ||
source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || \ | ||
source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || \ | ||
source "$0.runfiles/$f" 2>/dev/null || \ | ||
source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \ | ||
source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \ | ||
{ echo>&2 "ERROR: cannot find $f"; exit 1; }; f=; set -e | ||
# --- end runfiles.bash initialization v3 --- | ||
|
||
readonly TARGET_FILE="%target_file%" | ||
|
||
MAIN_BIN="$(rlocation "${TARGET_FILE#*/}")" | ||
|
||
exec "${MAIN_BIN}" "$@" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
# Copyright 2024 The Bazel Authors. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
load("//tests/support:sh_py_run_test.bzl", "py_reconfig_test") | ||
|
||
PYTHON_VERSIONS_TO_TEST = ( | ||
"3.10", | ||
"3.11", | ||
"3.12", | ||
) | ||
|
||
[py_reconfig_test( | ||
name = "python_version_%s_test" % python_version, | ||
srcs = ["interpreter_test.py"], | ||
data = [ | ||
"//python/bin:python", | ||
], | ||
env = { | ||
# Both the interpreter and the test itself are expected to run under | ||
# the same version. | ||
"EXPECTED_INTERPRETER_VERSION": python_version, | ||
"EXPECTED_SELF_VERSION": python_version, | ||
"PYTHON_BIN": "$(rootpath //python/bin:python)", | ||
}, | ||
main = "interpreter_test.py", | ||
python_version = python_version, | ||
) for python_version in PYTHON_VERSIONS_TO_TEST] | ||
|
||
[py_reconfig_test( | ||
philsc marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
name = "python_src_%s_test" % python_version, | ||
srcs = ["interpreter_test.py"], | ||
data = [ | ||
"//python/bin:python", | ||
], | ||
env = { | ||
# Since we're grabbing the interpreter from a binary with a fixed | ||
# version, we expect to always see that version. It doesn't matter what | ||
# Python version the test itself is running with. | ||
"EXPECTED_INTERPRETER_VERSION": "3.11", | ||
# The test itself is still running under different Python versions. | ||
"EXPECTED_SELF_VERSION": python_version, | ||
"PYTHON_BIN": "$(rootpath //python/bin:python)", | ||
}, | ||
main = "interpreter_test.py", | ||
python_src = "//tools/publish:twine", | ||
python_version = python_version, | ||
) for python_version in PYTHON_VERSIONS_TO_TEST] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
# Copyright 2024 The Bazel Authors. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import os | ||
import subprocess | ||
import sys | ||
import unittest | ||
|
||
|
||
class InterpreterTest(unittest.TestCase): | ||
def setUp(self): | ||
philsc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
super().setUp() | ||
self.interpreter = os.environ["PYTHON_BIN"] | ||
|
||
def test_self_version(self): | ||
"""Performs a sanity check on the Python version used for this test.""" | ||
expected_version = os.environ["EXPECTED_SELF_VERSION"] | ||
v = sys.version_info | ||
self.assertEqual(expected_version, f"{v.major}.{v.minor}") | ||
|
||
def test_interpreter_version(self): | ||
"""Validates that we can successfully execute arbitrary code from the CLI.""" | ||
expected_version = os.environ["EXPECTED_INTERPRETER_VERSION"] | ||
|
||
try: | ||
result = subprocess.check_output( | ||
[self.interpreter], | ||
text=True, | ||
stderr=subprocess.STDOUT, | ||
input="\r".join( | ||
[ | ||
"import sys", | ||
"v = sys.version_info", | ||
"print(f'version: {v.major}.{v.minor}')", | ||
] | ||
), | ||
).strip() | ||
except subprocess.CalledProcessError as error: | ||
print("OUTPUT:", error.stdout) | ||
raise | ||
|
||
self.assertEqual(result, f"version: {expected_version}") | ||
|
||
def test_json_tool(self): | ||
"""Validates that we can successfully invoke a module from the CLI.""" | ||
# Pass unformatted JSON to the json.tool module. | ||
try: | ||
result = subprocess.check_output( | ||
[ | ||
self.interpreter, | ||
"-m", | ||
"json.tool", | ||
], | ||
text=True, | ||
stderr=subprocess.STDOUT, | ||
input='{"json":"obj"}', | ||
).strip() | ||
except subprocess.CalledProcessError as error: | ||
print("OUTPUT:", error.stdout) | ||
raise | ||
|
||
# Validate that we get formatted JSON back. | ||
self.assertEqual(result, '{\n "json": "obj"\n}') | ||
|
||
|
||
if __name__ == "__main__": | ||
unittest.main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.