Skip to content

Commit 63114a3

Browse files
authored
refactor: move hermetic Python runtime setup into macro (bazel-contrib#2221)
This stems from conversation in bazel-contrib#2216. Moving the logic into a loading-phase macro makes it easier to understand how a repo with a python-build-standalone extracted archive has its toolchain defined. This also makes it easier to compare with the local runtime repo setup to try and find commonality in the future. Along the way: * Remove some Bazel 5 compatibility code: coverage_tool is now always passed to py_runtime. (Bazel 5 support was dropped earlier this year and we stopped testing with it; it's likely already broken with Bazel 5). * Add `semver.to_dict`, which makes it easier to pass into format() functions.
1 parent b3862ec commit 63114a3

File tree

4 files changed

+199
-145
lines changed

4 files changed

+199
-145
lines changed

examples/bzlmod/MODULE.bazel.lock

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
# Copyright 2024 The Bazel Authors. All rights reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
"""Setup a python-build-standalone based toolchain."""
15+
16+
load("@rules_cc//cc:defs.bzl", "cc_import", "cc_library")
17+
load("//python:py_runtime.bzl", "py_runtime")
18+
load("//python:py_runtime_pair.bzl", "py_runtime_pair")
19+
load("//python/cc:py_cc_toolchain.bzl", "py_cc_toolchain")
20+
load(":py_exec_tools_toolchain.bzl", "py_exec_tools_toolchain")
21+
load(":semver.bzl", "semver")
22+
23+
def define_hermetic_runtime_toolchain_impl(
24+
*,
25+
name,
26+
extra_files_glob_include,
27+
extra_files_glob_exclude,
28+
python_version,
29+
python_bin,
30+
coverage_tool):
31+
"""Define a toolchain implementation for a python-build-standalone repo.
32+
33+
It expected this macro is called in the top-level package of an extracted
34+
python-build-standalone repository. See
35+
python/private/python_repositories.bzl for how it is invoked.
36+
37+
Args:
38+
name: {type}`str` name used for tools to identify the invocation.
39+
extra_files_glob_include: {type}`list[str]` additional glob include
40+
patterns for the target runtime files (the one included in
41+
binaries).
42+
extra_files_glob_exclude: {type}`list[str]` additional glob exclude
43+
patterns for the target runtime files.
44+
python_version: {type}`str` The Python version, in `major.minor.micro`
45+
format.
46+
python_bin: {type}`str` The path to the Python binary within the
47+
repositoroy.
48+
coverage_tool: {type}`str` optional target to the coverage tool to
49+
use.
50+
"""
51+
_ = name # @unused
52+
version_info = semver(python_version)
53+
version_dict = version_info.to_dict()
54+
native.filegroup(
55+
name = "files",
56+
srcs = native.glob(
57+
include = [
58+
"bin/**",
59+
"extensions/**",
60+
"include/**",
61+
"libs/**",
62+
"share/**",
63+
] + extra_files_glob_include,
64+
# Platform-agnostic filegroup can't match on all patterns.
65+
allow_empty = True,
66+
exclude = [
67+
"**/* *", # Bazel does not support spaces in file names.
68+
# Unused shared libraries. `python` executable and the `:libpython` target
69+
# depend on `libpython{python_version}.so.1.0`.
70+
"lib/libpython{major}.{minor}.so".format(**version_dict),
71+
# static libraries
72+
"lib/**/*.a",
73+
# tests for the standard libraries.
74+
"lib/python{major}.{minor}/**/test/**".format(**version_dict),
75+
"lib/python{major}.{minor}/**/tests/**".format(**version_dict),
76+
"**/__pycache__/*.pyc.*", # During pyc creation, temp files named *.pyc.NNN are created
77+
] + extra_files_glob_exclude,
78+
),
79+
)
80+
cc_import(
81+
name = "interface",
82+
interface_library = "libs/python{major}{minor}.lib".format(**version_dict),
83+
system_provided = True,
84+
)
85+
86+
native.filegroup(
87+
name = "includes",
88+
srcs = native.glob(["include/**/*.h"]),
89+
)
90+
cc_library(
91+
name = "python_headers",
92+
deps = select({
93+
"@bazel_tools//src/conditions:windows": [":interface"],
94+
"//conditions:default": None,
95+
}),
96+
hdrs = [":includes"],
97+
includes = [
98+
"include",
99+
"include/python{major}.{minor}".format(**version_dict),
100+
"include/python{major}.{minor}m".format(**version_dict),
101+
],
102+
)
103+
cc_library(
104+
name = "libpython",
105+
hdrs = [":includes"],
106+
srcs = select({
107+
"@platforms//os:linux": [
108+
"lib/libpython{major}.{minor}.so".format(**version_dict),
109+
"lib/libpython{major}.{minor}.so.1.0".format(**version_dict),
110+
],
111+
"@platforms//os:macos": ["lib/libpython{major}.{minor}.dylib".format(**version_dict)],
112+
"@platforms//os:windows": ["python3.dll", "libs/python{major}{minor}.lib".format(**version_dict)],
113+
}),
114+
)
115+
116+
native.exports_files(["python", python_bin])
117+
118+
# Used to only download coverage toolchain when the coverage is collected by
119+
# bazel.
120+
native.config_setting(
121+
name = "coverage_enabled",
122+
values = {"collect_code_coverage": "true"},
123+
visibility = ["//visibility:private"],
124+
)
125+
126+
py_runtime(
127+
name = "py3_runtime",
128+
files = [":files"],
129+
interpreter = python_bin,
130+
interpreter_version_info = {
131+
"major": str(version_info.major),
132+
"micro": str(version_info.patch),
133+
"minor": str(version_info.minor),
134+
},
135+
# Convert empty string to None
136+
coverage_tool = coverage_tool or None,
137+
python_version = "PY3",
138+
implementation_name = "cpython",
139+
# See https://peps.python.org/pep-3147/ for pyc tag infix format
140+
pyc_tag = "cpython-{major}{minor}".format(**version_dict),
141+
)
142+
143+
py_runtime_pair(
144+
name = "python_runtimes",
145+
py2_runtime = None,
146+
py3_runtime = ":py3_runtime",
147+
)
148+
149+
py_cc_toolchain(
150+
name = "py_cc_toolchain",
151+
headers = ":python_headers",
152+
libs = ":libpython",
153+
python_version = python_version,
154+
)
155+
156+
py_exec_tools_toolchain(
157+
name = "py_exec_tools_toolchain",
158+
# This macro is called in another repo: use Label() to ensure it
159+
# resolves in the rules_python context.
160+
precompiler = Label("//tools/precompiler:precompiler"),
161+
)

python/private/python_repositories.bzl

Lines changed: 22 additions & 139 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ load(":coverage_deps.bzl", "coverage_dep")
3434
load(":full_version.bzl", "full_version")
3535
load(":internal_config_repo.bzl", "internal_config_repo")
3636
load(":repo_utils.bzl", "REPO_DEBUG_ENV_VAR", "repo_utils")
37+
load(":text_util.bzl", "render")
3738
load(
3839
":toolchains_repo.bzl",
3940
"host_toolchain",
@@ -246,20 +247,6 @@ def _python_repository_impl(rctx):
246247

247248
python_bin = "python.exe" if ("windows" in platform) else "bin/python3"
248249

249-
glob_include = []
250-
glob_exclude = [
251-
"**/* *", # Bazel does not support spaces in file names.
252-
# Unused shared libraries. `python` executable and the `:libpython` target
253-
# depend on `libpython{python_version}.so.1.0`.
254-
"lib/libpython{python_version}.so".format(python_version = python_short_version),
255-
# static libraries
256-
"lib/**/*.a",
257-
# tests for the standard libraries.
258-
"lib/python{python_version}/**/test/**".format(python_version = python_short_version),
259-
"lib/python{python_version}/**/tests/**".format(python_version = python_short_version),
260-
"**/__pycache__/*.pyc.*", # During pyc creation, temp files named *.pyc.NNN are created
261-
]
262-
263250
if "linux" in platform:
264251
# Workaround around https://github.com/indygreg/python-build-standalone/issues/231
265252
for url in urls:
@@ -281,6 +268,8 @@ def _python_repository_impl(rctx):
281268
rctx.delete("share/terminfo")
282269
break
283270

271+
glob_include = []
272+
glob_exclude = []
284273
if rctx.attr.ignore_root_user_error or "windows" in platform:
285274
glob_exclude += [
286275
# These pycache files are created on first use of the associated python files.
@@ -295,148 +284,42 @@ def _python_repository_impl(rctx):
295284
glob_include += [
296285
"*.exe",
297286
"*.dll",
298-
"bin/**",
299287
"DLLs/**",
300-
"extensions/**",
301-
"include/**",
302288
"Lib/**",
303-
"libs/**",
304289
"Scripts/**",
305-
"share/**",
306290
"tcl/**",
307291
]
308292
else:
309-
glob_include += [
310-
"bin/**",
311-
"extensions/**",
312-
"include/**",
293+
glob_include.append(
313294
"lib/**",
314-
"libs/**",
315-
"share/**",
316-
]
295+
)
317296

318-
if rctx.attr.coverage_tool:
319-
if "windows" in platform:
320-
coverage_tool = None
321-
else:
322-
coverage_tool = '"{}"'.format(rctx.attr.coverage_tool)
323-
324-
coverage_attr_text = """\
325-
coverage_tool = select({{
326-
":coverage_enabled": {coverage_tool},
327-
"//conditions:default": None
328-
}}),
329-
""".format(coverage_tool = coverage_tool)
297+
if "windows" in platform:
298+
coverage_tool = None
330299
else:
331-
coverage_attr_text = " # coverage_tool attribute not supported by this Bazel version"
300+
coverage_tool = rctx.attr.coverage_tool
332301

333302
build_content = """\
334-
# Generated by python/repositories.bzl
303+
# Generated by python/private/python_repositories.bzl
335304
336-
load("@rules_python//python:py_runtime.bzl", "py_runtime")
337-
load("@rules_python//python:py_runtime_pair.bzl", "py_runtime_pair")
338-
load("@rules_python//python/cc:py_cc_toolchain.bzl", "py_cc_toolchain")
339-
load("@rules_python//python/private:py_exec_tools_toolchain.bzl", "py_exec_tools_toolchain")
305+
load("@rules_python//python/private:hermetic_runtime_repo_setup.bzl", "define_hermetic_runtime_toolchain_impl")
340306
341307
package(default_visibility = ["//visibility:public"])
342308
343-
filegroup(
344-
name = "files",
345-
srcs = glob(
346-
include = {glob_include},
347-
# Platform-agnostic filegroup can't match on all patterns.
348-
allow_empty = True,
349-
exclude = {glob_exclude},
350-
),
351-
)
352-
353-
cc_import(
354-
name = "interface",
355-
interface_library = "libs/python{python_version_nodot}.lib",
356-
system_provided = True,
357-
)
358-
359-
filegroup(
360-
name = "includes",
361-
srcs = glob(["include/**/*.h"]),
362-
)
363-
364-
cc_library(
365-
name = "python_headers",
366-
deps = select({{
367-
"@bazel_tools//src/conditions:windows": [":interface"],
368-
"//conditions:default": None,
369-
}}),
370-
hdrs = [":includes"],
371-
includes = [
372-
"include",
373-
"include/python{python_version}",
374-
"include/python{python_version}m",
375-
],
376-
)
377-
378-
cc_library(
379-
name = "libpython",
380-
hdrs = [":includes"],
381-
srcs = select({{
382-
"@platforms//os:windows": ["python3.dll", "libs/python{python_version_nodot}.lib"],
383-
"@platforms//os:macos": ["lib/libpython{python_version}.dylib"],
384-
"@platforms//os:linux": ["lib/libpython{python_version}.so", "lib/libpython{python_version}.so.1.0"],
385-
}}),
386-
)
387-
388-
exports_files(["python", "{python_path}"])
389-
390-
# Used to only download coverage toolchain when the coverage is collected by
391-
# bazel.
392-
config_setting(
393-
name = "coverage_enabled",
394-
values = {{"collect_code_coverage": "true"}},
395-
visibility = ["//visibility:private"],
396-
)
397-
398-
py_runtime(
399-
name = "py3_runtime",
400-
files = [":files"],
401-
{coverage_attr}
402-
interpreter = "{python_path}",
403-
interpreter_version_info = {{
404-
"major": "{interpreter_version_info_major}",
405-
"minor": "{interpreter_version_info_minor}",
406-
"micro": "{interpreter_version_info_micro}",
407-
}},
408-
python_version = "PY3",
409-
implementation_name = 'cpython',
410-
pyc_tag = "cpython-{interpreter_version_info_major}{interpreter_version_info_minor}",
411-
)
412-
413-
py_runtime_pair(
414-
name = "python_runtimes",
415-
py2_runtime = None,
416-
py3_runtime = ":py3_runtime",
417-
)
418-
419-
py_cc_toolchain(
420-
name = "py_cc_toolchain",
421-
headers = ":python_headers",
422-
libs = ":libpython",
423-
python_version = "{python_version}",
424-
)
425-
426-
py_exec_tools_toolchain(
427-
name = "py_exec_tools_toolchain",
428-
precompiler = "@rules_python//tools/precompiler:precompiler",
309+
define_hermetic_runtime_toolchain_impl(
310+
name = "define_runtime",
311+
extra_files_glob_include = {extra_files_glob_include},
312+
extra_files_glob_exclude = {extra_files_glob_exclude},
313+
python_version = {python_version},
314+
python_bin = {python_bin},
315+
coverage_tool = {coverage_tool},
429316
)
430317
""".format(
431-
glob_exclude = repr(glob_exclude),
432-
glob_include = repr(glob_include),
433-
python_path = python_bin,
434-
python_version = python_short_version,
435-
python_version_nodot = python_short_version.replace(".", ""),
436-
coverage_attr = coverage_attr_text,
437-
interpreter_version_info_major = python_version_info[0],
438-
interpreter_version_info_minor = python_version_info[1],
439-
interpreter_version_info_micro = python_version_info[2],
318+
extra_files_glob_exclude = render.list(glob_exclude),
319+
extra_files_glob_include = render.list(glob_include),
320+
python_bin = render.str(python_bin),
321+
python_version = render.str(rctx.attr.python_version),
322+
coverage_tool = render.str(coverage_tool),
440323
)
441324
rctx.delete("python")
442325
rctx.symlink(python_bin, "python")

0 commit comments

Comments
 (0)