-
-
Notifications
You must be signed in to change notification settings - Fork 571
/
Copy pathpy_executable.bzl
1946 lines (1738 loc) · 74.3 KB
/
py_executable.bzl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2022 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.
"""Common functionality between test/binary executables."""
load("@bazel_skylib//lib:dicts.bzl", "dicts")
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_skylib//lib:structs.bzl", "structs")
load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")
load("@rules_cc//cc/common:cc_common.bzl", "cc_common")
load(":attr_builders.bzl", "attrb")
load(
":attributes.bzl",
"AGNOSTIC_EXECUTABLE_ATTRS",
"COMMON_ATTRS",
"COVERAGE_ATTRS",
"IMPORTS_ATTRS",
"PY_SRCS_ATTRS",
"PrecompileAttr",
"PycCollectionAttr",
"REQUIRED_EXEC_GROUP_BUILDERS",
)
load(":builders.bzl", "builders")
load(":cc_helper.bzl", "cc_helper")
load(
":common.bzl",
"collect_cc_info",
"collect_imports",
"collect_runfiles",
"create_binary_semantics_struct",
"create_cc_details_struct",
"create_executable_result_struct",
"create_instrumented_files_info",
"create_output_group_info",
"create_py_info",
"csv",
"filter_to_py_srcs",
"get_imports",
"is_bool",
"runfiles_root_path",
"target_platform_has_any_constraint",
)
load(":flags.bzl", "BootstrapImplFlag", "VenvsUseDeclareSymlinkFlag")
load(":precompile.bzl", "maybe_precompile")
load(":py_cc_link_params_info.bzl", "PyCcLinkParamsInfo")
load(":py_executable_info.bzl", "PyExecutableInfo")
load(":py_info.bzl", "PyInfo")
load(":py_internal.bzl", "py_internal")
load(":py_runtime_info.bzl", "DEFAULT_STUB_SHEBANG", "PyRuntimeInfo")
load(":reexports.bzl", "BuiltinPyInfo", "BuiltinPyRuntimeInfo")
load(":rule_builders.bzl", "ruleb")
load(
":semantics.bzl",
"ALLOWED_MAIN_EXTENSIONS",
"BUILD_DATA_SYMLINK_PATH",
"IS_BAZEL",
"PY_RUNTIME_ATTR_NAME",
)
load(
":toolchain_types.bzl",
"EXEC_TOOLS_TOOLCHAIN_TYPE",
"TARGET_TOOLCHAIN_TYPE",
TOOLCHAIN_TYPE = "TARGET_TOOLCHAIN_TYPE",
)
_py_builtins = py_internal
_EXTERNAL_PATH_PREFIX = "external"
_ZIP_RUNFILES_DIRECTORY_NAME = "runfiles"
_PYTHON_VERSION_FLAG = str(Label("//python/config_settings:python_version"))
# Non-Google-specific attributes for executables
# These attributes are for rules that accept Python sources.
EXECUTABLE_ATTRS = dicts.add(
COMMON_ATTRS,
AGNOSTIC_EXECUTABLE_ATTRS,
PY_SRCS_ATTRS,
IMPORTS_ATTRS,
COVERAGE_ATTRS,
{
"interpreter_args": lambda: attrb.StringList(
doc = """
Arguments that are only applicable to the interpreter.
The args an interpreter supports are specific to the interpreter. For
CPython, see https://docs.python.org/3/using/cmdline.html.
:::{note}
Only supported for {obj}`--bootstrap_impl=script`. Ignored otherwise.
:::
:::{seealso}
The {obj}`RULES_PYTHON_ADDITIONAL_INTERPRETER_ARGS` environment variable
:::
:::{versionadded} VERSION_NEXT_FEATURE
:::
""",
),
"legacy_create_init": lambda: attrb.Int(
default = -1,
values = [-1, 0, 1],
doc = """\
Whether to implicitly create empty `__init__.py` files in the runfiles tree.
These are created in every directory containing Python source code or shared
libraries, and every parent directory of those directories, excluding the repo
root directory. The default, `-1` (auto), means true unless
`--incompatible_default_to_explicit_init_py` is used. If false, the user is
responsible for creating (possibly empty) `__init__.py` files and adding them to
the `srcs` of Python targets as required.
""",
),
# TODO(b/203567235): In the Java impl, any file is allowed. While marked
# label, it is more treated as a string, and doesn't have to refer to
# anything that exists because it gets treated as suffix-search string
# over `srcs`.
"main": lambda: attrb.Label(
allow_single_file = True,
doc = """\
Optional; the name of the source file that is the main entry point of the
application. This file must also be listed in `srcs`. If left unspecified,
`name`, with `.py` appended, is used instead. If `name` does not match any
filename in `srcs`, `main` must be specified.
This is mutually exclusive with {obj}`main_module`.
""",
),
"main_module": lambda: attrb.String(
doc = """
Module name to execute as the main program.
When set, `srcs` is not required, and it is assumed the module is
provided by a dependency.
See https://docs.python.org/3/using/cmdline.html#cmdoption-m for more
information about running modules as the main program.
This is mutually exclusive with {obj}`main`.
:::{versionadded} VERSION_NEXT_FEATURE
:::
""",
),
"pyc_collection": lambda: attrb.String(
default = PycCollectionAttr.INHERIT,
values = sorted(PycCollectionAttr.__members__.values()),
doc = """
Determines whether pyc files from dependencies should be manually included.
Valid values are:
* `inherit`: Inherit the value from {flag}`--precompile`.
* `include_pyc`: Add implicitly generated pyc files from dependencies. i.e.
pyc files for targets that specify {attr}`precompile="inherit"`.
* `disabled`: Don't add implicitly generated pyc files. Note that
pyc files may still come from dependencies that enable precompiling at the
target level.
""",
),
"python_version": lambda: attrb.String(
# TODO(b/203567235): In the Java impl, the default comes from
# --python_version. Not clear what the Starlark equivalent is.
doc = """
The Python version this target should use.
The value should be in `X.Y` or `X.Y.Z` (or compatible) format. If empty or
unspecified, the incoming configuration's {obj}`--python_version` flag is
inherited. For backwards compatibility, the values `PY2` and `PY3` are
accepted, but treated as an empty/unspecified value.
:::{note}
In order for the requested version to be used, there must be a
toolchain configured to match the Python version. If there isn't, then it
may be silently ignored, or an error may occur, depending on the toolchain
configuration.
:::
:::{versionchanged} 1.1.0
This attribute was changed from only accepting `PY2` and `PY3` values to
accepting arbitrary Python versions.
:::
""",
),
# Required to opt-in to the transition feature.
"_allowlist_function_transition": lambda: attrb.Label(
default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
),
"_bootstrap_impl_flag": lambda: attrb.Label(
default = "//python/config_settings:bootstrap_impl",
providers = [BuildSettingInfo],
),
"_bootstrap_template": lambda: attrb.Label(
allow_single_file = True,
default = "@bazel_tools//tools/python:python_bootstrap_template.txt",
),
"_launcher": lambda: attrb.Label(
cfg = "target",
# NOTE: This is an executable, but is only used for Windows. It
# can't have executable=True because the backing target is an
# empty target for other platforms.
default = "//tools/launcher:launcher",
),
"_py_interpreter": lambda: attrb.Label(
# The configuration_field args are validated when called;
# we use the precense of py_internal to indicate this Bazel
# build has that fragment and name.
default = configuration_field(
fragment = "bazel_py",
name = "python_top",
) if py_internal else None,
),
# TODO: This appears to be vestigial. It's only added because
# GraphlessQueryTest.testLabelsOperator relies on it to test for
# query behavior of implicit dependencies.
"_py_toolchain_type": attr.label(
default = TARGET_TOOLCHAIN_TYPE,
),
"_python_version_flag": lambda: attrb.Label(
default = "//python/config_settings:python_version",
),
"_venvs_use_declare_symlink_flag": lambda: attrb.Label(
default = "//python/config_settings:venvs_use_declare_symlink",
providers = [BuildSettingInfo],
),
"_windows_constraints": lambda: attrb.LabelList(
default = [
"@platforms//os:windows",
],
),
"_windows_launcher_maker": lambda: attrb.Label(
default = "@bazel_tools//tools/launcher:launcher_maker",
cfg = "exec",
executable = True,
),
"_zipper": lambda: attrb.Label(
cfg = "exec",
executable = True,
default = "@bazel_tools//tools/zip:zipper",
),
},
)
def convert_legacy_create_init_to_int(kwargs):
"""Convert "legacy_create_init" key to int, in-place.
Args:
kwargs: The kwargs to modify. The key "legacy_create_init", if present
and bool, will be converted to its integer value, in place.
"""
if is_bool(kwargs.get("legacy_create_init")):
kwargs["legacy_create_init"] = 1 if kwargs["legacy_create_init"] else 0
def py_executable_impl(ctx, *, is_test, inherited_environment):
return py_executable_base_impl(
ctx = ctx,
semantics = create_binary_semantics(),
is_test = is_test,
inherited_environment = inherited_environment,
)
def create_binary_semantics():
return create_binary_semantics_struct(
# keep-sorted start
create_executable = _create_executable,
get_cc_details_for_binary = _get_cc_details_for_binary,
get_central_uncachable_version_file = lambda ctx: None,
get_coverage_deps = _get_coverage_deps,
get_debugger_deps = _get_debugger_deps,
get_extra_common_runfiles_for_binary = lambda ctx: ctx.runfiles(),
get_extra_providers = _get_extra_providers,
get_extra_write_build_data_env = lambda ctx: {},
get_imports = get_imports,
get_interpreter_path = _get_interpreter_path,
get_native_deps_dso_name = _get_native_deps_dso_name,
get_native_deps_user_link_flags = _get_native_deps_user_link_flags,
get_stamp_flag = _get_stamp_flag,
maybe_precompile = maybe_precompile,
should_build_native_deps_dso = lambda ctx: False,
should_create_init_files = _should_create_init_files,
should_include_build_data = lambda ctx: False,
# keep-sorted end
)
def _get_coverage_deps(ctx, runtime_details):
_ = ctx, runtime_details # @unused
return []
def _get_debugger_deps(ctx, runtime_details):
_ = ctx, runtime_details # @unused
return []
def _get_extra_providers(ctx, main_py, runtime_details):
_ = ctx, main_py, runtime_details # @unused
return []
def _get_stamp_flag(ctx):
# NOTE: Undocumented API; private to builtins
return ctx.configuration.stamp_binaries
def _should_create_init_files(ctx):
if ctx.attr.legacy_create_init == -1:
return not ctx.fragments.py.default_to_explicit_init_py
else:
return bool(ctx.attr.legacy_create_init)
def _create_executable(
ctx,
*,
executable,
main_py,
imports,
is_test,
runtime_details,
cc_details,
native_deps_details,
runfiles_details):
_ = is_test, cc_details, native_deps_details # @unused
is_windows = target_platform_has_any_constraint(ctx, ctx.attr._windows_constraints)
if is_windows:
if not executable.extension == "exe":
fail("Should not happen: somehow we are generating a non-.exe file on windows")
base_executable_name = executable.basename[0:-4]
else:
base_executable_name = executable.basename
venv = None
# The check for stage2_bootstrap_template is to support legacy
# BuiltinPyRuntimeInfo providers, which is likely to come from
# @bazel_tools//tools/python:autodetecting_toolchain, the toolchain used
# for workspace builds when no rules_python toolchain is configured.
if (BootstrapImplFlag.get_value(ctx) == BootstrapImplFlag.SCRIPT and
runtime_details.effective_runtime and
hasattr(runtime_details.effective_runtime, "stage2_bootstrap_template")):
venv = _create_venv(
ctx,
output_prefix = base_executable_name,
imports = imports,
runtime_details = runtime_details,
)
stage2_bootstrap = _create_stage2_bootstrap(
ctx,
output_prefix = base_executable_name,
output_sibling = executable,
main_py = main_py,
imports = imports,
runtime_details = runtime_details,
)
extra_runfiles = ctx.runfiles([stage2_bootstrap] + venv.files_without_interpreter)
zip_main = _create_zip_main(
ctx,
stage2_bootstrap = stage2_bootstrap,
runtime_details = runtime_details,
venv = venv,
)
else:
stage2_bootstrap = None
extra_runfiles = ctx.runfiles()
zip_main = ctx.actions.declare_file(base_executable_name + ".temp", sibling = executable)
_create_stage1_bootstrap(
ctx,
output = zip_main,
main_py = main_py,
imports = imports,
is_for_zip = True,
runtime_details = runtime_details,
)
zip_file = ctx.actions.declare_file(base_executable_name + ".zip", sibling = executable)
_create_zip_file(
ctx,
output = zip_file,
original_nonzip_executable = executable,
zip_main = zip_main,
runfiles = runfiles_details.default_runfiles.merge(extra_runfiles),
)
extra_files_to_build = []
# NOTE: --build_python_zip defaults to true on Windows
build_zip_enabled = ctx.fragments.py.build_python_zip
# When --build_python_zip is enabled, then the zip file becomes
# one of the default outputs.
if build_zip_enabled:
extra_files_to_build.append(zip_file)
# The logic here is a bit convoluted. Essentially, there are 3 types of
# executables produced:
# 1. (non-Windows) A bootstrap template based program.
# 2. (non-Windows) A self-executable zip file of a bootstrap template based program.
# 3. (Windows) A native Windows executable that finds and launches
# the actual underlying Bazel program (one of the above). Note that
# it implicitly assumes one of the above is located next to it, and
# that --build_python_zip defaults to true for Windows.
should_create_executable_zip = False
bootstrap_output = None
if not is_windows:
if build_zip_enabled:
should_create_executable_zip = True
else:
bootstrap_output = executable
else:
_create_windows_exe_launcher(
ctx,
output = executable,
use_zip_file = build_zip_enabled,
python_binary_path = runtime_details.executable_interpreter_path,
)
if not build_zip_enabled:
# On Windows, the main executable has an "exe" extension, so
# here we re-use the un-extensioned name for the bootstrap output.
bootstrap_output = ctx.actions.declare_file(base_executable_name)
# The launcher looks for the non-zip executable next to
# itself, so add it to the default outputs.
extra_files_to_build.append(bootstrap_output)
if should_create_executable_zip:
if bootstrap_output != None:
fail("Should not occur: bootstrap_output should not be used " +
"when creating an executable zip")
_create_executable_zip_file(
ctx,
output = executable,
zip_file = zip_file,
stage2_bootstrap = stage2_bootstrap,
runtime_details = runtime_details,
venv = venv,
)
elif bootstrap_output:
_create_stage1_bootstrap(
ctx,
output = bootstrap_output,
stage2_bootstrap = stage2_bootstrap,
runtime_details = runtime_details,
is_for_zip = False,
imports = imports,
main_py = main_py,
venv = venv,
)
else:
# Otherwise, this should be the Windows case of launcher + zip.
# Double check this just to make sure.
if not is_windows or not build_zip_enabled:
fail(("Should not occur: The non-executable-zip and " +
"non-bootstrap-template case should have windows and zip " +
"both true, but got " +
"is_windows={is_windows} " +
"build_zip_enabled={build_zip_enabled}").format(
is_windows = is_windows,
build_zip_enabled = build_zip_enabled,
))
# The interpreter is added this late in the process so that it isn't
# added to the zipped files.
if venv:
extra_runfiles = extra_runfiles.merge(ctx.runfiles([venv.interpreter]))
return create_executable_result_struct(
extra_files_to_build = depset(extra_files_to_build),
output_groups = {"python_zip_file": depset([zip_file])},
extra_runfiles = extra_runfiles,
)
def _create_zip_main(ctx, *, stage2_bootstrap, runtime_details, venv):
python_binary = runfiles_root_path(ctx, venv.interpreter.short_path)
python_binary_actual = venv.interpreter_actual_path
# The location of this file doesn't really matter. It's added to
# the zip file as the top-level __main__.py file and not included
# elsewhere.
output = ctx.actions.declare_file(ctx.label.name + "_zip__main__.py")
ctx.actions.expand_template(
template = runtime_details.effective_runtime.zip_main_template,
output = output,
substitutions = {
"%python_binary%": python_binary,
"%python_binary_actual%": python_binary_actual,
"%stage2_bootstrap%": "{}/{}".format(
ctx.workspace_name,
stage2_bootstrap.short_path,
),
"%workspace_name%": ctx.workspace_name,
},
)
return output
def relative_path(from_, to):
"""Compute a relative path from one path to another.
Args:
from_: {type}`str` the starting directory. Note that it should be
a directory because relative-symlinks are relative to the
directory the symlink resides in.
to: {type}`str` the path that `from_` wants to point to
Returns:
{type}`str` a relative path
"""
from_parts = from_.split("/")
to_parts = to.split("/")
# Strip common leading parts from both paths
n = min(len(from_parts), len(to_parts))
for _ in range(n):
if from_parts[0] == to_parts[0]:
from_parts.pop(0)
to_parts.pop(0)
else:
break
# Impossible to compute a relative path without knowing what ".." is
if from_parts and from_parts[0] == "..":
fail("cannot compute relative path from '%s' to '%s'", from_, to)
parts = ([".."] * len(from_parts)) + to_parts
return paths.join(*parts)
# Create a venv the executable can use.
# For venv details and the venv startup process, see:
# * https://docs.python.org/3/library/venv.html
# * https://snarky.ca/how-virtual-environments-work/
# * https://github.com/python/cpython/blob/main/Modules/getpath.py
# * https://github.com/python/cpython/blob/main/Lib/site.py
def _create_venv(ctx, output_prefix, imports, runtime_details):
venv = "_{}.venv".format(output_prefix.lstrip("_"))
# The pyvenv.cfg file must be present to trigger the venv site hooks.
# Because it's paths are expected to be absolute paths, we can't reliably
# put much in it. See https://github.com/python/cpython/issues/83650
pyvenv_cfg = ctx.actions.declare_file("{}/pyvenv.cfg".format(venv))
ctx.actions.write(pyvenv_cfg, "")
runtime = runtime_details.effective_runtime
venvs_use_declare_symlink_enabled = (
VenvsUseDeclareSymlinkFlag.get_value(ctx) == VenvsUseDeclareSymlinkFlag.YES
)
if not venvs_use_declare_symlink_enabled:
if runtime.interpreter:
interpreter_actual_path = runfiles_root_path(ctx, runtime.interpreter.short_path)
else:
interpreter_actual_path = runtime.interpreter_path
py_exe_basename = paths.basename(interpreter_actual_path)
# When the venv symlinks are disabled, the $venv/bin/python3 file isn't
# needed or used at runtime. However, the zip code uses the interpreter
# File object to figure out some paths.
interpreter = ctx.actions.declare_file("{}/bin/{}".format(venv, py_exe_basename))
ctx.actions.write(interpreter, "actual:{}".format(interpreter_actual_path))
elif runtime.interpreter:
py_exe_basename = paths.basename(runtime.interpreter.short_path)
# Even though ctx.actions.symlink() is used, using
# declare_symlink() is required to ensure that the resulting file
# in runfiles is always a symlink. An RBE implementation, for example,
# may choose to write what symlink() points to instead.
interpreter = ctx.actions.declare_symlink("{}/bin/{}".format(venv, py_exe_basename))
interpreter_actual_path = runfiles_root_path(ctx, runtime.interpreter.short_path)
rel_path = relative_path(
# dirname is necessary because a relative symlink is relative to
# the directory the symlink resides within.
from_ = paths.dirname(runfiles_root_path(ctx, interpreter.short_path)),
to = interpreter_actual_path,
)
ctx.actions.symlink(output = interpreter, target_path = rel_path)
else:
py_exe_basename = paths.basename(runtime.interpreter_path)
interpreter = ctx.actions.declare_symlink("{}/bin/{}".format(venv, py_exe_basename))
ctx.actions.symlink(output = interpreter, target_path = runtime.interpreter_path)
interpreter_actual_path = runtime.interpreter_path
if runtime.interpreter_version_info:
version = "{}.{}".format(
runtime.interpreter_version_info.major,
runtime.interpreter_version_info.minor,
)
else:
version_flag = ctx.attr._python_version_flag[config_common.FeatureFlagInfo].value
version_flag_parts = version_flag.split(".")[0:2]
version = "{}.{}".format(*version_flag_parts)
# See site.py logic: free-threaded builds append "t" to the venv lib dir name
if "t" in runtime.abi_flags:
version += "t"
site_packages = "{}/lib/python{}/site-packages".format(venv, version)
pth = ctx.actions.declare_file("{}/bazel.pth".format(site_packages))
ctx.actions.write(pth, "import _bazel_site_init\n")
site_init = ctx.actions.declare_file("{}/_bazel_site_init.py".format(site_packages))
computed_subs = ctx.actions.template_dict()
computed_subs.add_joined("%imports%", imports, join_with = ":", map_each = _map_each_identity)
ctx.actions.expand_template(
template = runtime.site_init_template,
output = site_init,
substitutions = {
"%coverage_tool%": _get_coverage_tool_runfiles_path(ctx, runtime),
"%import_all%": "True" if ctx.fragments.bazel_py.python_import_all_repositories else "False",
"%site_init_runfiles_path%": "{}/{}".format(ctx.workspace_name, site_init.short_path),
"%workspace_name%": ctx.workspace_name,
},
computed_substitutions = computed_subs,
)
site_packages_symlinks = _create_site_packages_symlinks(ctx, site_packages)
return struct(
interpreter = interpreter,
recreate_venv_at_runtime = not venvs_use_declare_symlink_enabled,
# Runfiles root relative path or absolute path
interpreter_actual_path = interpreter_actual_path,
files_without_interpreter = [pyvenv_cfg, pth, site_init] + site_packages_symlinks,
)
def _create_site_packages_symlinks(ctx, site_packages):
"""Creates symlinks within site-packages.
Args:
ctx: current rule ctx
site_packages: runfiles-root-relative path to the site-packages directory
Returns:
{type}`list[File]` list of the File symlink objects created.
"""
# maps site-package symlink to the runfiles path it should point to
entries = depset(
# NOTE: Topological ordering is used so that dependencies closer to the
# binary have precedence in creating their symlinks. This allows the
# binary a modicum of control over the result.
order = "topological",
transitive = [
dep[PyInfo].site_packages_symlinks
for dep in ctx.attr.deps
if PyInfo in dep
],
).to_list()
link_map = _build_link_map(entries)
sp_files = []
for sp_dir_path, link_to in link_map.items():
sp_link = ctx.actions.declare_symlink(paths.join(site_packages, sp_dir_path))
sp_link_rf_path = runfiles_root_path(ctx, sp_link.short_path)
rel_path = relative_path(
# dirname is necessary because a relative symlink is relative to
# the directory the symlink resides within.
from_ = paths.dirname(sp_link_rf_path),
to = link_to,
)
ctx.actions.symlink(output = sp_link, target_path = rel_path)
sp_files.append(sp_link)
return sp_files
def _build_link_map(entries):
link_map = {}
for link_to_runfiles_path, site_packages_path in entries:
if site_packages_path in link_map:
# We ignore duplicates by design. The dependency closer to the
# binary gets precedence due to the topological ordering.
continue
else:
link_map[site_packages_path] = link_to_runfiles_path
# An empty link_to value means to not create the site package symlink.
# Because of the topological ordering, this allows binaries to remove
# entries by having an earlier dependency produce empty link_to values.
for sp_dir_path, link_to in link_map.items():
if not link_to:
link_map.pop(sp_dir_path)
# Remove entries that would be a child path of a created symlink.
# Earlier entries have precedence to match how exact matches are handled.
keep_link_map = {}
for _ in range(len(link_map)):
if not link_map:
break
dirname, value = link_map.popitem()
keep_link_map[dirname] = value
prefix = dirname + "/" # Add slash to prevent /X matching /XY
for maybe_suffix in link_map.keys():
maybe_suffix += "/" # Add slash to prevent /X matching /XY
if maybe_suffix.startswith(prefix) or prefix.startswith(maybe_suffix):
link_map.pop(maybe_suffix)
return keep_link_map
def _map_each_identity(v):
return v
def _get_coverage_tool_runfiles_path(ctx, runtime):
if (ctx.configuration.coverage_enabled and
runtime and
runtime.coverage_tool):
return "{}/{}".format(
ctx.workspace_name,
runtime.coverage_tool.short_path,
)
else:
return ""
def _create_stage2_bootstrap(
ctx,
*,
output_prefix,
output_sibling,
main_py,
imports,
runtime_details):
output = ctx.actions.declare_file(
# Prepend with underscore to prevent pytest from trying to
# process the bootstrap for files starting with `test_`
"_{}_stage2_bootstrap.py".format(output_prefix),
sibling = output_sibling,
)
runtime = runtime_details.effective_runtime
template = runtime.stage2_bootstrap_template
if main_py:
main_py_path = "{}/{}".format(ctx.workspace_name, main_py.short_path)
else:
main_py_path = ""
ctx.actions.expand_template(
template = template,
output = output,
substitutions = {
"%coverage_tool%": _get_coverage_tool_runfiles_path(ctx, runtime),
"%import_all%": "True" if ctx.fragments.bazel_py.python_import_all_repositories else "False",
"%imports%": ":".join(imports.to_list()),
"%main%": main_py_path,
"%main_module%": ctx.attr.main_module,
"%target%": str(ctx.label),
"%workspace_name%": ctx.workspace_name,
},
is_executable = True,
)
return output
def _create_stage1_bootstrap(
ctx,
*,
output,
main_py = None,
stage2_bootstrap = None,
imports = None,
is_for_zip,
runtime_details,
venv = None):
runtime = runtime_details.effective_runtime
if venv:
python_binary_path = runfiles_root_path(ctx, venv.interpreter.short_path)
else:
python_binary_path = runtime_details.executable_interpreter_path
python_binary_actual = venv.interpreter_actual_path if venv else ""
subs = {
"%interpreter_args%": "\n".join([
'"{}"'.format(v)
for v in ctx.attr.interpreter_args
]),
"%is_zipfile%": "1" if is_for_zip else "0",
"%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",
"%target%": str(ctx.label),
"%workspace_name%": ctx.workspace_name,
}
if stage2_bootstrap:
subs["%stage2_bootstrap%"] = "{}/{}".format(
ctx.workspace_name,
stage2_bootstrap.short_path,
)
template = runtime.bootstrap_template
subs["%shebang%"] = runtime.stub_shebang
else:
if (ctx.configuration.coverage_enabled and
runtime and
runtime.coverage_tool):
coverage_tool_runfiles_path = "{}/{}".format(
ctx.workspace_name,
runtime.coverage_tool.short_path,
)
else:
coverage_tool_runfiles_path = ""
if runtime:
subs["%shebang%"] = runtime.stub_shebang
template = runtime.bootstrap_template
else:
subs["%shebang%"] = DEFAULT_STUB_SHEBANG
template = ctx.file._bootstrap_template
subs["%coverage_tool%"] = coverage_tool_runfiles_path
subs["%import_all%"] = ("True" if ctx.fragments.bazel_py.python_import_all_repositories else "False")
subs["%imports%"] = ":".join(imports.to_list())
subs["%main%"] = "{}/{}".format(ctx.workspace_name, main_py.short_path)
ctx.actions.expand_template(
template = template,
output = output,
substitutions = subs,
)
def _create_windows_exe_launcher(
ctx,
*,
output,
python_binary_path,
use_zip_file):
launch_info = ctx.actions.args()
launch_info.use_param_file("%s", use_always = True)
launch_info.set_param_file_format("multiline")
launch_info.add("binary_type=Python")
launch_info.add(ctx.workspace_name, format = "workspace_name=%s")
launch_info.add(
"1" if py_internal.runfiles_enabled(ctx) else "0",
format = "symlink_runfiles_enabled=%s",
)
launch_info.add(python_binary_path, format = "python_bin_path=%s")
launch_info.add("1" if use_zip_file else "0", format = "use_zip_file=%s")
launcher = ctx.attr._launcher[DefaultInfo].files_to_run.executable
ctx.actions.run(
executable = ctx.executable._windows_launcher_maker,
arguments = [launcher.path, launch_info, output.path],
inputs = [launcher],
outputs = [output],
mnemonic = "PyBuildLauncher",
progress_message = "Creating launcher for %{label}",
# Needed to inherit PATH when using non-MSVC compilers like MinGW
use_default_shell_env = True,
)
def _create_zip_file(ctx, *, output, original_nonzip_executable, zip_main, runfiles):
"""Create a Python zipapp (zip with __main__.py entry point)."""
workspace_name = ctx.workspace_name
legacy_external_runfiles = _py_builtins.get_legacy_external_runfiles(ctx)
manifest = ctx.actions.args()
manifest.use_param_file("@%s", use_always = True)
manifest.set_param_file_format("multiline")
manifest.add("__main__.py={}".format(zip_main.path))
manifest.add("__init__.py=")
manifest.add(
"{}=".format(
_get_zip_runfiles_path("__init__.py", workspace_name, legacy_external_runfiles),
),
)
for path in runfiles.empty_filenames.to_list():
manifest.add("{}=".format(_get_zip_runfiles_path(path, workspace_name, legacy_external_runfiles)))
def map_zip_runfiles(file):
if file != original_nonzip_executable and file != output:
return "{}={}".format(
_get_zip_runfiles_path(file.short_path, workspace_name, legacy_external_runfiles),
file.path,
)
else:
return None
manifest.add_all(runfiles.files, map_each = map_zip_runfiles, allow_closure = True)
inputs = [zip_main]
if _py_builtins.is_bzlmod_enabled(ctx):
zip_repo_mapping_manifest = ctx.actions.declare_file(
output.basename + ".repo_mapping",
sibling = output,
)
_py_builtins.create_repo_mapping_manifest(
ctx = ctx,
runfiles = runfiles,
output = zip_repo_mapping_manifest,
)
manifest.add("{}/_repo_mapping={}".format(
_ZIP_RUNFILES_DIRECTORY_NAME,
zip_repo_mapping_manifest.path,
))
inputs.append(zip_repo_mapping_manifest)
for artifact in runfiles.files.to_list():
# Don't include the original executable because it isn't used by the
# zip file, so no need to build it for the action.
# Don't include the zipfile itself because it's an output.
if artifact != original_nonzip_executable and artifact != output:
inputs.append(artifact)
zip_cli_args = ctx.actions.args()
zip_cli_args.add("cC")
zip_cli_args.add(output)
ctx.actions.run(
executable = ctx.executable._zipper,
arguments = [zip_cli_args, manifest],
inputs = depset(inputs),
outputs = [output],
use_default_shell_env = True,
mnemonic = "PythonZipper",
progress_message = "Building Python zip: %{label}",
)
def _get_zip_runfiles_path(path, workspace_name, legacy_external_runfiles):
if legacy_external_runfiles and path.startswith(_EXTERNAL_PATH_PREFIX):
zip_runfiles_path = paths.relativize(path, _EXTERNAL_PATH_PREFIX)
else:
# NOTE: External runfiles (artifacts in other repos) will have a leading
# path component of "../" so that they refer outside the main workspace
# directory and into the runfiles root. By normalizing, we simplify e.g.
# "workspace/../foo/bar" to simply "foo/bar".
zip_runfiles_path = paths.normalize("{}/{}".format(workspace_name, path))
return "{}/{}".format(_ZIP_RUNFILES_DIRECTORY_NAME, zip_runfiles_path)
def _create_executable_zip_file(
ctx,
*,
output,
zip_file,
stage2_bootstrap,
runtime_details,
venv):
prelude = ctx.actions.declare_file(
"{}_zip_prelude.sh".format(output.basename),
sibling = output,
)
if stage2_bootstrap:
_create_stage1_bootstrap(
ctx,
output = prelude,
stage2_bootstrap = stage2_bootstrap,
runtime_details = runtime_details,
is_for_zip = True,
venv = venv,
)
else:
ctx.actions.write(prelude, "#!/usr/bin/env python3\n")
ctx.actions.run_shell(
command = "cat {prelude} {zip} > {output}".format(
prelude = prelude.path,
zip = zip_file.path,
output = output.path,
),
inputs = [prelude, zip_file],
outputs = [output],
use_default_shell_env = True,
mnemonic = "PyBuildExecutableZip",
progress_message = "Build Python zip executable: %{label}",
)
def _get_cc_details_for_binary(ctx, extra_deps):
cc_info = collect_cc_info(ctx, extra_deps = extra_deps)
return create_cc_details_struct(
cc_info_for_propagating = cc_info,
cc_info_for_self_link = cc_info,
cc_info_with_extra_link_time_libraries = None,
extra_runfiles = ctx.runfiles(),
# Though the rules require the CcToolchain, it isn't actually used.
cc_toolchain = None,
feature_config = None,
)
def _get_interpreter_path(ctx, *, runtime, flag_interpreter_path):
if runtime:
if runtime.interpreter_path:
interpreter_path = runtime.interpreter_path
else:
interpreter_path = "{}/{}".format(
ctx.workspace_name,
runtime.interpreter.short_path,
)
# NOTE: External runfiles (artifacts in other repos) will have a
# leading path component of "../" so that they refer outside the
# main workspace directory and into the runfiles root. By
# normalizing, we simplify e.g. "workspace/../foo/bar" to simply
# "foo/bar"
interpreter_path = paths.normalize(interpreter_path)
elif flag_interpreter_path:
interpreter_path = flag_interpreter_path