From bc224450ced3e1b51d4a4be91755519afaffa28b Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 16 Jul 2024 10:41:26 -0700 Subject: [PATCH 001/465] Run integration tests with `rules_java` distribution instead of repo source Also build `@rules_java//java/...` as part of integration tests. Would have caught the v7.7.1 breakage (fixed by https://github.com/rules_java/bazel/commit/f7337ec36eb1fa78a3b4f641ccae7e5a2fe4a2b8) on presubmit. PiperOrigin-RevId: 652899892 Change-Id: I1a225922c15803263d25d0b905debb75d3f814a2 --- .bazelci/presubmit.yml | 3 +++ test/repo/MODULE.bazel | 4 ++-- test/repo/setup.sh | 5 +++++ 3 files changed, 10 insertions(+), 2 deletions(-) create mode 100644 test/repo/setup.sh diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 41c79ea9..331d1e7a 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -28,9 +28,12 @@ tasks: name: "Integration Tests" platform: ubuntu2004 working_directory: "test/repo" + shell_commands: + - sh setup.sh build_targets: - "//..." - "//:bin_deploy.jar" + - "@rules_java//java/..." macos: build_targets: *build_targets windows: diff --git a/test/repo/MODULE.bazel b/test/repo/MODULE.bazel index 10460a86..9289fcd5 100644 --- a/test/repo/MODULE.bazel +++ b/test/repo/MODULE.bazel @@ -1,7 +1,7 @@ module(name = "fake_repo_for_testing") bazel_dep(name = "rules_java", version = "7.5.0") -local_path_override( +archive_override( module_name = "rules_java", - path = "../../", + urls = ["file:///tmp/rules_java-HEAD.tar.gz"], ) diff --git a/test/repo/setup.sh b/test/repo/setup.sh new file mode 100644 index 00000000..4c268fc6 --- /dev/null +++ b/test/repo/setup.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +cd ../../ +bazel build //distro:all +cp -f bazel-bin/distro/rules_java-*.tar.gz /tmp/rules_java-HEAD.tar.gz \ No newline at end of file From 38cdd62af6e891f8249b791865b4043767dab5d7 Mon Sep 17 00:00:00 2001 From: Lazy Programer Date: Wed, 17 Jul 2024 00:33:48 -0700 Subject: [PATCH 002/465] Fix jni_md.h not found on linux_mips64 and linux_riscv64 Copybara Import from https://github.com/bazelbuild/rules_java/pull/198 BEGIN_PUBLIC Fix jni_md.h not found on linux_mips64 and linux_riscv64 (#198) Re-fixes regression: https://github.com/bazelbuild/bazel/issues/14808 Closes #198 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/198 from lazyprogrammerio:bazel-riscv64-refix 52a71a5e6cb6c028ed047de91a2174c0f38093dd PiperOrigin-RevId: 653123595 Change-Id: Ib735a0de9b66e9570921a85be5fdd21aff8177d8 --- toolchains/BUILD | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/toolchains/BUILD b/toolchains/BUILD index 81126c22..06d7201b 100644 --- a/toolchains/BUILD +++ b/toolchains/BUILD @@ -136,9 +136,9 @@ cc_library( "@bazel_tools//src/conditions:darwin": ["include/darwin"], "@bazel_tools//src/conditions:freebsd": ["include/freebsd"], "@bazel_tools//src/conditions:linux_aarch64": ["include/linux"], - "@bazel_tools//src/conditions:linux_mips64": [":include/linux"], + "@bazel_tools//src/conditions:linux_mips64": ["include/linux"], "@bazel_tools//src/conditions:linux_ppc64le": ["include/linux"], - "@bazel_tools//src/conditions:linux_riscv64": [":include/linux"], + "@bazel_tools//src/conditions:linux_riscv64": ["include/linux"], "@bazel_tools//src/conditions:linux_s390x": ["include/linux"], "@bazel_tools//src/conditions:linux_x86_64": ["include/linux"], "@bazel_tools//src/conditions:openbsd": ["include/openbsd"], From 7517ac67831e286117ed85722810fc1407fa01a3 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 22 Jul 2024 04:52:37 -0700 Subject: [PATCH 003/465] Expose symbols needed to support Java proto libraries BEGIN_PUBLIC Expose symbols needed to support Java proto libraries END_PUBLIC PiperOrigin-RevId: 654697985 Change-Id: Ie4b3a81e9f6139dd7f13a4e171ccf4cffcf17a1c --- java/private/proto_support.bzl | 27 +++++++++++++++++++++++++++ java/private/proto_support.bzl.oss | 25 +++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 java/private/proto_support.bzl create mode 100644 java/private/proto_support.bzl.oss diff --git a/java/private/proto_support.bzl b/java/private/proto_support.bzl new file mode 100644 index 00000000..624f0d61 --- /dev/null +++ b/java/private/proto_support.bzl @@ -0,0 +1,27 @@ +# 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. +"""Support for Java compilation of protocol buffer generated code.""" + +load("//java/private:native.bzl", "native_java_common") + +visibility(["//third_party/protobuf/..."]) + +# Partial support, because internal symbols are not available in older Bazel version +# TODO: Once Java rules are moved into the rules_java, this should become a full support. + +def compile(*, injecting_rule_kind, enable_jspecify, include_compilation_info, **kwargs): # buildifier: disable=unused-variable + return native_java_common.compile(**kwargs) + +def merge(providers, *, merge_java_outputs = True, merge_source_jars = True): # buildifier: disable=unused-variable + return native_java_common.merge(providers) diff --git a/java/private/proto_support.bzl.oss b/java/private/proto_support.bzl.oss new file mode 100644 index 00000000..bb94ccab --- /dev/null +++ b/java/private/proto_support.bzl.oss @@ -0,0 +1,25 @@ +# 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. +"""Support for Java compilation of protocol buffer generated code.""" + +load("//third_party/bazel_rules/rules_java/java/private:native.bzl", "native_java_common") + +# Partial support, because internal symbols are not available in older Bazel version +# TODO: Once Java rules are moved into the rules_java, this should become a full support. + +def compile(*, injecting_rule_kind, enable_jspecify, include_compilation_info, **kwargs): # buildifier: disable=unused-variable + return native_java_common.compile(**kwargs) + +def merge(providers, *, merge_java_outputs = True, merge_source_jars = True): # buildifier: disable=unused-variable + return native_java_common.merge(providers) From 0c4318b22a7783c726360cf90130ccd451651da3 Mon Sep 17 00:00:00 2001 From: keertk Date: Mon, 22 Jul 2024 07:18:18 -0700 Subject: [PATCH 004/465] Release rules_java v7.8.0 Copybara Import from https://github.com/bazelbuild/rules_java/pull/200 BEGIN_PUBLIC Release rules_java v7.8.0 (#200) https://github.com/bazelbuild/rules_java/issues/199 Closes #200 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/200 from bazelbuild:keertk-patch-2 9ab5a8a99690814f3df0b41f1265ae933c0fdaf9 PiperOrigin-RevId: 654736163 Change-Id: Ib3c71c19f96074ae4dcf7984d127be7505b6d5b4 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index d9aaa8ef..773efd05 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "7.7.2", + version = "7.8.0", # Requires @bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type. bazel_compatibility = [">=7.0.0"], compatibility_level = 1, From ed710a414de57bd5ccd565221c00f0c5f0b01adc Mon Sep 17 00:00:00 2001 From: keertk Date: Mon, 22 Jul 2024 09:15:30 -0700 Subject: [PATCH 005/465] Update version to 7.7.3 Copybara Import from https://github.com/bazelbuild/rules_java/pull/201 BEGIN_PUBLIC Update version to 7.7.3 (#201) Recreate https://github.com/bazelbuild/rules_java/issues/199 as 7.7.3 instead of 7.8.0 Closes #201 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/201 from bazelbuild:keertk-patch-3 d3d47ff112622513a8dd364896667612007b4ee8 PiperOrigin-RevId: 654779098 Change-Id: Icd9786863f1acff36f4512a46ffadbfaa55ae418 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 773efd05..ca0d7e17 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "7.8.0", + version = "7.7.3", # Requires @bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type. bazel_compatibility = [">=7.0.0"], compatibility_level = 1, From ca8565f190508ce6867dc38dfde2323a5f98cb29 Mon Sep 17 00:00:00 2001 From: "Ian (Hee) Cha" Date: Tue, 13 Aug 2024 00:28:33 -0700 Subject: [PATCH 006/465] Update rules_java to 7.9.0 and java_tools to 13.7 Copybara Import from https://github.com/bazelbuild/rules_java/pull/205 BEGIN_PUBLIC Update rules_java to 7.9.0 and java_tools to 13.7 (#205) Closes #205 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/205 from bazelbuild:java_v13.7 bae61263ea54aee69428f01907b39e5e19860734 PiperOrigin-RevId: 662401985 Change-Id: I82db7c8c4c381bc20f2daa3705440c0b17694f1e --- MODULE.bazel | 2 +- java/defs.bzl | 2 ++ java/repositories.bzl | 32 ++++++++++++++++---------------- 3 files changed, 19 insertions(+), 17 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index ca0d7e17..10564d5a 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "7.7.3", + version = "7.9.0", # Requires @bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type. bazel_compatibility = [">=7.0.0"], compatibility_level = 1, diff --git a/java/defs.bzl b/java/defs.bzl index 64de71a4..1ffdec98 100644 --- a/java/defs.bzl +++ b/java/defs.bzl @@ -25,6 +25,8 @@ load("//java/toolchains:java_package_configuration.bzl", _java_package_configura load("//java/toolchains:java_runtime.bzl", _java_runtime = "java_runtime") load("//java/toolchains:java_toolchain.bzl", _java_toolchain = "java_toolchain") +version = "7.9.0" + # Language rules java_binary = _java_binary diff --git a/java/repositories.bzl b/java/repositories.bzl index f60a4d0c..43ea5f0e 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.6.1", + "version": "v13.7", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.6.1/java_tools_linux-v13.6.1.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_13.6.1/java_tools_linux-v13.6.1.zip", - "sha": "0d3fcae7ae40d0a25f17c3adc30a3674f526953c55871189e2efe3463fce3496", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.7/java_tools_linux-v13.7.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.7/java_tools_linux-v13.7.zip", + "sha": "d0d379a7af5e82aceab8b355ed0184d9b7eddf133d7ecbe129199ce65078da77", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.6.1/java_tools_windows-v13.6.1.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_13.6.1/java_tools_windows-v13.6.1.zip", - "sha": "5a7d00e42c0b35f08eb5c8577eb115f8f57dd36ef8b6940c2190bd0d0e4ddcf0", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.7/java_tools_windows-v13.7.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.7/java_tools_windows-v13.7.zip", + "sha": "c8083a1e684a8f96400c4c07d4bade64fb95989992891e66d6f9953988f49472", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.6.1/java_tools_darwin_x86_64-v13.6.1.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_13.6.1/java_tools_darwin_x86_64-v13.6.1.zip", - "sha": "465dcb1da77a0c83c49f178c11bad29b3d703df1756722ec42fe5afd7c8129f8", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.7/java_tools_darwin_x86_64-v13.7.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.7/java_tools_darwin_x86_64-v13.7.zip", + "sha": "dd4d69a9fe3706f71e1a3a20e39a97941a10b3c75aa54361d06462038d48f1a2", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.6.1/java_tools_darwin_arm64-v13.6.1.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_13.6.1/java_tools_darwin_arm64-v13.6.1.zip", - "sha": "eb54c4e5fa23d6e9e9fc14c106a682dbefc54659d8e389a2f3c0d61d51cae274", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.7/java_tools_darwin_arm64-v13.7.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.7/java_tools_darwin_arm64-v13.7.zip", + "sha": "b0b9b8e5e9f423155b2a055eb9a43030846d2de3c296e3949d1b497bd2fcc284", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.6.1/java_tools-v13.6.1.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_13.6.1/java_tools-v13.6.1.zip", - "sha": "74c978eab040ad4ec38ce0d0970ac813cc2c6f4f6f4f121c0414719487edc991", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.7/java_tools-v13.7.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.7/java_tools-v13.7.zip", + "sha": "36eefdb4d52b268a278e776975ef00902cb85d829bd11a45bb08ef2f53ceb5e1", }, }, } From 18e8c3b79fde5eff093ddc9f4add91df586ec63e Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 22 Aug 2024 05:53:07 -0700 Subject: [PATCH 007/465] Expose correct symbols from Blaze BEGIN_PUBLIC Internal change END_PUBLIC PiperOrigin-RevId: 666314384 Change-Id: Id5c5ac6b9a729465a43ce2218c4ab6584940c966 --- java/private/proto_support.bzl | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/java/private/proto_support.bzl b/java/private/proto_support.bzl index 624f0d61..8dd644cd 100644 --- a/java/private/proto_support.bzl +++ b/java/private/proto_support.bzl @@ -13,15 +13,9 @@ # limitations under the License. """Support for Java compilation of protocol buffer generated code.""" -load("//java/private:native.bzl", "native_java_common") +_legacy_api = _legacy_api_DO_NOT_USE_OR_ELSE() visibility(["//third_party/protobuf/..."]) -# Partial support, because internal symbols are not available in older Bazel version -# TODO: Once Java rules are moved into the rules_java, this should become a full support. - -def compile(*, injecting_rule_kind, enable_jspecify, include_compilation_info, **kwargs): # buildifier: disable=unused-variable - return native_java_common.compile(**kwargs) - -def merge(providers, *, merge_java_outputs = True, merge_source_jars = True): # buildifier: disable=unused-variable - return native_java_common.merge(providers) +compile = _legacy_api.java_compile_for_protos +merge = _legacy_api.java_info_merge_for_protos From e1d74669d0d7d9a14beaf17236094712a7443967 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 23 Aug 2024 01:57:10 -0700 Subject: [PATCH 008/465] Revert https://github.com/bazelbuild/rules_java/commit/18e8c3b79fde5eff093ddc9f4add91df586ec63e PiperOrigin-RevId: 666698763 Change-Id: Ied733f052b47f6e869353c4126307576e4155598 --- java/private/proto_support.bzl | 12 ++++++++---- java/private/proto_support.bzl.oss | 25 ------------------------- 2 files changed, 8 insertions(+), 29 deletions(-) delete mode 100644 java/private/proto_support.bzl.oss diff --git a/java/private/proto_support.bzl b/java/private/proto_support.bzl index 8dd644cd..8666e5a5 100644 --- a/java/private/proto_support.bzl +++ b/java/private/proto_support.bzl @@ -13,9 +13,13 @@ # limitations under the License. """Support for Java compilation of protocol buffer generated code.""" -_legacy_api = _legacy_api_DO_NOT_USE_OR_ELSE() +load("//java/private:native.bzl", "native_java_common") -visibility(["//third_party/protobuf/..."]) +# Partial support, because internal symbols are not available in older Bazel version +# TODO: Once Java rules are moved into the rules_java, this should become a full support. -compile = _legacy_api.java_compile_for_protos -merge = _legacy_api.java_info_merge_for_protos +def compile(*, injecting_rule_kind, enable_jspecify, include_compilation_info, **kwargs): # buildifier: disable=unused-variable + return native_java_common.compile(**kwargs) + +def merge(providers, *, merge_java_outputs = True, merge_source_jars = True): # buildifier: disable=unused-variable + return native_java_common.merge(providers) diff --git a/java/private/proto_support.bzl.oss b/java/private/proto_support.bzl.oss deleted file mode 100644 index bb94ccab..00000000 --- a/java/private/proto_support.bzl.oss +++ /dev/null @@ -1,25 +0,0 @@ -# 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. -"""Support for Java compilation of protocol buffer generated code.""" - -load("//third_party/bazel_rules/rules_java/java/private:native.bzl", "native_java_common") - -# Partial support, because internal symbols are not available in older Bazel version -# TODO: Once Java rules are moved into the rules_java, this should become a full support. - -def compile(*, injecting_rule_kind, enable_jspecify, include_compilation_info, **kwargs): # buildifier: disable=unused-variable - return native_java_common.compile(**kwargs) - -def merge(providers, *, merge_java_outputs = True, merge_source_jars = True): # buildifier: disable=unused-variable - return native_java_common.merge(providers) From 2392b2415198b0b2153fecf76ca2816b6064593b Mon Sep 17 00:00:00 2001 From: keertk Date: Fri, 30 Aug 2024 07:58:03 -0700 Subject: [PATCH 009/465] Release rules_java v7.9.1 Copybara Import from https://github.com/bazelbuild/rules_java/pull/208 BEGIN_PUBLIC Release rules_java v7.9.1 (#208) https://github.com/bazelbuild/rules_java/issues/207 Closes #208 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/208 from bazelbuild:keertk-patch-4 b551c835fdf9c99c1b3f9ba20ff14bd0e0daec4f PiperOrigin-RevId: 669326485 Change-Id: I9fbba75328f040d796f35c11bcd39ada0e7e0c35 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 10564d5a..26dbceed 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "7.9.0", + version = "7.9.1", # Requires @bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type. bazel_compatibility = [">=7.0.0"], compatibility_level = 1, From 30ecf3ff6ee8f30b4df505d9d3bde5bb1c25690b Mon Sep 17 00:00:00 2001 From: Ivo List Date: Mon, 2 Sep 2024 23:08:00 -0700 Subject: [PATCH 010/465] Make rules_java backwards compatible with Bazel 6.3.0 Copybara Import from https://github.com/bazelbuild/rules_java/pull/210 BEGIN_PUBLIC Make rules_java backwards compatible with Bazel 6.3.0 (#210) Move bootstrap_toolchain_type into rules_java. There are no uses outside of rules_java. This fixes compatiblity with Bazel 6.3.0, which doesn't have the definition. Add back `_allowlist_function_transition`. Older versions of Bazel require it. Add Bazel 6.3.0 to the CI. Remove a couple of broken targets from toolchains/BUILD. Those were broken becuase old JDKs were removed. Closes #210 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/210 from comius:backward-compatible-rules_java 393f270312cbb13fa5bc7807b93cf95f1e7b3969 PiperOrigin-RevId: 670415171 Change-Id: I7f42cc92bb7285cb51a2a1185695451a644d5b30 --- .bazelci/presubmit.yml | 17 ++++++++++++++++- .bazelversion | 1 - MODULE.bazel | 3 +-- toolchains/BUILD | 16 ++-------------- toolchains/default_java_toolchain.bzl | 2 +- toolchains/java_toolchain_alias.bzl | 3 +++ toolchains/local_java_repository.bzl | 4 ++-- toolchains/remote_java_repository.bzl | 2 +- 8 files changed, 26 insertions(+), 22 deletions(-) delete mode 100644 .bazelversion diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 331d1e7a..1a493180 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -70,4 +70,19 @@ tasks: platform: windows build_flags: - "--config=bzlmod" - build_targets: *build_targets_bzlmod \ No newline at end of file + build_targets: *build_targets_bzlmod + ubuntu2004_bazel630: + name: "Bazel 6.3.0" + bazel: 6.3.0 + platform: ubuntu2004 + build_targets: *build_targets + macos_bazel630: + name: "Bazel 6.3.0" + bazel: 6.3.0 + platform: macos + build_targets: *build_targets + windows_bazel630: + name: "Bazel 6.3.0" + bazel: 6.3.0 + platform: windows + build_targets: *build_targets diff --git a/.bazelversion b/.bazelversion deleted file mode 100644 index 66ce77b7..00000000 --- a/.bazelversion +++ /dev/null @@ -1 +0,0 @@ -7.0.0 diff --git a/MODULE.bazel b/MODULE.bazel index 26dbceed..775caf99 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,8 +1,7 @@ module( name = "rules_java", version = "7.9.1", - # Requires @bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type. - bazel_compatibility = [">=7.0.0"], + bazel_compatibility = [">=6.2.0"], compatibility_level = 1, ) diff --git a/toolchains/BUILD b/toolchains/BUILD index 06d7201b..b7252a4e 100644 --- a/toolchains/BUILD +++ b/toolchains/BUILD @@ -66,8 +66,8 @@ filegroup( # # Toolchains of this type are only consumed internally by the bootclasspath rule and should not be # accessed from Starlark. -# TODO: migrate away from using @bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type ? -# toolchain_type(name = "bootstrap_runtime_toolchain_type") + +toolchain_type(name = "bootstrap_runtime_toolchain_type") # Points to toolchain[":runtime_toolchain_type"] (was :legacy_current_java_runtime) java_runtime_alias(name = "current_java_runtime") @@ -293,18 +293,6 @@ java_runtime_version_alias( visibility = ["//visibility:public"], ) -java_runtime_version_alias( - name = "remotejdk_15", - runtime_version = "remotejdk_15", - visibility = ["//visibility:public"], -) - -java_runtime_version_alias( - name = "remotejdk_16", - runtime_version = "remotejdk_16", - visibility = ["//visibility:public"], -) - java_runtime_version_alias( name = "remotejdk_17", runtime_version = "remotejdk_17", diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl index b3d4d28b..e63b7c8e 100644 --- a/toolchains/default_java_toolchain.bzl +++ b/toolchains/default_java_toolchain.bzl @@ -208,7 +208,7 @@ def java_runtime_files(name, srcs): tags = ["manual"], ) -_JAVA_BOOTSTRAP_RUNTIME_TOOLCHAIN_TYPE = Label("@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type") +_JAVA_BOOTSTRAP_RUNTIME_TOOLCHAIN_TYPE = Label("//toolchains:bootstrap_runtime_toolchain_type") # Opt the Java bootstrap actions into path mapping: # https://github.com/bazelbuild/bazel/commit/a239ea84832f18ee8706682145e9595e71b39680 diff --git a/toolchains/java_toolchain_alias.bzl b/toolchains/java_toolchain_alias.bzl index 8d8a7e47..34889258 100644 --- a/toolchains/java_toolchain_alias.bzl +++ b/toolchains/java_toolchain_alias.bzl @@ -85,6 +85,9 @@ java_runtime_version_alias = rule( toolchains = ["@bazel_tools//tools/jdk:runtime_toolchain_type"], attrs = { "runtime_version": attr.string(mandatory = True), + "_allowlist_function_transition": attr.label( + default = "@bazel_tools//tools/allowlists/function_transition_allowlist", + ), }, cfg = _java_runtime_transition, ) diff --git a/toolchains/local_java_repository.bzl b/toolchains/local_java_repository.bzl index ae5f82f8..d4c60291 100644 --- a/toolchains/local_java_repository.bzl +++ b/toolchains/local_java_repository.bzl @@ -110,7 +110,7 @@ def local_java_runtime(name, java_home, version, runtime_name = None, visibility native.toolchain( name = "bootstrap_runtime_toolchain_definition", target_settings = [":%s_settings_alias" % name], - toolchain_type = Label("@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type"), + toolchain_type = Label("//toolchains:bootstrap_runtime_toolchain_type"), toolchain = runtime_name, ) @@ -268,7 +268,7 @@ toolchain( toolchain( name = "bootstrap_runtime_toolchain_definition", target_settings = [":localjdk_setting"], - toolchain_type = "@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type", + toolchain_type = "@rules_java//tools/jdk:bootstrap_runtime_toolchain_type", toolchain = ":jdk", ) ''' diff --git a/toolchains/remote_java_repository.bzl b/toolchains/remote_java_repository.bzl index 65bbe482..a2535d3c 100644 --- a/toolchains/remote_java_repository.bzl +++ b/toolchains/remote_java_repository.bzl @@ -89,7 +89,7 @@ toolchain( # the same configuration, this constraint will not result in toolchain resolution failures. exec_compatible_with = {target_compatible_with}, target_settings = [":version_or_prefix_version_setting"], - toolchain_type = "@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type", + toolchain_type = "@rules_java//toolchains:bootstrap_runtime_toolchain_type", toolchain = "{toolchain}", ) """.format( From 2c67f888b3bb52f248ec5f9f5f71050224e25379 Mon Sep 17 00:00:00 2001 From: keertk Date: Tue, 3 Sep 2024 08:30:53 -0700 Subject: [PATCH 011/465] Release rules_java v7.10.0 Copybara Import from https://github.com/bazelbuild/rules_java/pull/212 BEGIN_PUBLIC Release rules_java v7.10.0 (#212) https://github.com/bazelbuild/rules_java/issues/211 Closes #212 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/212 from bazelbuild:keertk-patch-1 715b007a6c51b76e2c4341da581a745aa761dc05 PiperOrigin-RevId: 670569529 Change-Id: Ibf5ba915692c078aa1246cfed625d2072cbf482f --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 775caf99..5e42665f 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "7.9.1", + version = "7.10.0", bazel_compatibility = [">=6.2.0"], compatibility_level = 1, ) From 19841b7bc283b79e3b041f218312aa6e9dca2724 Mon Sep 17 00:00:00 2001 From: keertk Date: Tue, 3 Sep 2024 09:05:05 -0700 Subject: [PATCH 012/465] Update version in defs.bzl Copybara Import from https://github.com/bazelbuild/rules_java/pull/213 BEGIN_PUBLIC Update version in defs.bzl (#213) https://github.com/bazelbuild/rules_java/issues/211 Closes #213 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/213 from bazelbuild:keertk-patch-2 4e0b5df061756f83582df00713358070086a64f6 PiperOrigin-RevId: 670581032 Change-Id: Id70745592047fa2ddfdea6b0ea9952d24a10aa99 --- java/defs.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/defs.bzl b/java/defs.bzl index 1ffdec98..bc5ad1fa 100644 --- a/java/defs.bzl +++ b/java/defs.bzl @@ -25,7 +25,7 @@ load("//java/toolchains:java_package_configuration.bzl", _java_package_configura load("//java/toolchains:java_runtime.bzl", _java_runtime = "java_runtime") load("//java/toolchains:java_toolchain.bzl", _java_toolchain = "java_toolchain") -version = "7.9.0" +version = "7.10.0" # Language rules From bcc506228f3ac2c6a811c3414329d8727883685e Mon Sep 17 00:00:00 2001 From: Ivo List Date: Wed, 4 Sep 2024 05:18:32 -0700 Subject: [PATCH 013/465] Fix bootstrap_runtime_toolchain_type reference Copybara Import from https://github.com/bazelbuild/rules_java/pull/215 BEGIN_PUBLIC Fix bootstrap_runtime_toolchain_type reference (#215) Closes #215 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/215 from bazelbuild:comius-patch-1 a4907eaab8a642b1e1dfa24dcdb174ec6671023a PiperOrigin-RevId: 670931588 Change-Id: Ib5b8502d8443bb2133920a101d1d086c9a77345c --- toolchains/local_java_repository.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/toolchains/local_java_repository.bzl b/toolchains/local_java_repository.bzl index d4c60291..e0123673 100644 --- a/toolchains/local_java_repository.bzl +++ b/toolchains/local_java_repository.bzl @@ -268,7 +268,7 @@ toolchain( toolchain( name = "bootstrap_runtime_toolchain_definition", target_settings = [":localjdk_setting"], - toolchain_type = "@rules_java//tools/jdk:bootstrap_runtime_toolchain_type", + toolchain_type = "@rules_java//toolchains:bootstrap_runtime_toolchain_type", toolchain = ":jdk", ) ''' From 4f50c3b4f6f595711901c8fabb5e023c6525e335 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Wed, 4 Sep 2024 10:13:51 -0700 Subject: [PATCH 014/465] Wire up `oneversion` in Java toolchain configurations Copybara Import from https://github.com/bazelbuild/rules_java/pull/206 BEGIN_PUBLIC Wire up `oneversion` in Java toolchain configurations (#206) Closes #206 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/206 from fmeum:one_version d65f3d0f30de1bd3ed07ac05612570bb985e1136 PiperOrigin-RevId: 671012643 Change-Id: Ica0aa0053cd8b3ac7e2b882006e9e0b0d98da94b --- MODULE.bazel | 1 + toolchains/BUILD | 31 +++++++++++++++++++++++++++ toolchains/default_java_toolchain.bzl | 3 +++ 3 files changed, 35 insertions(+) diff --git a/MODULE.bazel b/MODULE.bazel index 5e42665f..291b6b1f 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -13,6 +13,7 @@ bazel_dep(name = "bazel_skylib", version = "1.6.1") # Required by @remote_java_tools, which is loaded via module extension. bazel_dep(name = "rules_proto", version = "4.0.0") bazel_dep(name = "rules_license", version = "0.0.3") +bazel_dep(name = "abseil-cpp", version = "20240116.2", repo_name = "com_google_absl") register_toolchains("//toolchains:all") diff --git a/toolchains/BUILD b/toolchains/BUILD index b7252a4e..f78c3b9e 100644 --- a/toolchains/BUILD +++ b/toolchains/BUILD @@ -160,6 +160,11 @@ cc_library( actual = "@remote_java_tools_%s//:prebuilt_singlejar" % OS, visibility = ["//visibility:private"], ), + alias( + name = "prebuilt_one_version_%s" % OS, + actual = "@remote_java_tools_%s//:prebuilt_one_version" % OS, + visibility = ["//visibility:private"], + ), alias( name = "turbine_direct_graal_%s" % OS, actual = "@remote_java_tools_%s//:turbine_direct_graal" % OS, @@ -225,6 +230,32 @@ alias( }), ) +alias( + name = "one_version", + actual = ":one_version_prebuilt_or_cc_binary", +) + +alias( + name = "one_version_prebuilt_or_cc_binary", + actual = select({ + "@bazel_tools//src/conditions:darwin_arm64": ":prebuilt_one_version_darwin_arm64", + "@bazel_tools//src/conditions:darwin_x86_64": ":prebuilt_one_version_darwin_x86_64", + "@bazel_tools//src/conditions:linux_x86_64": ":prebuilt_one_version_linux", + "@bazel_tools//src/conditions:windows": ":prebuilt_one_version_windows", + "//conditions:default": "@remote_java_tools//:one_version_cc_bin", + }), +) + +alias( + name = "prebuilt_one_version", + actual = select({ + "@bazel_tools//src/conditions:darwin_arm64": ":prebuilt_one_version_darwin_arm64", + "@bazel_tools//src/conditions:darwin_x86_64": ":prebuilt_one_version_darwin_x86_64", + "@bazel_tools//src/conditions:linux_x86_64": ":prebuilt_one_version_linux", + "@bazel_tools//src/conditions:windows": ":prebuilt_one_version_windows", + }), +) + alias( name = "turbine_direct", actual = ":turbine_direct_graal_or_java", diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl index e63b7c8e..a92a1f93 100644 --- a/toolchains/default_java_toolchain.bzl +++ b/toolchains/default_java_toolchain.bzl @@ -94,6 +94,7 @@ _BASE_TOOLCHAIN_CONFIGURATION = dict( "dagger.hilt.processor.internal.root.RootProcessor", # see b/21307381 ], java_runtime = Label("//toolchains:remotejdk_21"), + oneversion = Label("//toolchains:one_version"), ) DEFAULT_TOOLCHAIN_CONFIGURATION = _BASE_TOOLCHAIN_CONFIGURATION @@ -125,6 +126,7 @@ VANILLA_TOOLCHAIN_CONFIGURATION = dict( PREBUILT_TOOLCHAIN_CONFIGURATION = dict( ijar = [Label("//toolchains:ijar_prebuilt_binary")], singlejar = [Label("//toolchains:prebuilt_singlejar")], + oneversion = Label("//toolchains:prebuilt_one_version"), ) # The new toolchain is using all the tools from sources. @@ -132,6 +134,7 @@ NONPREBUILT_TOOLCHAIN_CONFIGURATION = dict( ijar = [Label("@remote_java_tools//:ijar_cc_binary")], singlejar = [Label("@remote_java_tools//:singlejar_cc_bin")], header_compiler_direct = [Label("@remote_java_tools//:TurbineDirect")], + oneversion = Label("@remote_java_tools//:one_version_cc_bin"), ) # If this is changed, the docs for "{,tool_}java_language_version" also From 9c9f935a60008c6ae881520f7d7a08cf0e58a27e Mon Sep 17 00:00:00 2001 From: "Ian (Hee) Cha" Date: Sun, 8 Sep 2024 21:19:05 -0700 Subject: [PATCH 015/465] Update rules_java to 7.11.0 and java_tools to 13.8 Copybara Import from https://github.com/bazelbuild/rules_java/pull/221 BEGIN_PUBLIC Update rules_java to 7.11.0 and java_tools to 13.8 (#221) Closes #221 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/221 from bazelbuild:java_v13.8 fb736dd858b7ee0eb1bc80963dd69756023e51c1 PiperOrigin-RevId: 672390820 Change-Id: I7e7200a95a4d5c3fe2e8fdeea9bd36b1ad9bfb15 --- MODULE.bazel | 2 +- java/defs.bzl | 2 +- java/repositories.bzl | 34 +++++++++++++++++----------------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 291b6b1f..d688417e 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "7.10.0", + version = "7.11.0", bazel_compatibility = [">=6.2.0"], compatibility_level = 1, ) diff --git a/java/defs.bzl b/java/defs.bzl index bc5ad1fa..f1f7311e 100644 --- a/java/defs.bzl +++ b/java/defs.bzl @@ -25,7 +25,7 @@ load("//java/toolchains:java_package_configuration.bzl", _java_package_configura load("//java/toolchains:java_runtime.bzl", _java_runtime = "java_runtime") load("//java/toolchains:java_toolchain.bzl", _java_toolchain = "java_toolchain") -version = "7.10.0" +version = "7.11.0" # Language rules diff --git a/java/repositories.bzl b/java/repositories.bzl index 43ea5f0e..c8156bd4 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.7", - "release": "true", + "version": "v13.8", + "release": "false", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.7/java_tools_linux-v13.7.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.7/java_tools_linux-v13.7.zip", - "sha": "d0d379a7af5e82aceab8b355ed0184d9b7eddf133d7ecbe129199ce65078da77", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.8/java_tools_linux-v13.8.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.8/java_tools_linux-v13.8.zip", + "sha": "e480906978b34d1f15fa958699112872c7b5883a3d48b630b6bed574d86523ca", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.7/java_tools_windows-v13.7.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.7/java_tools_windows-v13.7.zip", - "sha": "c8083a1e684a8f96400c4c07d4bade64fb95989992891e66d6f9953988f49472", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.8/java_tools_windows-v13.8.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.8/java_tools_windows-v13.8.zip", + "sha": "bae74a8f1c7d3d5f73f944a31446b2d87d4e94966ef9cc0bc6b07de6fed6e382", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.7/java_tools_darwin_x86_64-v13.7.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.7/java_tools_darwin_x86_64-v13.7.zip", - "sha": "dd4d69a9fe3706f71e1a3a20e39a97941a10b3c75aa54361d06462038d48f1a2", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.8/java_tools_darwin_x86_64-v13.8.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.8/java_tools_darwin_x86_64-v13.8.zip", + "sha": "78a750e24d0bf0f125f3bb4218f58c4e60343f3d28c834e88bd09c7924c83d8d", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.7/java_tools_darwin_arm64-v13.7.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.7/java_tools_darwin_arm64-v13.7.zip", - "sha": "b0b9b8e5e9f423155b2a055eb9a43030846d2de3c296e3949d1b497bd2fcc284", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.8/java_tools_darwin_arm64-v13.8.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.8/java_tools_darwin_arm64-v13.8.zip", + "sha": "7a4bf783c67db892e3e670d61c194a0595df8f151c0684146ec7bcf2057a6500", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.7/java_tools-v13.7.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.7/java_tools-v13.7.zip", - "sha": "36eefdb4d52b268a278e776975ef00902cb85d829bd11a45bb08ef2f53ceb5e1", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.8/java_tools-v13.8.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.8/java_tools-v13.8.zip", + "sha": "224287ef2b581795392cbd8b1b9f4306d11abb95bba41ea72810cc9c7872a5f8", }, }, } From 764a64f4560780997a60088c4cb466e8c87bfea7 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Sep 2024 00:48:48 -0700 Subject: [PATCH 016/465] Dowgrade `abseil-cpp` version in `java_tools` (and tests) to match the one in Bazel PiperOrigin-RevId: 672842119 Change-Id: I5f5975d88bf24259bedb7bb53cbc872f919ef703 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index d688417e..03c63207 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -13,7 +13,7 @@ bazel_dep(name = "bazel_skylib", version = "1.6.1") # Required by @remote_java_tools, which is loaded via module extension. bazel_dep(name = "rules_proto", version = "4.0.0") bazel_dep(name = "rules_license", version = "0.0.3") -bazel_dep(name = "abseil-cpp", version = "20240116.2", repo_name = "com_google_absl") +bazel_dep(name = "abseil-cpp", version = "20230802.1", repo_name = "com_google_absl") register_toolchains("//toolchains:all") From c98fb704f47cec1d7d5a0410a3faff63a3987edf Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Sep 2024 00:56:06 -0700 Subject: [PATCH 017/465] Release `rules_java` `v7.11.1` PiperOrigin-RevId: 672843946 Change-Id: I2f3200434c48c2aeb41ed15b2f0bb5d1ae6e24f4 --- MODULE.bazel | 2 +- java/defs.bzl | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 03c63207..f66bbd18 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "7.11.0", + version = "7.11.1", bazel_compatibility = [">=6.2.0"], compatibility_level = 1, ) diff --git a/java/defs.bzl b/java/defs.bzl index f1f7311e..64de71a4 100644 --- a/java/defs.bzl +++ b/java/defs.bzl @@ -25,8 +25,6 @@ load("//java/toolchains:java_package_configuration.bzl", _java_package_configura load("//java/toolchains:java_runtime.bzl", _java_runtime = "java_runtime") load("//java/toolchains:java_toolchain.bzl", _java_toolchain = "java_toolchain") -version = "7.11.0" - # Language rules java_binary = _java_binary From 272366dcd763a8d3d7c05edc3256b1866ba815c7 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Sep 2024 04:39:00 -0700 Subject: [PATCH 018/465] Copy the Bazel java rules out of builtins PiperOrigin-RevId: 672907957 Change-Id: I8f14924015857a378ded08929b6966047f042d10 --- java/bazel/rules/bazel_java_binary.bzl | 576 ++++++++++++ .../bazel/rules/bazel_java_binary_nonexec.bzl | 28 + .../bazel/rules/bazel_java_binary_wrapper.bzl | 45 + java/common/java_semantics.bzl | 107 +++ java/common/rules/BUILD | 1 + java/common/rules/android_lint.bzl | 145 ++++ java/common/rules/basic_java_library.bzl | 282 ++++++ java/common/rules/compile_action.bzl | 176 ++++ java/common/rules/import_deps_check.bzl | 81 ++ java/common/rules/java_binary.bzl | 821 ++++++++++++++++++ java/common/rules/java_binary_deploy_jar.bzl | 248 ++++++ java/common/rules/java_binary_wrapper.bzl | 73 ++ java/common/rules/java_helper.bzl | 507 +++++++++++ java/common/rules/java_import.bzl | 356 ++++++++ java/common/rules/java_library.bzl | 392 +++++++++ .../rules/java_package_configuration.bzl | 115 +++ java/common/rules/java_plugin.bzl | 185 ++++ java/common/rules/java_runtime.bzl | 260 ++++++ java/common/rules/java_toolchain.bzl | 604 +++++++++++++ java/common/rules/proguard_validation.bzl | 71 ++ java/common/rules/rule_util.bzl | 50 ++ 21 files changed, 5123 insertions(+) create mode 100644 java/bazel/rules/bazel_java_binary.bzl create mode 100644 java/bazel/rules/bazel_java_binary_nonexec.bzl create mode 100644 java/bazel/rules/bazel_java_binary_wrapper.bzl create mode 100644 java/common/java_semantics.bzl create mode 100644 java/common/rules/BUILD create mode 100644 java/common/rules/android_lint.bzl create mode 100644 java/common/rules/basic_java_library.bzl create mode 100644 java/common/rules/compile_action.bzl create mode 100644 java/common/rules/import_deps_check.bzl create mode 100644 java/common/rules/java_binary.bzl create mode 100644 java/common/rules/java_binary_deploy_jar.bzl create mode 100644 java/common/rules/java_binary_wrapper.bzl create mode 100644 java/common/rules/java_helper.bzl create mode 100644 java/common/rules/java_import.bzl create mode 100644 java/common/rules/java_library.bzl create mode 100644 java/common/rules/java_package_configuration.bzl create mode 100644 java/common/rules/java_plugin.bzl create mode 100644 java/common/rules/java_runtime.bzl create mode 100644 java/common/rules/java_toolchain.bzl create mode 100644 java/common/rules/proguard_validation.bzl create mode 100644 java/common/rules/rule_util.bzl diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl new file mode 100644 index 00000000..9317cc29 --- /dev/null +++ b/java/bazel/rules/bazel_java_binary.bzl @@ -0,0 +1,576 @@ +# 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. +"""Bazel java_binary rule""" + +load("@rules_cc//cc:find_cc_toolchain.bzl", "use_cc_toolchain") +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_semantics.bzl", "semantics") +load( + "//java/common/rules:android_lint.bzl", + "android_lint_subrule", +) +load("//java/common/rules:java_binary.bzl", "BASE_TEST_ATTRIBUTES", "BASIC_JAVA_BINARY_ATTRIBUTES", "basic_java_binary") +load("//java/common/rules:java_binary_deploy_jar.bzl", "create_deploy_archives") +load("//java/common/rules:java_helper.bzl", "helper") +load("//java/common/rules:rule_util.bzl", "merge_attrs") +load("//third_party/bazel_skylib/lib:paths.bzl", "paths") + +visibility("private") + +def _bazel_java_binary_impl(ctx): + return _bazel_base_binary_impl(ctx, is_test_rule_class = False) + helper.executable_providers(ctx) + +def _bazel_java_test_impl(ctx): + return _bazel_base_binary_impl(ctx, is_test_rule_class = True) + helper.test_providers(ctx) + +def _bazel_base_binary_impl(ctx, is_test_rule_class): + deps = _collect_all_targets_as_deps(ctx, classpath_type = "compile_only") + runtime_deps = _collect_all_targets_as_deps(ctx) + + main_class = _check_and_get_main_class(ctx) + coverage_main_class = main_class + coverage_config = helper.get_coverage_config(ctx, _get_coverage_runner(ctx)) + if coverage_config: + main_class = coverage_config.main_class + + launcher_info = _get_launcher_info(ctx) + + executable = _get_executable(ctx) + + feature_config = helper.get_feature_config(ctx) + if feature_config: + strip_as_default = helper.should_strip_as_default(ctx, feature_config) + else: + # No C++ toolchain available. + strip_as_default = False + + providers, default_info, jvm_flags = basic_java_binary( + ctx, + deps, + runtime_deps, + ctx.files.resources, + main_class, + coverage_main_class, + coverage_config, + launcher_info, + executable, + strip_as_default, + is_test_rule_class = is_test_rule_class, + ) + + if ctx.attr.use_testrunner: + if semantics.find_java_runtime_toolchain(ctx).version >= 17: + jvm_flags.append("-Djava.security.manager=allow") + test_class = ctx.attr.test_class if hasattr(ctx.attr, "test_class") else "" + if test_class == "": + test_class = helper.primary_class(ctx) + if test_class == None: + fail("cannot determine test class. You might want to rename the " + + " rule or add a 'test_class' attribute.") + jvm_flags.extend([ + "-ea", + "-Dbazel.test_suite=" + helper.shell_escape(test_class), + ]) + + java_attrs = providers["InternalDeployJarInfo"].java_attrs + + if executable: + _create_stub(ctx, java_attrs, launcher_info.launcher, executable, jvm_flags, main_class, coverage_main_class) + + runfiles = default_info.runfiles + + if executable: + runtime_toolchain = semantics.find_java_runtime_toolchain(ctx) + runfiles = runfiles.merge(ctx.runfiles(transitive_files = runtime_toolchain.files)) + + test_support = helper.get_test_support(ctx) + if test_support: + runfiles = runfiles.merge(test_support[DefaultInfo].default_runfiles) + + providers["DefaultInfo"] = DefaultInfo( + files = default_info.files, + runfiles = runfiles, + executable = default_info.executable, + ) + + info = providers.pop("InternalDeployJarInfo") + create_deploy_archives( + ctx, + info.java_attrs, + launcher_info, + main_class, + coverage_main_class, + info.strip_as_default, + add_exports = info.add_exports, + add_opens = info.add_opens, + ) + + return providers.values() + +def _get_coverage_runner(ctx): + if ctx.configuration.coverage_enabled and ctx.attr.create_executable: + toolchain = semantics.find_java_toolchain(ctx) + runner = toolchain.jacocorunner + if not runner: + fail("jacocorunner not set in java_toolchain: %s" % toolchain.label) + runner_jar = runner.executable + + # wrap the jar in JavaInfo so we can add it to deps for java_common.compile() + return JavaInfo(output_jar = runner_jar, compile_jar = runner_jar) + + return None + +def _collect_all_targets_as_deps(ctx, classpath_type = "all"): + deps = helper.collect_all_targets_as_deps(ctx, classpath_type = classpath_type) + + if classpath_type == "compile_only" and ctx.fragments.java.enforce_explicit_java_test_deps(): + return deps + + test_support = helper.get_test_support(ctx) + if test_support: + deps.append(test_support) + return deps + +def _check_and_get_main_class(ctx): + create_executable = ctx.attr.create_executable + main_class = _get_main_class(ctx) + + if not create_executable and main_class: + fail("main class must not be specified when executable is not created") + if create_executable and not main_class: + if not ctx.attr.srcs: + fail("need at least one of 'main_class' or Java source files") + main_class = helper.primary_class(ctx) + if main_class == None: + fail("main_class was not provided and cannot be inferred: " + + "source path doesn't include a known root (java, javatests, src, testsrc)") + + return _get_main_class(ctx) + +def _get_main_class(ctx): + if not ctx.attr.create_executable: + return None + + main_class = _get_main_class_from_rule(ctx) + + if main_class == "": + main_class = helper.primary_class(ctx) + return main_class + +def _get_main_class_from_rule(ctx): + main_class = ctx.attr.main_class + if main_class: + return main_class + if ctx.attr.use_testrunner: + return "com.google.testing.junit.runner.BazelTestRunner" + return main_class + +def _get_launcher_info(ctx): + launcher = helper.launcher_artifact_for_target(ctx) + return struct( + launcher = launcher, + unstripped_launcher = launcher, + runfiles = [], + runtime_jars = [], + jvm_flags = [], + classpath_resources = [], + ) + +def _get_executable(ctx): + if not ctx.attr.create_executable: + return None + executable_name = ctx.label.name + if helper.is_target_platform_windows(ctx): + executable_name = executable_name + ".exe" + + return ctx.actions.declare_file(executable_name) + +def _create_stub(ctx, java_attrs, launcher, executable, jvm_flags, main_class, coverage_main_class): + java_runtime_toolchain = semantics.find_java_runtime_toolchain(ctx) + java_executable = helper.get_java_executable(ctx, java_runtime_toolchain, launcher) + workspace_name = ctx.workspace_name + workspace_prefix = workspace_name + ("/" if workspace_name else "") + runfiles_enabled = helper.runfiles_enabled(ctx) + coverage_enabled = ctx.configuration.coverage_enabled + + test_support = helper.get_test_support(ctx) + test_support_jars = test_support[JavaInfo].transitive_runtime_jars if test_support else depset() + classpath = depset( + transitive = [ + java_attrs.runtime_classpath, + test_support_jars if ctx.fragments.java.enforce_explicit_java_test_deps() else depset(), + ], + ) + + if helper.is_target_platform_windows(ctx): + jvm_flags_for_launcher = [] + for flag in jvm_flags: + jvm_flags_for_launcher.extend(ctx.tokenize(flag)) + return _create_windows_exe_launcher(ctx, java_executable, classpath, main_class, jvm_flags_for_launcher, runfiles_enabled, executable) + + if runfiles_enabled: + prefix = "" if helper.is_absolute_target_platform_path(ctx, java_executable) else "${JAVA_RUNFILES}/" + java_bin = "JAVABIN=${JAVABIN:-" + prefix + java_executable + "}" + else: + java_bin = "JAVABIN=${JAVABIN:-$(rlocation " + java_executable + ")}" + + td = ctx.actions.template_dict() + td.add_joined( + "%classpath%", + classpath, + map_each = lambda file: _format_classpath_entry(runfiles_enabled, workspace_prefix, file), + join_with = ctx.configuration.host_path_separator, + format_joined = "\"%s\"", + allow_closure = True, + ) + + ctx.actions.expand_template( + template = ctx.file._stub_template, + output = executable, + substitutions = { + "%runfiles_manifest_only%": "" if runfiles_enabled else "1", + "%workspace_prefix%": workspace_prefix, + "%javabin%": java_bin, + "%needs_runfiles%": "0" if helper.is_absolute_target_platform_path(ctx, java_runtime_toolchain.java_executable_exec_path) else "1", + "%set_jacoco_metadata%": "", + "%set_jacoco_main_class%": "export JACOCO_MAIN_CLASS=" + coverage_main_class if coverage_enabled else "", + "%set_jacoco_java_runfiles_root%": "export JACOCO_JAVA_RUNFILES_ROOT=${JAVA_RUNFILES}/" + workspace_prefix if coverage_enabled else "", + "%java_start_class%": helper.shell_escape(main_class), + "%jvm_flags%": " ".join(jvm_flags), + }, + computed_substitutions = td, + is_executable = True, + ) + return executable + +def _format_classpath_entry(runfiles_enabled, workspace_prefix, file): + if runfiles_enabled: + return "${RUNPATH}" + file.short_path + + return "$(rlocation " + paths.normalize(workspace_prefix + file.short_path) + ")" + +def _create_windows_exe_launcher(ctx, java_executable, classpath, main_class, jvm_flags_for_launcher, runfiles_enabled, executable): + launch_info = ctx.actions.args().use_param_file("%s", use_always = True).set_param_file_format("multiline") + launch_info.add("binary_type=Java") + launch_info.add(ctx.workspace_name, format = "workspace_name=%s") + launch_info.add("1" if runfiles_enabled else "0", format = "symlink_runfiles_enabled=%s") + launch_info.add(java_executable, format = "java_bin_path=%s") + launch_info.add(main_class, format = "java_start_class=%s") + launch_info.add_joined(classpath, map_each = _short_path, join_with = ";", format_joined = "classpath=%s", omit_if_empty = False) + launch_info.add_joined(jvm_flags_for_launcher, join_with = "\t", format_joined = "jvm_flags=%s", omit_if_empty = False) + launch_info.add(semantics.find_java_runtime_toolchain(ctx).java_home_runfiles_path, format = "jar_bin_path=%s/bin/jar.exe") + + # TODO(b/295221112): Change to use the "launcher" attribute (only windows use a fixed _launcher attribute) + launcher_artifact = ctx.executable._launcher + ctx.actions.run( + executable = ctx.executable._windows_launcher_maker, + inputs = [launcher_artifact], + outputs = [executable], + arguments = [launcher_artifact.path, launch_info, executable.path], + use_default_shell_env = True, + ) + return executable + +def _short_path(file): + return file.short_path + +def _compute_test_support(use_testrunner): + return Label(semantics.JAVA_TEST_RUNNER_LABEL) if use_testrunner else None + +def _make_binary_rule(implementation, *, doc, attrs, executable = False, test = False, initializer = None): + return rule( + implementation = implementation, + initializer = initializer, + doc = doc, + attrs = attrs, + executable = executable, + test = test, + fragments = ["cpp", "java"], + provides = [JavaInfo], + toolchains = [semantics.JAVA_TOOLCHAIN] + use_cc_toolchain() + ( + [semantics.JAVA_RUNTIME_TOOLCHAIN] if executable or test else [] + ), + # TODO(hvd): replace with filegroups? + outputs = { + "classjar": "%{name}.jar", + "sourcejar": "%{name}-src.jar", + "deploysrcjar": "%{name}_deploy-src.jar", + "deployjar": "%{name}_deploy.jar", + "unstrippeddeployjar": "%{name}_deploy.jar.unstripped", + }, + exec_groups = { + "cpp_link": exec_group(toolchains = use_cc_toolchain()), + }, + subrules = [android_lint_subrule], + ) + +_BASE_BINARY_ATTRS = merge_attrs( + BASIC_JAVA_BINARY_ATTRIBUTES, + { + "resource_strip_prefix": attr.string( + doc = """ +The path prefix to strip from Java resources. +

+If specified, this path prefix is stripped from every file in the resources +attribute. It is an error for a resource file not to be under this directory. If not +specified (the default), the path of resource file is determined according to the same +logic as the Java package of source files. For example, a source file at +stuff/java/foo/bar/a.txt will be located at foo/bar/a.txt. +

+ """, + ), + "_test_support": attr.label(default = _compute_test_support), + "_launcher": attr.label( + cfg = "exec", + executable = True, + default = "@bazel_tools//tools/launcher:launcher", + ), + "_windows_launcher_maker": attr.label( + default = "@bazel_tools//tools/launcher:launcher_maker", + cfg = "exec", + executable = True, + ), + }, +) + +def make_java_binary(executable): + return _make_binary_rule( + _bazel_java_binary_impl, + doc = """ +

+ Builds a Java archive ("jar file"), plus a wrapper shell script with the same name as the rule. + The wrapper shell script uses a classpath that includes, among other things, a jar file for each + library on which the binary depends. When running the wrapper shell script, any nonempty + JAVABIN environment variable will take precedence over the version specified via + Bazel's --java_runtime_version flag. +

+

+ The wrapper script accepts several unique flags. Refer to + //src/main/java/com/google/devtools/build/lib/bazel/rules/java/java_stub_template.txt + for a list of configurable flags and environment variables accepted by the wrapper. +

+ +

Implicit output targets

+
    +
  • name.jar: A Java archive, containing the class files and other + resources corresponding to the binary's direct dependencies.
  • +
  • name-src.jar: An archive containing the sources ("source + jar").
  • +
  • name_deploy.jar: A Java archive suitable for deployment (only + built if explicitly requested). +

    + Building the <name>_deploy.jar target for your rule + creates a self-contained jar file with a manifest that allows it to be run with the + java -jar command or with the wrapper script's --singlejar + option. Using the wrapper script is preferred to java -jar because it + also passes the JVM flags and the options + to load native libraries. +

    +

    + The deploy jar contains all the classes that would be found by a classloader that + searched the classpath from the binary's wrapper script from beginning to end. It also + contains the native libraries needed for dependencies. These are automatically loaded + into the JVM at runtime. +

    +

    If your target specifies a launcher + attribute, then instead of being a normal JAR file, the _deploy.jar will be a + native binary. This will contain the launcher plus any native (C++) dependencies of + your rule, all linked into a static binary. The actual jar file's bytes will be + appended to that native binary, creating a single binary blob containing both the + executable and the Java code. You can execute the resulting jar file directly + like you would execute any native binary.

    +
  • +
  • name_deploy-src.jar: An archive containing the sources + collected from the transitive closure of the target. These will match the classes in the + deploy.jar except where jars have no matching source jar.
  • +
+ +

+It is good practice to use the name of the source file that is the main entry point of the +application (minus the extension). For example, if your entry point is called +Main.java, then your name could be Main. +

+ +

+ A deps attribute is not allowed in a java_binary rule without + srcs; such a rule requires a + main_class provided by + runtime_deps. +

+ +

The following code snippet illustrates a common mistake:

+ +
+
+java_binary(
+    name = "DontDoThis",
+    srcs = [
+        ...,
+        "GeneratedJavaFile.java",  # a generated .java file
+    ],
+    deps = [":generating_rule",],  # rule that generates that file
+)
+
+
+ +

Do this instead:

+ +
+
+java_binary(
+    name = "DoThisInstead",
+    srcs = [
+        ...,
+        ":generating_rule",
+    ],
+)
+
+
+ """, + attrs = merge_attrs( + _BASE_BINARY_ATTRS, + ({} if executable else { + "args": attr.string_list(), + "output_licenses": attr.string_list(), + }), + ), + executable = executable, + ) + +java_binary = make_java_binary(executable = True) + +def _java_test_initializer(**kwargs): + if "stamp" in kwargs and type(kwargs["stamp"]) == type(True): + kwargs["stamp"] = 1 if kwargs["stamp"] else 0 + if "use_launcher" in kwargs and not kwargs["use_launcher"]: + kwargs["launcher"] = None + else: + # If launcher is not set or None, set it to config flag + if "launcher" not in kwargs or not kwargs["launcher"]: + kwargs["launcher"] = semantics.LAUNCHER_FLAG_LABEL + return kwargs + +java_test = _make_binary_rule( + _bazel_java_test_impl, + doc = """ +

+A java_test() rule compiles a Java test. A test is a binary wrapper around your +test code. The test runner's main method is invoked instead of the main class being compiled. +

+ +

Implicit output targets

+
    +
  • name.jar: A Java archive.
  • +
  • name_deploy.jar: A Java archive suitable + for deployment. (Only built if explicitly requested.) See the description of the + name_deploy.jar output from + java_binary for more details.
  • +
+ +

+See the section on java_binary() arguments. This rule also +supports all attributes common +to all test rules (*_test). +

+ +

Examples

+ +
+
+
+java_library(
+    name = "tests",
+    srcs = glob(["*.java"]),
+    deps = [
+        "//java/com/foo/base:testResources",
+        "//java/com/foo/testing/util",
+    ],
+)
+
+java_test(
+    name = "AllTests",
+    size = "small",
+    runtime_deps = [
+        ":tests",
+        "//util/mysql",
+    ],
+)
+
+
+ """, + attrs = merge_attrs( + BASE_TEST_ATTRIBUTES, + _BASE_BINARY_ATTRS, + { + "_lcov_merger": attr.label( + cfg = "exec", + default = configuration_field( + fragment = "coverage", + name = "output_generator", + ), + ), + "_collect_cc_coverage": attr.label( + cfg = "exec", + allow_single_file = True, + default = "@bazel_tools//tools/test:collect_cc_coverage", + ), + }, + override_attrs = { + "use_testrunner": attr.bool( + default = True, + doc = semantics.DOCS.for_attribute("use_testrunner") + """ +
+You can use this to override the default +behavior, which is to use test runner for +java_test rules, +and not use it for java_binary rules. It is unlikely +you will want to do this. One use is for AllTest +rules that are invoked by another rule (to set up a database +before running the tests, for example). The AllTest +rule must be declared as a java_binary, but should +still use the test runner as its main entry point. + +The name of a test runner class can be overridden with main_class attribute. + """, + ), + "stamp": attr.int( + default = 0, + values = [-1, 0, 1], + doc = """ +Whether to encode build information into the binary. Possible values: +
    +
  • + stamp = 1: Always stamp the build information into the binary, even in + --nostamp builds. This + setting should be avoided, since it potentially kills remote caching for the + binary and any downstream actions that depend on it. +
  • +
  • + stamp = 0: Always replace build information by constant values. This + gives good build result caching. +
  • +
  • + stamp = -1: Embedding of build information is controlled by the + --[no]stamp flag. +
  • +
+

Stamped binaries are not rebuilt unless their dependencies change.

+ """, + ), + }, + remove_attrs = ["deploy_env"], + ), + test = True, + initializer = _java_test_initializer, +) diff --git a/java/bazel/rules/bazel_java_binary_nonexec.bzl b/java/bazel/rules/bazel_java_binary_nonexec.bzl new file mode 100644 index 00000000..82a76430 --- /dev/null +++ b/java/bazel/rules/bazel_java_binary_nonexec.bzl @@ -0,0 +1,28 @@ +# 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. + +"""Defines a java_binary rule class that is non-executable. + +There are three physical rule classes for java_binary and we want all of them +to have a name string of "java_binary" because various tooling expects that. +But we also need the rule classes to be defined in separate files. That way the +hash of their bzl environments will be different. See http://b/226379109, +specifically #20, for details. +""" + +load(":bazel_java_binary.bzl", "make_java_binary") + +visibility("private") + +java_binary = make_java_binary(executable = False) diff --git a/java/bazel/rules/bazel_java_binary_wrapper.bzl b/java/bazel/rules/bazel_java_binary_wrapper.bzl new file mode 100644 index 00000000..31696bcc --- /dev/null +++ b/java/bazel/rules/bazel_java_binary_wrapper.bzl @@ -0,0 +1,45 @@ +# 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. + +"""Macro encapsulating the java_binary implementation + +This is needed since the `executable` nature of the target must be computed from +the supplied value of the `create_executable` attribute. +""" + +load("//java/common:java_common.bzl", "java_common") +load( + "//java/common/rules:java_binary_wrapper.bzl", + "register_java_binary_rules", + "register_legacy_java_binary_rules", +) +load(":bazel_java_binary.bzl", java_bin_exec = "java_binary") +load(":bazel_java_binary_nonexec.bzl", java_bin_nonexec = "java_binary") + +_java_common_internal = java_common.internal_DO_NOT_USE() + +visibility("private") + +def java_binary(**kwargs): + if _java_common_internal.incompatible_disable_non_executable_java_binary(): + register_java_binary_rules( + java_bin_exec, + **kwargs + ) + else: + register_legacy_java_binary_rules( + java_bin_exec, + java_bin_nonexec, + **kwargs + ) diff --git a/java/common/java_semantics.bzl b/java/common/java_semantics.bzl new file mode 100644 index 00000000..d8bf824b --- /dev/null +++ b/java/common/java_semantics.bzl @@ -0,0 +1,107 @@ +# Copyright 2021 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. +"""Bazel Java Semantics""" + +load("@rules_cc//cc/common:cc_helper.bzl", "cc_helper") + +visibility(["//java/..."]) + +def _find_java_toolchain(ctx): + return ctx.toolchains["@bazel_tools//tools/jdk:toolchain_type"].java + +def _find_java_runtime_toolchain(ctx): + return ctx.toolchains["@bazel_tools//tools/jdk:runtime_toolchain_type"].java_runtime + +def _get_default_resource_path(path, segment_extractor): + # Look for src/.../resources to match Maven repository structure. + segments = path.split("/") + for idx in range(0, len(segments) - 2): + if segments[idx] == "src" and segments[idx + 2] == "resources": + return "/".join(segments[idx + 3:]) + java_segments = segment_extractor(path) + return "/".join(java_segments) if java_segments != None else path + +def _compatible_javac_options(*_args): + return depset() + +def _check_java_info_opens_exports(): + pass + +_DOCS = struct( + ATTRS = { + "resources": """ +

+If resources are specified, they will be bundled in the jar along with the usual +.class files produced by compilation. The location of the resources inside +of the jar file is determined by the project structure. Bazel first looks for Maven's +standard directory layout, +(a "src" directory followed by a "resources" directory grandchild). If that is not +found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for +example, if a resource is at <workspace root>/x/java/y/java/z, the +path of the resource will be y/java/z. This heuristic cannot be overridden, +however, the resource_strip_prefix attribute can be used to specify a +specific alternative directory for resource files. + """, + "use_testrunner": """ +Use the test runner (by default +com.google.testing.junit.runner.BazelTestRunner) class as the +main entry point for a Java program, and provide the test class +to the test runner as a value of bazel.test_suite +system property. + """, + }, +) + +tokenize_javacopts = cc_helper.tokenize + +PLATFORMS_ROOT = "@platforms//" + +semantics = struct( + JAVA_TOOLCHAIN_LABEL = "@bazel_tools//tools/jdk:current_java_toolchain", + JAVA_TOOLCHAIN_TYPE = "@bazel_tools//tools/jdk:toolchain_type", + JAVA_TOOLCHAIN = config_common.toolchain_type("@bazel_tools//tools/jdk:toolchain_type", mandatory = True), + find_java_toolchain = _find_java_toolchain, + JAVA_RUNTIME_TOOLCHAIN_TYPE = "@bazel_tools//tools/jdk:runtime_toolchain_type", + JAVA_RUNTIME_TOOLCHAIN = config_common.toolchain_type("@bazel_tools//tools/jdk:runtime_toolchain_type", mandatory = True), + find_java_runtime_toolchain = _find_java_runtime_toolchain, + JAVA_PLUGINS_FLAG_ALIAS_LABEL = "@bazel_tools//tools/jdk:java_plugins_flag_alias", + EXTRA_SRCS_TYPES = [], + ALLOWED_RULES_IN_DEPS = [ + "cc_binary", # NB: linkshared=1 + "cc_library", + "genrule", + "genproto", # TODO(bazel-team): we should filter using providers instead (starlark rule). + "java_import", + "java_library", + "java_proto_library", + "java_lite_proto_library", + "proto_library", + "sh_binary", + "sh_library", + ], + ALLOWED_RULES_IN_DEPS_WITH_WARNING = [], + LINT_PROGRESS_MESSAGE = "Running Android Lint for: %{label}", + JAVA_STUB_TEMPLATE_LABEL = "@bazel_tools//tools/jdk:java_stub_template.txt", + BUILD_INFO_TRANSLATOR_LABEL = "@bazel_tools//tools/build_defs/build_info:java_build_info", + JAVA_TEST_RUNNER_LABEL = "@bazel_tools//tools/jdk:TestRunner", + IS_BAZEL = True, + get_default_resource_path = _get_default_resource_path, + compatible_javac_options = _compatible_javac_options, + LAUNCHER_FLAG_LABEL = Label("@bazel_tools//tools/jdk:launcher_flag_alias"), + PROGUARD_ALLOWLISTER_LABEL = "@bazel_tools//tools/jdk:proguard_whitelister", + check_java_info_opens_exports = _check_java_info_opens_exports, + DOCS = struct( + for_attribute = lambda name: _DOCS.ATTRS.get(name, ""), + ), +) diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD new file mode 100644 index 00000000..ffd0fb0c --- /dev/null +++ b/java/common/rules/BUILD @@ -0,0 +1 @@ +package(default_visibility = ["//visibility:public"]) diff --git a/java/common/rules/android_lint.bzl b/java/common/rules/android_lint.bzl new file mode 100644 index 00000000..9d23681b --- /dev/null +++ b/java/common/rules/android_lint.bzl @@ -0,0 +1,145 @@ +# Copyright 2021 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. + +"""Creates the android lint action for java rules""" + +load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_helper.bzl", "helper") + +visibility(["//java/..."]) + +def _tokenize_opts(opts_depset): + return helper.tokenize_javacopts(ctx = None, opts = opts_depset) + +def _android_lint_action(ctx, source_files, source_jars, compilation_info): + """ + Creates an action that runs Android lint against Java source files. + + You need to add `ANDROID_LINT_IMPLICIT_ATTRS` to any rule or aspect using this call. + + To lint generated source jars (java_info.java_outputs.gen_source_jar) + add them to the `source_jar` parameter. + + `compilation_info` parameter should supply the classpath and Javac options + that were used during Java compilation. + + The Android lint tool is obtained from Java toolchain. + + Args: + ctx: (RuleContext) Used to register the action. + source_files: (list[File]) A list of .java source files + source_jars: (list[File]) A list of .jar or .srcjar files containing + source files. It should also include generated source jars. + compilation_info: (struct) Information about compilation. + + Returns: + (None|File) The Android lint output file or None if no source files were + present. + """ + + # assuming that linting is enabled for all java rules i.e. + # --experimental_limit_android_lint_to_android_constrained_java=false + + # --experimental_run_android_lint_on_java_rules= is checked in basic_java_library.bzl + + if not (source_files or source_jars): + return None + + toolchain = semantics.find_java_toolchain(ctx) + java_runtime = toolchain.java_runtime + linter = toolchain._android_linter + if not linter: + # TODO(hvd): enable after enabling in tests + # fail("android linter not set in java_toolchain") + return None + + args = ctx.actions.args() + + executable = linter.tool.executable + transitive_inputs = [] + if executable.extension != "jar": + tools = [linter.tool] + transitive_inputs.append(linter.data) + args_list = [args] + else: + jvm_args = ctx.actions.args() + jvm_args.add_all(toolchain.jvm_opt) + jvm_args.add_all(linter.jvm_opts) + jvm_args.add("-jar", executable) + executable = java_runtime.java_executable_exec_path + tools = [java_runtime.files, linter.tool.executable] + transitive_inputs.append(linter.data) + args_list = [jvm_args, args] + + classpath = compilation_info.compilation_classpath + + # TODO(hvd): get from toolchain if we need this - probably android only + bootclasspath_aux = [] + if bootclasspath_aux: + classpath = depset(transitive = [classpath, bootclasspath_aux]) + transitive_inputs.append(classpath) + + bootclasspath = toolchain.bootclasspath + transitive_inputs.append(bootclasspath) + + transitive_inputs.append(compilation_info.plugins.processor_jars) + transitive_inputs.append(compilation_info.plugins.processor_data) + args.add_all("--sources", source_files) + args.add_all("--source_jars", source_jars) + args.add_all("--bootclasspath", bootclasspath) + args.add_all("--classpath", classpath) + args.add_all("--lint_rules", compilation_info.plugins.processor_jars) + args.add("--target_label", ctx.label) + + javac_opts = compilation_info.javac_options + if javac_opts: + # wrap in a list so that map_each passes the depset to _tokenize_opts + args.add_all("--javacopts", [javac_opts], map_each = _tokenize_opts) + args.add("--") + + args.add("--lintopts") + args.add_all(linter.lint_opts) + + for package_config in linter.package_config: + if package_config.matches(ctx.label): + # wrap in a list so that map_each passes the depset to _tokenize_opts + package_opts = [package_config.javac_opts] + args.add_all(package_opts, map_each = _tokenize_opts) + transitive_inputs.append(package_config.data) + + android_lint_out = ctx.actions.declare_file("%s_android_lint_output.xml" % ctx.label.name) + args.add("--xml", android_lint_out) + + args.set_param_file_format(format = "multiline") + args.use_param_file(param_file_arg = "@%s", use_always = True) + ctx.actions.run( + mnemonic = "AndroidLint", + progress_message = semantics.LINT_PROGRESS_MESSAGE, + executable = executable, + inputs = depset( + # TODO(b/213551463) benchmark using a transitive depset instead + source_files + source_jars, + transitive = transitive_inputs, + ), + outputs = [android_lint_out], + tools = tools, + arguments = args_list, + execution_requirements = {"supports-workers": "1"}, + ) + return android_lint_out + +android_lint_subrule = subrule( + implementation = _android_lint_action, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], +) diff --git a/java/common/rules/basic_java_library.bzl b/java/common/rules/basic_java_library.bzl new file mode 100644 index 00000000..221baca4 --- /dev/null +++ b/java/common/rules/basic_java_library.bzl @@ -0,0 +1,282 @@ +# Copyright 2021 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 code for reuse across java_* rules +""" + +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") +load("//java/common:java_semantics.bzl", "semantics") +load(":android_lint.bzl", "android_lint_subrule") +load(":compile_action.bzl", "compile_action") +load(":proguard_validation.bzl", "validate_proguard_specs") +load(":rule_util.bzl", "merge_attrs") + +visibility([ + "//java/...", +]) + +_java_common_internal = java_common.internal_DO_NOT_USE() +BootClassPathInfo = java_common.BootClassPathInfo +target_kind = _java_common_internal.target_kind + +def _filter_srcs(srcs, ext): + return [f for f in srcs if f.extension == ext] + +def _filter_provider(provider, *attrs): + return [dep[provider] for attr in attrs for dep in attr if provider in dep] + +# TODO(b/11285003): disallow jar files in deps, require java_import instead +def _filter_javainfo_and_legacy_jars(attr): + dep_list = [] + + # Native code collected data into a NestedSet, using add for legacy jars and + # addTransitive for JavaInfo. This resulted in legacy jars being first in the list. + for dep in attr: + kind = target_kind(dep) + if not JavaInfo in dep or kind == "java_binary" or kind == "java_test": + for file in dep[DefaultInfo].files.to_list(): + if file.extension == "jar": + # Native doesn't construct JavaInfo + java_info = JavaInfo(output_jar = file, compile_jar = file) + dep_list.append(java_info) + + for dep in attr: + if JavaInfo in dep: + dep_list.append(dep[JavaInfo]) + return dep_list + +def basic_java_library( + ctx, + srcs, + deps = [], + runtime_deps = [], + plugins = [], + exports = [], + exported_plugins = [], + resources = [], + resource_jars = [], + classpath_resources = [], + javacopts = [], + neverlink = False, + enable_compile_jar_action = True, + coverage_config = None, + proguard_specs = None, + add_exports = [], + add_opens = [], + bootclasspath = None, + javabuilder_jvm_flags = None): + """ + Creates actions that compile and lint Java sources, sets up coverage and returns JavaInfo, InstrumentedFilesInfo and output groups. + + The call creates actions and providers needed and shared by `java_library`, + `java_plugin`,`java_binary`, and `java_test` rules and it is primarily + intended to be used in those rules. + + Before compilation coverage.runner is added to the dependencies and if + present plugins are extended with the value of `--plugin` flag. + + Args: + ctx: (RuleContext) Used to register the actions. + srcs: (list[File]) The list of source files that are processed to create the target. + deps: (list[Target]) The list of other libraries to be linked in to the target. + runtime_deps: (list[Target]) Libraries to make available to the final binary or test at runtime only. + plugins: (list[Target]) Java compiler plugins to run at compile-time. + exports: (list[Target]) Exported libraries. + exported_plugins: (list[Target]) The list of `java_plugin`s (e.g. annotation + processors) to export to libraries that directly depend on this library. + resources: (list[File]) A list of data files to include in a Java jar. + resource_jars: (list[File]) A list of jar files to unpack and include in a + Java jar. + classpath_resources: (list[File]) + javacopts: (list[str]) + neverlink: (bool) Whether this library should only be used for compilation and not at runtime. + enable_compile_jar_action: (bool) Enables header compilation or ijar creation. + coverage_config: (struct{runner:JavaInfo, support_files:list[File]|depset[File], env:dict[str,str]}) + Coverage configuration. `runner` is added to dependencies during + compilation, `support_files` and `env` is returned in InstrumentedFilesInfo. + proguard_specs: (list[File]) Files to be used as Proguard specification. + Proguard validation is done only when the parameter is set. + add_exports: (list[str]) Allow this library to access the given /. + add_opens: (list[str]) Allow this library to reflectively access the given /. + bootclasspath: (Target) The JDK APIs to compile this library against. + javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. + Returns: + (dict[str, Provider], + {files_to_build: list[File], + runfiles: list[File], + output_groups: dict[str,list[File]]}) + """ + source_files = _filter_srcs(srcs, "java") + source_jars = _filter_srcs(srcs, "srcjar") + + plugins_javaplugininfo = _collect_plugins(plugins) + plugins_javaplugininfo.append(ctx.attr._java_plugins[JavaPluginInfo]) + + properties = _filter_srcs(srcs, "properties") + if properties: + resources = list(resources) + resources.extend(properties) + + java_info, compilation_info = compile_action( + ctx, + ctx.outputs.classjar, + ctx.outputs.sourcejar, + source_files, + source_jars, + collect_deps(deps) + ([coverage_config.runner] if coverage_config and coverage_config.runner else []), + collect_deps(runtime_deps), + plugins_javaplugininfo, + collect_deps(exports), + _collect_plugins(exported_plugins), + resources, + resource_jars, + classpath_resources, + _collect_native_libraries(deps, runtime_deps, exports), + javacopts, + neverlink, + ctx.fragments.java.strict_java_deps, + enable_compile_jar_action, + add_exports = add_exports, + add_opens = add_opens, + bootclasspath = bootclasspath[BootClassPathInfo] if bootclasspath else None, + javabuilder_jvm_flags = javabuilder_jvm_flags, + ) + target = {"JavaInfo": java_info} + + output_groups = dict( + compilation_outputs = compilation_info.files_to_build, + _source_jars = java_info.transitive_source_jars, + _direct_source_jars = java_info.source_jars, + ) + + if ctx.fragments.java.run_android_lint: + generated_source_jars = [ + output.generated_source_jar + for output in java_info.java_outputs + if output.generated_source_jar != None + ] + lint_output = android_lint_subrule( + source_files, + source_jars + generated_source_jars, + compilation_info, + ) + if lint_output: + output_groups["_validation"] = [lint_output] + + target["InstrumentedFilesInfo"] = coverage_common.instrumented_files_info( + ctx, + source_attributes = ["srcs"], + dependency_attributes = ["deps", "data", "resources", "resource_jars", "exports", "runtime_deps", "jars"], + coverage_support_files = coverage_config.support_files if coverage_config else depset(), + coverage_environment = coverage_config.env if coverage_config else {}, + ) + + if proguard_specs != None: + target["ProguardSpecProvider"] = validate_proguard_specs( + ctx, + proguard_specs, + [deps, runtime_deps, exports], + ) + output_groups["_hidden_top_level_INTERNAL_"] = target["ProguardSpecProvider"].specs + + return target, struct( + files_to_build = compilation_info.files_to_build, + runfiles = compilation_info.runfiles, + output_groups = output_groups, + ) + +def _collect_plugins(plugins): + """Collects plugins from an attribute. + + Use this call to collect plugins from `plugins` or `exported_plugins` attribute. + + The call simply extracts JavaPluginInfo provider. + + Args: + plugins: (list[Target]) Attribute to collect plugins from. + Returns: + (list[JavaPluginInfo]) The plugins. + """ + return _filter_provider(JavaPluginInfo, plugins) + +def collect_deps(deps): + """Collects dependencies from an attribute. + + Use this call to collect plugins from `deps`, `runtime_deps`, or `exports` attribute. + + The call extracts JavaInfo and additionaly also "legacy jars". "legacy jars" + are wrapped into a JavaInfo. + + Args: + deps: (list[Target]) Attribute to collect dependencies from. + Returns: + (list[JavaInfo]) The dependencies. + """ + return _filter_javainfo_and_legacy_jars(deps) + +def _collect_native_libraries(*attrs): + """Collects native libraries from a list of attributes. + + Use this call to collect native libraries from `deps`, `runtime_deps`, or `exports` attributes. + + The call simply extracts CcInfo provider. + Args: + *attrs: (*list[Target]) Attribute to collect native libraries from. + Returns: + (list[CcInfo]) The native library dependencies. + """ + return _filter_provider(CcInfo, *attrs) + +def construct_defaultinfo(ctx, files_to_build, files, neverlink, *extra_attrs): + """Constructs DefaultInfo for Java library like rule. + + Args: + ctx: (RuleContext) Used to construct the runfiles. + files_to_build: (list[File]) List of the files built by the rule. + files: (list[File]) List of the files include in runfiles. + neverlink: (bool) When true empty runfiles are constructed. + *extra_attrs: (list[Target]) Extra attributes to merge runfiles from. + + Returns: + (DefaultInfo) DefaultInfo provider. + """ + if neverlink: + runfiles = None + else: + runfiles = ctx.runfiles(files = files, collect_default = True) + runfiles = runfiles.merge_all([dep[DefaultInfo].default_runfiles for attr in extra_attrs for dep in attr]) + default_info = DefaultInfo( + files = depset(files_to_build), + runfiles = runfiles, + ) + return default_info + +BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS = merge_attrs( + { + "_java_plugins": attr.label( + default = semantics.JAVA_PLUGINS_FLAG_ALIAS_LABEL, + providers = [JavaPluginInfo], + ), + # TODO(b/245144242): Used by IDE integration, remove when toolchains are used + "_java_toolchain": attr.label( + default = semantics.JAVA_TOOLCHAIN_LABEL, + providers = [java_common.JavaToolchainInfo], + ), + "_use_auto_exec_groups": attr.bool(default = True), + }, +) diff --git a/java/common/rules/compile_action.bzl b/java/common/rules/compile_action.bzl new file mode 100644 index 00000000..d1c7f0ed --- /dev/null +++ b/java/common/rules/compile_action.bzl @@ -0,0 +1,176 @@ +# Copyright 2021 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. + +""" +Java compile action +""" + +load("//java/common:java_semantics.bzl", "semantics") + +visibility("private") + +_java_common_internal = java_common.internal_DO_NOT_USE() +_compile_private_for_builtins = _java_common_internal.compile + +def _filter_strict_deps(mode): + return "error" if mode in ["strict", "default"] else mode + +def _collect_plugins(deps, plugins): + transitive_processor_jars = [] + transitive_processor_data = [] + for plugin in plugins: + transitive_processor_jars.append(plugin.plugins.processor_jars) + transitive_processor_data.append(plugin.plugins.processor_data) + for dep in deps: + transitive_processor_jars.append(dep.plugins.processor_jars) + transitive_processor_data.append(dep.plugins.processor_data) + return struct( + processor_jars = depset(transitive = transitive_processor_jars), + processor_data = depset(transitive = transitive_processor_data), + ) + +def compile_action( + ctx, + output_class_jar, + output_source_jar, + source_files = [], + source_jars = [], + deps = [], + runtime_deps = [], + plugins = [], + exports = [], + exported_plugins = [], + resources = [], + resource_jars = [], + classpath_resources = [], + native_libraries = [], + javacopts = [], + neverlink = False, + strict_deps = "ERROR", + enable_compile_jar_action = True, + add_exports = [], + add_opens = [], + bootclasspath = None, + javabuilder_jvm_flags = None): + """ + Creates actions that compile Java sources, produce source jar, and produce header jar and returns JavaInfo. + + Use this call when you need the most basic and consistent Java compilation. + + Most parameters correspond to attributes on a java_library (srcs, deps, + plugins, resources ...) except they are more strict, for example: + + - Where java_library's srcs attribute allows mixing of .java, .srcjar, and + .properties files the arguments accepted by this call should be strictly + separated into source_files, source_jars, and resources parameter. + - deps parameter accepts only JavaInfo providers and plugins parameter only + JavaPluginInfo + + The call creates following actions and files: + - compiling Java sources to a class jar (output_class_jar parameter) + - a source jar (output_source_jar parameter) + - optionally a jar containing plugin generated classes when plugins are present + - optionally a jar containing plugin generated sources + - jdeps file containing dependencies used during compilation + - other files used to speed up incremental builds: + - a header jar - a jar containing only method signatures without implementation + - compile jdeps - dependencies used during header compilation + + The returned JavaInfo provider may be used as a "fully-qualified" dependency + to a java_library. + + Args: + ctx: (RuleContext) Used to register the actions. + output_class_jar: (File) Output class .jar file. The file needs to be declared. + output_source_jar: (File) Output source .jar file. The file needs to be declared. + source_files: (list[File]) A list of .java source files to compile. + At least one of source_files or source_jars parameter must be specified. + source_jars: (list[File]) A list of .jar or .srcjar files containing + source files to compile. + At least one of source_files or source_jars parameter must be specified. + deps: (list[JavaInfo]) A list of dependencies. + runtime_deps: (list[JavaInfo]) A list of runtime dependencies. + plugins: (list[JavaPluginInfo]) A list of plugins. + exports: (list[JavaInfo]) A list of exports. + exported_plugins: (list[JavaInfo]) A list of exported plugins. + resources: (list[File]) A list of resources. + resource_jars: (list[File]) A list of jars to unpack. + classpath_resources: (list[File]) A list of classpath resources. + native_libraries: (list[CcInfo]) C++ native library dependencies that are + needed for this library. + javacopts: (list[str]) A list of the desired javac options. The options + may contain `$(location ..)` templates that will be expanded. + neverlink: (bool) Whether or not this library should be used only for + compilation and not at runtime. + strict_deps: (str) A string that specifies how to handle strict deps. + Possible values: 'OFF', 'ERROR', 'WARN' and 'DEFAULT'. For more details + see https://bazel.build/docs/user-manual#strict-java-deps. + By default 'ERROR'. + enable_compile_jar_action: (bool) Enables header compilation or ijar + creation. If set to False, it forces use of the full class jar in the + compilation classpaths of any dependants. Doing so is intended for use + by non-library targets such as binaries that do not have dependants. + add_exports: (list[str]) Allow this library to access the given /. + add_opens: (list[str]) Allow this library to reflectively access the given /. + bootclasspath: (BootClassPathInfo) The set of JDK APIs to compile this library against. + javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. + + Returns: + ((JavaInfo, {files_to_build: list[File], + runfiles: list[File], + compilation_classpath: list[File], + plugins: {processor_jars, + processor_data: depset[File]}})) + A tuple with JavaInfo provider and additional compilation info. + + Files_to_build may include an empty .jar file when there are no sources + or resources present, whereas runfiles in this case are empty. + """ + + java_info = _compile_private_for_builtins( + ctx, + output = output_class_jar, + java_toolchain = semantics.find_java_toolchain(ctx), + source_files = source_files, + source_jars = source_jars, + resources = resources, + resource_jars = resource_jars, + classpath_resources = classpath_resources, + plugins = plugins, + deps = deps, + native_libraries = native_libraries, + runtime_deps = runtime_deps, + exports = exports, + exported_plugins = exported_plugins, + javac_opts = [ctx.expand_location(opt) for opt in javacopts], + neverlink = neverlink, + output_source_jar = output_source_jar, + strict_deps = _filter_strict_deps(strict_deps), + enable_compile_jar_action = enable_compile_jar_action, + add_exports = add_exports, + add_opens = add_opens, + bootclasspath = bootclasspath, + javabuilder_jvm_flags = javabuilder_jvm_flags, + ) + + compilation_info = struct( + files_to_build = [output_class_jar], + runfiles = [output_class_jar] if source_files or source_jars or resources else [], + # TODO(ilist): collect compile_jars from JavaInfo in deps & exports + compilation_classpath = java_info.compilation_info.compilation_classpath, + javac_options = java_info.compilation_info.javac_options, + plugins = _collect_plugins(deps, plugins), + ) + + return java_info, compilation_info diff --git a/java/common/rules/import_deps_check.bzl b/java/common/rules/import_deps_check.bzl new file mode 100644 index 00000000..1981f13f --- /dev/null +++ b/java/common/rules/import_deps_check.bzl @@ -0,0 +1,81 @@ +# 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. + +"""Creates the import deps checker for java rules""" + +load("//java/common:java_semantics.bzl", "semantics") + +visibility("private") + +def import_deps_check( + ctx, + jars_to_check, + declared_deps, + transitive_deps, + rule_class): + """ + Creates actions that checks import deps for java rules. + + Args: + ctx: (RuleContext) Used to register the actions. + jars_to_check: (list[File]) A list of jars files to check. + declared_deps: (list[File]) A list of direct dependencies. + transitive_deps: (list[File]) A list of transitive dependencies. + rule_class: (String) Rule class. + + Returns: + (File) Output file of the created action. + """ + java_toolchain = semantics.find_java_toolchain(ctx) + deps_checker = java_toolchain._deps_checker + if deps_checker == None: + return None + + jdeps_output = ctx.actions.declare_file("_%s/%s/jdeps.proto" % (rule_class, ctx.label.name)) + + args = ctx.actions.args() + args.add("-jar", deps_checker) + args.add_all(jars_to_check, before_each = "--input") + args.add_all(declared_deps, before_each = "--directdep") + args.add_all( + depset(order = "preorder", transitive = [declared_deps, transitive_deps]), + before_each = "--classpath_entry", + ) + args.add_all(java_toolchain.bootclasspath, before_each = "--bootclasspath_entry") + args.add("--checking_mode=error") + args.add("--jdeps_output", jdeps_output) + args.add("--rule_label", ctx.label) + + inputs = depset( + jars_to_check, + transitive = [ + declared_deps, + transitive_deps, + java_toolchain.bootclasspath, + ], + ) + tools = [deps_checker, java_toolchain.java_runtime.files] + + ctx.actions.run( + mnemonic = "ImportDepsChecker", + progress_message = "Checking the completeness of the deps for %s" % jars_to_check, + executable = java_toolchain.java_runtime.java_executable_exec_path, + arguments = [args], + inputs = inputs, + outputs = [jdeps_output], + tools = tools, + toolchain = semantics.JAVA_TOOLCHAIN_TYPE, + ) + + return jdeps_output diff --git a/java/common/rules/java_binary.bzl b/java/common/rules/java_binary.bzl new file mode 100644 index 00000000..74a5ab9a --- /dev/null +++ b/java/common/rules/java_binary.bzl @@ -0,0 +1,821 @@ +# 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. + +""" Implementation of java_binary for bazel """ + +load("@rules_cc//cc/common:cc_common.bzl", "cc_common") +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") +load("//java/common:java_semantics.bzl", "PLATFORMS_ROOT", "semantics") +load("//third_party/bazel_skylib/lib:paths.bzl", "paths") +load("//third_party/protobuf/bazel/common:proto_info.bzl", "ProtoInfo") +load(":basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS", "basic_java_library", "collect_deps") +load(":java_binary_deploy_jar.bzl", "create_deploy_archive") +load(":java_helper.bzl", "helper") +load(":rule_util.bzl", "merge_attrs") + +visibility(["//java/..."]) + +BootClassPathInfo = java_common.BootClassPathInfo +CcLauncherInfo = cc_common.launcher_provider + +_java_common_internal = java_common.internal_DO_NOT_USE() +JavaCompilationInfo = _java_common_internal.JavaCompilationInfo +collect_native_deps_dirs = _java_common_internal.collect_native_deps_dirs +get_runtime_classpath_for_archive = _java_common_internal.get_runtime_classpath_for_archive +to_java_binary_info = _java_common_internal.to_java_binary_info + +InternalDeployJarInfo = provider( + "Provider for passing info to deploy jar rule", + fields = [ + "java_attrs", + "strip_as_default", + "add_exports", + "add_opens", + ], +) + +def basic_java_binary( + ctx, + deps, + runtime_deps, + resources, + main_class, + coverage_main_class, + coverage_config, + launcher_info, + executable, + strip_as_default, + extension_registry_provider = None, + is_test_rule_class = False): + """Creates actions for compiling and linting java sources, coverage support, and sources jar (_deploy-src.jar). + + Args: + ctx: (RuleContext) The rule context + deps: (list[Target]) The list of other targets to be compiled with + runtime_deps: (list[Target]) The list of other targets to be linked in + resources: (list[File]) The list of data files to be included in the class jar + main_class: (String) FQN of the java main class + coverage_main_class: (String) FQN of the actual main class if coverage is enabled + coverage_config: (Struct|None) If coverage is enabled, a struct with fields (runner, manifest, env, support_files), None otherwise + launcher_info: (Struct) Structure with fields (launcher, unstripped_launcher, runfiles, runtime_jars, jvm_flags, classpath_resources) + executable: (File) The executable output of the rule + strip_as_default: (bool) Whether this target outputs a stripped launcher and deploy jar + extension_registry_provider: (GeneratedExtensionRegistryProvider) internal param, do not use + is_test_rule_class: (bool) Whether this rule is a test rule + + Returns: + Tuple( + dict[str, Provider], // providers + Struct( // default info + files_to_build: depset(File), + runfiles: Runfiles, + executable: File + ), + list[String] // jvm flags + ) + + """ + if not ctx.attr.create_executable and (ctx.attr.launcher and cc_common.launcher_provider in ctx.attr.launcher): + fail("launcher specified but create_executable is false") + if not ctx.attr.use_launcher and (ctx.attr.launcher and ctx.attr.launcher.label != semantics.LAUNCHER_FLAG_LABEL): + fail("launcher specified but use_launcher is false") + + if not ctx.attr.srcs and ctx.attr.deps: + fail("deps not allowed without srcs; move to runtime_deps?") + + module_flags = [dep[JavaInfo].module_flags_info for dep in runtime_deps if JavaInfo in dep] + add_exports = depset(ctx.attr.add_exports, transitive = [m.add_exports for m in module_flags]) + add_opens = depset(ctx.attr.add_opens, transitive = [m.add_opens for m in module_flags]) + + classpath_resources = [] + classpath_resources.extend(launcher_info.classpath_resources) + if hasattr(ctx.files, "classpath_resources"): + classpath_resources.extend(ctx.files.classpath_resources) + + toolchain = semantics.find_java_toolchain(ctx) + timezone_data = [toolchain._timezone_data] if toolchain._timezone_data else [] + target, common_info = basic_java_library( + ctx, + srcs = ctx.files.srcs, + deps = deps, + runtime_deps = runtime_deps, + plugins = ctx.attr.plugins, + resources = resources, + resource_jars = timezone_data, + classpath_resources = classpath_resources, + javacopts = ctx.attr.javacopts, + neverlink = ctx.attr.neverlink, + enable_compile_jar_action = False, + coverage_config = coverage_config, + add_exports = ctx.attr.add_exports, + add_opens = ctx.attr.add_opens, + bootclasspath = ctx.attr.bootclasspath, + ) + java_info = target["JavaInfo"] + compilation_info = java_info.compilation_info + runtime_classpath = depset( + order = "preorder", + transitive = [ + java_info.transitive_runtime_jars + for java_info in ( + collect_deps(ctx.attr.runtime_deps + deps) + + ([coverage_config.runner] if coverage_config and coverage_config.runner else []) + ) + ], + ) + if extension_registry_provider: + runtime_classpath = depset(order = "preorder", direct = [extension_registry_provider.class_jar], transitive = [runtime_classpath]) + java_info = java_common.merge( + [ + java_info, + JavaInfo( + output_jar = extension_registry_provider.class_jar, + compile_jar = None, + source_jar = extension_registry_provider.src_jar, + ), + ], + ) + compilation_info = JavaCompilationInfo( + compilation_classpath = compilation_info.compilation_classpath, + runtime_classpath = runtime_classpath, + boot_classpath = compilation_info.boot_classpath, + javac_options = compilation_info.javac_options, + ) + + java_attrs = _collect_attrs(ctx, runtime_classpath, classpath_resources) + + jvm_flags = [] + + jvm_flags.extend(launcher_info.jvm_flags) + + native_libs_depsets = [] + for dep in runtime_deps: + if JavaInfo in dep: + native_libs_depsets.append(dep[JavaInfo].transitive_native_libraries) + if CcInfo in dep: + native_libs_depsets.append(dep[CcInfo].transitive_native_libraries()) + native_libs_dirs = collect_native_deps_dirs(depset(transitive = native_libs_depsets)) + if native_libs_dirs: + prefix = "${JAVA_RUNFILES}/" + ctx.workspace_name + "/" + jvm_flags.append("-Djava.library.path=%s" % ( + ":".join([prefix + d for d in native_libs_dirs]) + )) + + jvm_flags.extend(ctx.fragments.java.default_jvm_opts) + jvm_flags.extend([ctx.expand_make_variables( + "jvm_flags", + ctx.expand_location(flag, ctx.attr.data, short_paths = True), + {}, + ) for flag in ctx.attr.jvm_flags]) + + # TODO(cushon): make string formatting lazier once extend_template support is added + # https://github.com/bazelbuild/proposals#:~:text=2022%2D04%2D25,Starlark + jvm_flags.extend(["--add-exports=%s=ALL-UNNAMED" % x for x in add_exports.to_list()]) + jvm_flags.extend(["--add-opens=%s=ALL-UNNAMED" % x for x in add_opens.to_list()]) + + files_to_build = [] + + if executable: + files_to_build.append(executable) + + output_groups = common_info.output_groups + + if coverage_config: + _generate_coverage_manifest(ctx, coverage_config.manifest, java_attrs.runtime_classpath) + files_to_build.append(coverage_config.manifest) + + if extension_registry_provider: + files_to_build.append(extension_registry_provider.class_jar) + output_groups["_direct_source_jars"] = ( + output_groups["_direct_source_jars"] + [extension_registry_provider.src_jar] + ) + output_groups["_source_jars"] = depset( + direct = [extension_registry_provider.src_jar], + transitive = [output_groups["_source_jars"]], + ) + + if (ctx.fragments.java.one_version_enforcement_on_java_tests or not is_test_rule_class): + one_version_output = _create_one_version_check(ctx, java_attrs.runtime_classpath, is_test_rule_class) + else: + one_version_output = None + + validation_outputs = [one_version_output] if one_version_output else [] + + _create_deploy_sources_jar(ctx, output_groups["_source_jars"]) + + files = depset(files_to_build + common_info.files_to_build) + + transitive_runfiles_artifacts = depset(transitive = [ + files, + java_attrs.runtime_classpath, + depset(transitive = launcher_info.runfiles), + ]) + + runfiles = ctx.runfiles( + transitive_files = transitive_runfiles_artifacts, + collect_default = True, + ) + + if launcher_info.launcher: + default_launcher = helper.filter_launcher_for_target(ctx) + default_launcher_artifact = helper.launcher_artifact_for_target(ctx) + default_launcher_runfiles = default_launcher[DefaultInfo].default_runfiles + if default_launcher_artifact == launcher_info.launcher: + runfiles = runfiles.merge(default_launcher_runfiles) + else: + # N.B. The "default launcher" referred to here is the launcher target specified through + # an attribute or flag. We wish to retain the runfiles of the default launcher, *except* + # for the original cc_binary artifact, because we've swapped it out with our custom + # launcher. Hence, instead of calling builder.addTarget(), or adding an odd method + # to Runfiles.Builder, we "unravel" the call and manually add things to the builder. + # Because the NestedSet representing each target's launcher runfiles is re-built here, + # we may see increased memory consumption for representing the target's runfiles. + runfiles = runfiles.merge( + ctx.runfiles( + files = [launcher_info.launcher], + transitive_files = depset([ + file + for file in default_launcher_runfiles.files.to_list() + if file != default_launcher_artifact + ]), + symlinks = default_launcher_runfiles.symlinks, + root_symlinks = default_launcher_runfiles.root_symlinks, + ), + ) + + runfiles = runfiles.merge_all([ + dep[DefaultInfo].default_runfiles + for dep in ctx.attr.runtime_deps + if DefaultInfo in dep + ]) + + if validation_outputs: + output_groups["_validation"] = output_groups.get("_validation", []) + validation_outputs + + _filter_validation_output_group(ctx, output_groups) + + java_binary_info = to_java_binary_info(java_info, compilation_info) + + internal_deploy_jar_info = InternalDeployJarInfo( + java_attrs = java_attrs, + strip_as_default = strip_as_default, + add_exports = add_exports, + add_opens = add_opens, + ) + + # "temporary" workaround for https://github.com/bazelbuild/intellij/issues/5845 + extra_files = [] + if is_test_rule_class and ctx.fragments.java.auto_create_java_test_deploy_jars(): + extra_files.append(_auto_create_deploy_jar(ctx, internal_deploy_jar_info, launcher_info, main_class, coverage_main_class)) + + default_info = struct( + files = depset(extra_files, transitive = [files]), + runfiles = runfiles, + executable = executable, + ) + + return { + "OutputGroupInfo": OutputGroupInfo(**output_groups), + "JavaInfo": java_binary_info, + "InstrumentedFilesInfo": target["InstrumentedFilesInfo"], + "JavaRuntimeClasspathInfo": java_common.JavaRuntimeClasspathInfo(runtime_classpath = java_info.transitive_runtime_jars), + "InternalDeployJarInfo": internal_deploy_jar_info, + }, default_info, jvm_flags + +def _collect_attrs(ctx, runtime_classpath, classpath_resources): + deploy_env_jars = depset(transitive = [ + dep[java_common.JavaRuntimeClasspathInfo].runtime_classpath + for dep in ctx.attr.deploy_env + ]) if hasattr(ctx.attr, "deploy_env") else depset() + + runtime_classpath_for_archive = get_runtime_classpath_for_archive(runtime_classpath, deploy_env_jars) + runtime_jars = [ctx.outputs.classjar] + + resources = [p for p in ctx.files.srcs if p.extension == "properties"] + transitive_resources = [] + for r in ctx.attr.resources: + transitive_resources.append( + r[ProtoInfo].transitive_sources if ProtoInfo in r else r.files, + ) + + resource_names = dict() + for r in classpath_resources: + if r.basename in resource_names: + fail("entries must have different file names (duplicate: %s)" % r.basename) + resource_names[r.basename] = None + + return struct( + runtime_jars = depset(runtime_jars), + runtime_classpath_for_archive = runtime_classpath_for_archive, + classpath_resources = depset(classpath_resources), + runtime_classpath = depset(order = "preorder", direct = runtime_jars, transitive = [runtime_classpath]), + resources = depset(resources, transitive = transitive_resources), + ) + +def _generate_coverage_manifest(ctx, output, runtime_classpath): + ctx.actions.write( + output = output, + content = "\n".join([file.short_path for file in runtime_classpath.to_list()]), + ) + +def _create_one_version_check(ctx, inputs, is_test_rule_class): + one_version_level = ctx.fragments.java.one_version_enforcement_level + if one_version_level == "OFF": + return None + tool = helper.check_and_get_one_version_attribute(ctx, "_one_version_tool") + + if is_test_rule_class: + toolchain = semantics.find_java_toolchain(ctx) + allowlist = toolchain._one_version_allowlist_for_tests + else: + allowlist = helper.check_and_get_one_version_attribute(ctx, "_one_version_allowlist") + + if not tool: # On Mac oneversion tool is not available + return None + + output = ctx.actions.declare_file("%s-one-version.txt" % ctx.label.name) + + args = ctx.actions.args() + args.set_param_file_format("shell").use_param_file("@%s", use_always = True) + + one_version_inputs = [] + args.add("--output", output) + if allowlist: + args.add("--whitelist", allowlist) + one_version_inputs.append(allowlist) + if one_version_level == "WARNING": + args.add("--succeed_on_found_violations") + args.add_all( + "--inputs", + inputs, + map_each = helper.jar_and_target_arg_mapper, + ) + + ctx.actions.run( + mnemonic = "JavaOneVersion", + progress_message = "Checking for one-version violations in %{label}", + executable = tool, + toolchain = semantics.JAVA_TOOLCHAIN_TYPE, + inputs = depset(one_version_inputs, transitive = [inputs]), + tools = [tool], + outputs = [output], + arguments = [args], + ) + + return output + +def _create_deploy_sources_jar(ctx, sources): + helper.create_single_jar( + ctx.actions, + toolchain = semantics.find_java_toolchain(ctx), + output = ctx.outputs.deploysrcjar, + sources = sources, + ) + +def _filter_validation_output_group(ctx, output_group): + to_exclude = depset(transitive = [ + dep[OutputGroupInfo]._validation + for dep in ctx.attr.deploy_env + if OutputGroupInfo in dep and hasattr(dep[OutputGroupInfo], "_validation") + ]) if hasattr(ctx.attr, "deploy_env") else depset() + if to_exclude: + transitive_validations = depset(transitive = [ + _get_validations_from_attr(ctx, attr_name) + for attr_name in dir(ctx.attr) + # we also exclude implicit, cfg=host/exec and tool attributes + if not attr_name.startswith("_") and + attr_name not in [ + "deploy_env", + "applicable_licenses", + "package_metadata", + "plugins", + "translations", + # special ignored attributes + "compatible_with", + "restricted_to", + "exec_compatible_with", + "target_compatible_with", + ] + ]) + if not ctx.attr.create_executable: + excluded_set = {x: None for x in to_exclude.to_list()} + transitive_validations = [ + x + for x in transitive_validations.to_list() + if x not in excluded_set + ] + output_group["_validation_transitive"] = transitive_validations + +def _get_validations_from_attr(ctx, attr_name): + attr = getattr(ctx.attr, attr_name) + if type(attr) == "list": + return depset(transitive = [_get_validations_from_target(t) for t in attr]) + else: + return _get_validations_from_target(attr) + +def _get_validations_from_target(target): + if ( + type(target) == "Target" and + OutputGroupInfo in target and + hasattr(target[OutputGroupInfo], "_validation") + ): + return target[OutputGroupInfo]._validation + else: + return depset() + +# TODO: bazelbuild/intellij/issues/5845 - remove this once no longer required +# this need not be completely identical to the regular deploy jar since we only +# care about packaging the classpath +def _auto_create_deploy_jar(ctx, info, launcher_info, main_class, coverage_main_class): + output = ctx.actions.declare_file(ctx.label.name + "_auto_deploy.jar") + java_attrs = info.java_attrs + runtime_classpath = depset( + direct = launcher_info.runtime_jars, + transitive = [ + java_attrs.runtime_jars, + java_attrs.runtime_classpath_for_archive, + ], + order = "preorder", + ) + create_deploy_archive( + ctx, + launcher = launcher_info.launcher, + main_class = main_class, + coverage_main_class = coverage_main_class, + resources = java_attrs.resources, + classpath_resources = java_attrs.classpath_resources, + runtime_classpath = runtime_classpath, + manifest_lines = info.manifest_lines, + build_info_files = [], + build_target = str(ctx.label), + output = output, + one_version_level = ctx.fragments.java.one_version_enforcement_level, + one_version_allowlist = helper.check_and_get_one_version_attribute(ctx, "_one_version_allowlist"), + multi_release = ctx.fragments.java.multi_release_deploy_jars, + hermetic = hasattr(ctx.attr, "hermetic") and ctx.attr.hermetic, + add_exports = info.add_exports, + add_opens = info.add_opens, + ) + return output + +BASIC_JAVA_BINARY_ATTRIBUTES = merge_attrs( + BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS, + # buildifier: disable=attr-licenses + { + "srcs": attr.label_list( + allow_files = [".java", ".srcjar", ".properties"] + semantics.EXTRA_SRCS_TYPES, + flags = ["DIRECT_COMPILE_TIME_INPUT", "ORDER_INDEPENDENT"], + doc = """ +The list of source files that are processed to create the target. +This attribute is almost always required; see exceptions below. +

+Source files of type .java are compiled. In case of generated +.java files it is generally advisable to put the generating rule's name +here instead of the name of the file itself. This not only improves readability but +makes the rule more resilient to future changes: if the generating rule generates +different files in the future, you only need to fix one place: the outs of +the generating rule. You should not list the generating rule in deps +because it is a no-op. +

+

+Source files of type .srcjar are unpacked and compiled. (This is useful if +you need to generate a set of .java files with a genrule.) +

+

+Rules: if the rule (typically genrule or filegroup) generates +any of the files listed above, they will be used the same way as described for source +files. +

+ +

+This argument is almost always required, except if a +main_class attribute specifies a +class on the runtime classpath or you specify the runtime_deps argument. +

+ """, + ), + "deps": attr.label_list( + allow_files = [".jar"], + allow_rules = semantics.ALLOWED_RULES_IN_DEPS + semantics.ALLOWED_RULES_IN_DEPS_WITH_WARNING, + providers = [ + [CcInfo], + [JavaInfo], + ], + flags = ["SKIP_ANALYSIS_TIME_FILETYPE_CHECK"], + doc = """ +The list of other libraries to be linked in to the target. +See general comments about deps at +Typical attributes defined by +most build rules. + """, + ), + "resources": attr.label_list( + allow_files = True, + flags = ["SKIP_CONSTRAINTS_OVERRIDE", "ORDER_INDEPENDENT"], + doc = """ +A list of data files to include in a Java jar. + +

+Resources may be source files or generated files. +

+ """ + semantics.DOCS.for_attribute("resources"), + ), + "runtime_deps": attr.label_list( + allow_files = [".jar"], + allow_rules = semantics.ALLOWED_RULES_IN_DEPS, + providers = [[CcInfo], [JavaInfo]], + flags = ["SKIP_ANALYSIS_TIME_FILETYPE_CHECK"], + doc = """ +Libraries to make available to the final binary or test at runtime only. +Like ordinary deps, these will appear on the runtime classpath, but unlike +them, not on the compile-time classpath. Dependencies needed only at runtime should be +listed here. Dependency-analysis tools should ignore targets that appear in both +runtime_deps and deps. + """, + ), + "data": attr.label_list( + allow_files = True, + flags = ["SKIP_CONSTRAINTS_OVERRIDE"], + doc = """ +The list of files needed by this library at runtime. +See general comments about data +at Typical attributes defined by +most build rules. + """ + semantics.DOCS.for_attribute("data"), + ), + "plugins": attr.label_list( + providers = [JavaPluginInfo], + allow_files = True, + cfg = "exec", + doc = """ +Java compiler plugins to run at compile-time. +Every java_plugin specified in this attribute will be run whenever this rule +is built. A library may also inherit plugins from dependencies that use +exported_plugins. Resources +generated by the plugin will be included in the resulting jar of this rule. + """, + ), + "deploy_env": attr.label_list( + providers = [java_common.JavaRuntimeClasspathInfo], + allow_files = False, + doc = """ +A list of other java_binary targets which represent the deployment +environment for this binary. +Set this attribute when building a plugin which will be loaded by another +java_binary.
Setting this attribute excludes all dependencies from +the runtime classpath (and the deploy jar) of this binary that are shared between this +binary and the targets specified in deploy_env. + """, + ), + "launcher": attr.label( + # TODO(b/295221112): add back CcLauncherInfo + allow_files = False, + doc = """ +Specify a binary that will be used to run your Java program instead of the +normal bin/java program included with the JDK. +The target must be a cc_binary. Any cc_binary that +implements the + +Java Invocation API can be specified as a value for this attribute. + +

By default, Bazel will use the normal JDK launcher (bin/java or java.exe).

+ +

The related +--java_launcher Bazel flag affects only those +java_binary and java_test targets that have +not specified a launcher attribute.

+ +

Note that your native (C++, SWIG, JNI) dependencies will be built differently +depending on whether you are using the JDK launcher or another launcher:

+ +
    +
  • If you are using the normal JDK launcher (the default), native dependencies are +built as a shared library named {name}_nativedeps.so, where +{name} is the name attribute of this java_binary rule. +Unused code is not removed by the linker in this configuration.
  • + +
  • If you are using any other launcher, native (C++) dependencies are statically +linked into a binary named {name}_nativedeps, where {name} +is the name attribute of this java_binary rule. In this case, +the linker will remove any code it thinks is unused from the resulting binary, +which means any C++ code accessed only via JNI may not be linked in unless +that cc_library target specifies alwayslink = 1.
  • +
+ +

When using any launcher other than the default JDK launcher, the format +of the *_deploy.jar output changes. See the main +java_binary docs for details.

+ """, + ), + "bootclasspath": attr.label( + providers = [BootClassPathInfo], + flags = ["SKIP_CONSTRAINTS_OVERRIDE"], + doc = "Restricted API, do not use!", + ), + "neverlink": attr.bool(), + "javacopts": attr.string_list( + doc = """ +Extra compiler options for this binary. +Subject to "Make variable" substitution and +Bourne shell tokenization. +

These compiler options are passed to javac after the global compiler options.

+ """, + ), + "add_exports": attr.string_list( + doc = """ +Allow this library to access the given module or package. +

+This corresponds to the javac and JVM --add-exports= flags. + """, + ), + "add_opens": attr.string_list( + doc = """ +Allow this library to reflectively access the given module or +package. +

+This corresponds to the javac and JVM --add-opens= flags. + """, + ), + "main_class": attr.string( + doc = """ +Name of class with main() method to use as entry point. +If a rule uses this option, it does not need a srcs=[...] list. +Thus, with this attribute one can make an executable from a Java library that already +contains one or more main() methods. +

+The value of this attribute is a class name, not a source file. The class must be +available at runtime: it may be compiled by this rule (from srcs) or +provided by direct or transitive dependencies (through runtime_deps or +deps). If the class is unavailable, the binary will fail at runtime; there +is no build-time check. +

+ """, + ), + "jvm_flags": attr.string_list( + doc = """ +A list of flags to embed in the wrapper script generated for running this binary. +Subject to $(location) and +"Make variable" substitution, and +Bourne shell tokenization. + +

The wrapper script for a Java binary includes a CLASSPATH definition +(to find all the dependent jars) and invokes the right Java interpreter. +The command line generated by the wrapper script includes the name of +the main class followed by a "$@" so you can pass along other +arguments after the classname. However, arguments intended for parsing +by the JVM must be specified before the classname on the command +line. The contents of jvm_flags are added to the wrapper +script before the classname is listed.

+ +

Note that this attribute has no effect on *_deploy.jar +outputs.

+ """, + ), + "deploy_manifest_lines": attr.string_list( + doc = """ +A list of lines to add to the META-INF/manifest.mf file generated for the +*_deploy.jar target. The contents of this attribute are not subject +to "Make variable" substitution. + """, + ), + "stamp": attr.int( + default = -1, + values = [-1, 0, 1], + doc = """ +Whether to encode build information into the binary. Possible values: +
    +
  • + stamp = 1: Always stamp the build information into the binary, even in + --nostamp builds. This + setting should be avoided, since it potentially kills remote caching for the + binary and any downstream actions that depend on it. +
  • +
  • + stamp = 0: Always replace build information by constant values. This + gives good build result caching. +
  • +
  • + stamp = -1: Embedding of build information is controlled by the + --[no]stamp flag. +
  • +
+

Stamped binaries are not rebuilt unless their dependencies change.

+ """, + ), + "use_testrunner": attr.bool( + default = False, + doc = semantics.DOCS.for_attribute("use_testrunner") + """ +
+You can use this to override the default +behavior, which is to use test runner for +java_test rules, +and not use it for java_binary rules. It is unlikely +you will want to do this. One use is for AllTest +rules that are invoked by another rule (to set up a database +before running the tests, for example). The AllTest +rule must be declared as a java_binary, but should +still use the test runner as its main entry point. + +The name of a test runner class can be overridden with main_class attribute. + """, + ), + "use_launcher": attr.bool( + default = True, + doc = """ +Whether the binary should use a custom launcher. + +

If this attribute is set to false, the +launcher attribute and the related +--java_launcher flag +will be ignored for this target. + """, + ), + "env": attr.string_dict(), + "classpath_resources": attr.label_list( + allow_files = True, + doc = """ +DO NOT USE THIS OPTION UNLESS THERE IS NO OTHER WAY) +

+A list of resources that must be located at the root of the java tree. This attribute's +only purpose is to support third-party libraries that require that their resources be +found on the classpath as exactly "myconfig.xml". It is only allowed on +binaries and not libraries, due to the danger of namespace conflicts. +

+ """, + ), + "licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), + "_stub_template": attr.label( + default = semantics.JAVA_STUB_TEMPLATE_LABEL, + allow_single_file = True, + ), + "_java_toolchain_type": attr.label(default = semantics.JAVA_TOOLCHAIN_TYPE), + "_windows_constraints": attr.label_list( + default = [paths.join(PLATFORMS_ROOT, "os:windows")], + ), + "_build_info_translator": attr.label(default = semantics.BUILD_INFO_TRANSLATOR_LABEL), + } | ({} if _java_common_internal.incompatible_disable_non_executable_java_binary() else {"create_executable": attr.bool(default = True, doc = "Deprecated, use java_single_jar instead.")}), +) + +BASE_TEST_ATTRIBUTES = { + "test_class": attr.string( + doc = """ +The Java class to be loaded by the test runner.
+

+ By default, if this argument is not defined then the legacy mode is used and the + test arguments are used instead. Set the --nolegacy_bazel_java_test flag + to not fallback on the first argument. +

+

+ This attribute specifies the name of a Java class to be run by + this test. It is rare to need to set this. If this argument is omitted, + it will be inferred using the target's name and its + source-root-relative path. If the test is located outside a known + source root, Bazel will report an error if test_class + is unset. +

+

+ For JUnit3, the test class needs to either be a subclass of + junit.framework.TestCase or it needs to have a public + static suite() method that returns a + junit.framework.Test (or a subclass of Test). + For JUnit4, the class needs to be annotated with + org.junit.runner.RunWith. +

+

+ This attribute allows several java_test rules to + share the same Test + (TestCase, TestSuite, ...). Typically + additional information is passed to it + (e.g. via jvm_flags=['-Dkey=value']) so that its + behavior differs in each case, such as running a different + subset of the tests. This attribute also enables the use of + Java tests outside the javatests tree. +

+ """, + ), + "env_inherit": attr.string_list(), + "_apple_constraints": attr.label_list( + default = [ + paths.join(PLATFORMS_ROOT, "os:ios"), + paths.join(PLATFORMS_ROOT, "os:macos"), + paths.join(PLATFORMS_ROOT, "os:tvos"), + paths.join(PLATFORMS_ROOT, "os:visionos"), + paths.join(PLATFORMS_ROOT, "os:watchos"), + ], + ), + "_legacy_any_type_attrs": attr.string_list(default = ["stamp"]), +} diff --git a/java/common/rules/java_binary_deploy_jar.bzl b/java/common/rules/java_binary_deploy_jar.bzl new file mode 100644 index 00000000..183be458 --- /dev/null +++ b/java/common/rules/java_binary_deploy_jar.bzl @@ -0,0 +1,248 @@ +# 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. + +"""Auxiliary rule to create the deploy archives for java_binary""" + +load("//java/common:java_semantics.bzl", "semantics") +load(":java_helper.bzl", "helper") + +visibility(["//java/..."]) + +def _get_build_info(ctx, stamp): + if helper.is_stamping_enabled(ctx, stamp): + # Makes the target depend on BUILD_INFO_KEY, which helps to discover stamped targets + # See b/326620485 for more details. + ctx.version_file # buildifier: disable=no-effect + return ctx.attr._build_info_translator[OutputGroupInfo].non_redacted_build_info_files.to_list() + else: + return ctx.attr._build_info_translator[OutputGroupInfo].redacted_build_info_files.to_list() + +def create_deploy_archives( + ctx, + java_attrs, + launcher_info, + main_class, + coverage_main_class, + strip_as_default, + hermetic = False, + add_exports = depset(), + add_opens = depset(), + shared_archive = None, + one_version_level = "OFF", + one_version_allowlist = None, + extra_args = [], + extra_manifest_lines = []): + """ Registers actions for _deploy.jar and _deploy.jar.unstripped + + Args: + ctx: (RuleContext) The rule context + java_attrs: (Struct) Struct of (classpath_resources, runtime_jars, runtime_classpath_for_archive, resources) + launcher_info: (Struct) Struct of (runtime_jars, launcher, unstripped_launcher) + main_class: (String) FQN of the entry point for execution + coverage_main_class: (String) FQN of the entry point for coverage collection + strip_as_default: (bool) Whether to create unstripped deploy jar + hermetic: (bool) + add_exports: (depset) + add_opens: (depset) + shared_archive: (File) Optional .jsa artifact + one_version_level: (String) Optional one version check level, default OFF + one_version_allowlist: (File) Optional allowlist for one version check + extra_args: (list[Args]) Optional arguments for the deploy jar action + extra_manifest_lines: (list[String]) Optional lines added to the jar manifest + """ + classpath_resources = java_attrs.classpath_resources + + runtime_classpath = depset( + direct = launcher_info.runtime_jars, + transitive = [ + java_attrs.runtime_jars, + java_attrs.runtime_classpath_for_archive, + ], + order = "preorder", + ) + multi_release = ctx.fragments.java.multi_release_deploy_jars + build_info_files = _get_build_info(ctx, ctx.attr.stamp) + build_target = str(ctx.label) + manifest_lines = ctx.attr.deploy_manifest_lines + extra_manifest_lines + create_deploy_archive( + ctx, + launcher_info.launcher, + main_class, + coverage_main_class, + java_attrs.resources, + classpath_resources, + runtime_classpath, + manifest_lines, + build_info_files, + build_target, + output = ctx.outputs.deployjar, + shared_archive = shared_archive, + one_version_level = one_version_level, + one_version_allowlist = one_version_allowlist, + multi_release = multi_release, + hermetic = hermetic, + add_exports = add_exports, + add_opens = add_opens, + extra_args = extra_args, + ) + + if strip_as_default: + create_deploy_archive( + ctx, + launcher_info.unstripped_launcher, + main_class, + coverage_main_class, + java_attrs.resources, + classpath_resources, + runtime_classpath, + manifest_lines, + build_info_files, + build_target, + output = ctx.outputs.unstrippeddeployjar, + multi_release = multi_release, + hermetic = hermetic, + add_exports = add_exports, + add_opens = add_opens, + extra_args = extra_args, + ) + else: + ctx.actions.write(ctx.outputs.unstrippeddeployjar, "") + +def create_deploy_archive( + ctx, + launcher, + main_class, + coverage_main_class, + resources, + classpath_resources, + runtime_classpath, + manifest_lines, + build_info_files, + build_target, + output, + shared_archive = None, + one_version_level = "OFF", + one_version_allowlist = None, + multi_release = False, + hermetic = False, + add_exports = [], + add_opens = [], + extra_args = []): + """ Creates a deploy jar + + Requires a Java runtime toolchain if and only if hermetic is True. + + Args: + ctx: (RuleContext) The rule context + launcher: (File) the launcher artifact + main_class: (String) FQN of the entry point for execution + coverage_main_class: (String) FQN of the entry point for coverage collection + resources: (Depset) resource inputs + classpath_resources: (Depset) classpath resource inputs + runtime_classpath: (Depset) source files to add to the jar + build_target: (String) Name of the build target for stamping + manifest_lines: (list[String]) Optional lines added to the jar manifest + build_info_files: (list[File]) build info files for stamping + build_target: (String) the owner build target label name string + output: (File) the output jar artifact + shared_archive: (File) Optional .jsa artifact + one_version_level: (String) Optional one version check level, default OFF + one_version_allowlist: (File) Optional allowlist for one version check + multi_release: (bool) + hermetic: (bool) + add_exports: (depset) + add_opens: (depset) + extra_args: (list[Args]) Optional arguments for the deploy jar action + """ + input_files = [] + input_files.extend(build_info_files) + + transitive_input_files = [ + resources, + classpath_resources, + runtime_classpath, + ] + + single_jar = semantics.find_java_toolchain(ctx).single_jar + + manifest_lines = list(manifest_lines) + if ctx.configuration.coverage_enabled: + manifest_lines.append("Coverage-Main-Class: %s" % coverage_main_class) + + args = ctx.actions.args() + args.set_param_file_format("shell").use_param_file("@%s", use_always = True) + + args.add("--output", output) + args.add("--build_target", build_target) + args.add("--normalize") + args.add("--compression") + if main_class: + args.add("--main_class", main_class) + args.add_all("--deploy_manifest_lines", manifest_lines) + args.add_all(build_info_files, before_each = "--build_info_file") + if launcher: + input_files.append(launcher) + args.add("--java_launcher", launcher) + args.add_all("--classpath_resources", classpath_resources) + args.add_all( + "--sources", + runtime_classpath, + map_each = helper.jar_and_target_arg_mapper, + ) + + if one_version_level != "OFF" and one_version_allowlist: + input_files.append(one_version_allowlist) + args.add("--enforce_one_version") + args.add("--one_version_whitelist", one_version_allowlist) + if one_version_level == "WARNING": + args.add("--succeed_on_found_violations") + + if multi_release: + args.add("--multi_release") + + if hermetic: + runtime = ctx.toolchains["@//tools/jdk/hermetic:hermetic_runtime_toolchain_type"].java_runtime + if runtime.lib_modules != None: + java_home = runtime.java_home + lib_modules = runtime.lib_modules + hermetic_files = runtime.hermetic_files + args.add("--hermetic_java_home", java_home) + args.add("--jdk_lib_modules", lib_modules) + args.add_all("--resources", hermetic_files) + input_files.append(lib_modules) + transitive_input_files.append(hermetic_files) + + if shared_archive == None: + shared_archive = runtime.default_cds + + if shared_archive: + input_files.append(shared_archive) + args.add("--cds_archive", shared_archive) + + args.add_all("--add_exports", add_exports) + args.add_all("--add_opens", add_opens) + + inputs = depset(input_files, transitive = transitive_input_files) + + ctx.actions.run( + mnemonic = "JavaDeployJar", + progress_message = "Building deploy jar %s" % output.short_path, + executable = single_jar, + inputs = inputs, + tools = [single_jar], + outputs = [output], + arguments = [args] + extra_args, + use_default_shell_env = True, + toolchain = semantics.JAVA_TOOLCHAIN_TYPE, + ) diff --git a/java/common/rules/java_binary_wrapper.bzl b/java/common/rules/java_binary_wrapper.bzl new file mode 100644 index 00000000..3d94dcd7 --- /dev/null +++ b/java/common/rules/java_binary_wrapper.bzl @@ -0,0 +1,73 @@ +# 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. + +"""Macro encapsulating the java_binary implementation + +This is needed since the `executable` nature of the target must be computed from +the supplied value of the `create_executable` attribute. +""" + +load("//java/common:java_semantics.bzl", "semantics") + +visibility(["//java/..."]) + +def register_legacy_java_binary_rules( + rule_exec, + rule_nonexec, + **kwargs): + """Registers the correct java_binary rule and deploy jar rule + + Args: + rule_exec: (Rule) The executable java_binary rule + rule_nonexec: (Rule) The non-executable java_binary rule + **kwargs: Actual args to instantiate the rule + """ + + create_executable = "create_executable" not in kwargs or kwargs["create_executable"] + + # TODO(hvd): migrate depot to integers / maybe use decompose_select_list() + if "stamp" in kwargs and type(kwargs["stamp"]) == type(True): + kwargs["stamp"] = 1 if kwargs["stamp"] else 0 + if not create_executable: + rule_nonexec(**kwargs) + else: + if "use_launcher" in kwargs and not kwargs["use_launcher"]: + kwargs["launcher"] = None + else: + # If launcher is not set or None, set it to config flag + if "launcher" not in kwargs or not kwargs["launcher"]: + kwargs["launcher"] = semantics.LAUNCHER_FLAG_LABEL + rule_exec(**kwargs) + +def register_java_binary_rules( + java_binary, + **kwargs): + """Creates a java_binary rule and a deploy jar rule + + Args: + java_binary: (Rule) The executable java_binary rule + **kwargs: Actual args to instantiate the rule + """ + + # TODO(hvd): migrate depot to integers / maybe use decompose_select_list() + if "stamp" in kwargs and type(kwargs["stamp"]) == type(True): + kwargs["stamp"] = 1 if kwargs["stamp"] else 0 + + if "use_launcher" in kwargs and not kwargs["use_launcher"]: + kwargs["launcher"] = None + else: + # If launcher is not set or None, set it to config flag + if "launcher" not in kwargs or not kwargs["launcher"]: + kwargs["launcher"] = semantics.LAUNCHER_FLAG_LABEL + java_binary(**kwargs) diff --git a/java/common/rules/java_helper.bzl b/java/common/rules/java_helper.bzl new file mode 100644 index 00000000..c0aa231a --- /dev/null +++ b/java/common/rules/java_helper.bzl @@ -0,0 +1,507 @@ +# 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 util functions for java_* rules""" + +load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cc_toolchain") +load("@rules_cc//cc/common:cc_common.bzl", "cc_common") +load("@rules_cc//cc/common:cc_helper.bzl", "cc_helper") +load( + "//java/common:java_semantics.bzl", + "semantics", + _semantics_tokenize_javacopts = "tokenize_javacopts", +) +load("//third_party/bazel_skylib/lib:paths.bzl", "paths") + +visibility(["//java/..."]) + +def _collect_all_targets_as_deps(ctx, classpath_type = "all"): + deps = [] + if not classpath_type == "compile_only": + if hasattr(ctx.attr, "runtime_deps"): + deps.extend(ctx.attr.runtime_deps) + if hasattr(ctx.attr, "exports"): + deps.extend(ctx.attr.exports) + + deps.extend(ctx.attr.deps or []) + + launcher = _filter_launcher_for_target(ctx) + if launcher: + deps.append(launcher) + + return deps + +def _filter_launcher_for_target(ctx): + # create_executable=0 disables the launcher + if hasattr(ctx.attr, "create_executable") and not ctx.attr.create_executable: + return None + + # use_launcher=False disables the launcher + if hasattr(ctx.attr, "use_launcher") and not ctx.attr.use_launcher: + return None + + # BUILD rule "launcher" attribute + if ctx.attr.launcher and cc_common.launcher_provider in ctx.attr.launcher: + return ctx.attr.launcher + + return None + +def _launcher_artifact_for_target(ctx): + launcher = _filter_launcher_for_target(ctx) + if not launcher: + return None + files = launcher[DefaultInfo].files.to_list() + if len(files) != 1: + fail("%s expected a single artifact in %s" % (ctx.label, launcher)) + return files[0] + +def _check_and_get_main_class(ctx): + create_executable = ctx.attr.create_executable + use_testrunner = ctx.attr.use_testrunner + main_class = ctx.attr.main_class + + if not create_executable and use_testrunner: + fail("cannot have use_testrunner without creating an executable") + if not create_executable and main_class: + fail("main class must not be specified when executable is not created") + if create_executable and not use_testrunner: + if not main_class: + if not ctx.attr.srcs: + fail("need at least one of 'main_class', 'use_testrunner' or Java source files") + main_class = _primary_class(ctx) + if main_class == None: + fail("main_class was not provided and cannot be inferred: " + + "source path doesn't include a known root (java, javatests, src, testsrc)") + if not create_executable: + return None + if not main_class: + if use_testrunner: + main_class = "com.google.testing.junit.runner.GoogleTestRunner" + else: + main_class = _primary_class(ctx) + return main_class + +def _primary_class(ctx): + if ctx.attr.srcs: + main = ctx.label.name + ".java" + for src in ctx.files.srcs: + if src.basename == main: + return _full_classname(_strip_extension(src)) + return _full_classname(paths.get_relative(ctx.label.package, ctx.label.name)) + +def _strip_extension(file): + return file.dirname + "/" + ( + file.basename[:-(1 + len(file.extension))] if file.extension else file.basename + ) + +# TODO(b/193629418): once out of builtins, create a canonical implementation and remove duplicates in depot +def _full_classname(path): + java_segments = _java_segments(path) + return ".".join(java_segments) if java_segments != None else None + +def _java_segments(path): + if path.startswith("/"): + fail("path must not be absolute: '%s'" % path) + segments = path.split("/") + root_idx = -1 + for idx, segment in enumerate(segments): + if segment in ["java", "javatests", "src", "testsrc"]: + root_idx = idx + break + if root_idx < 0: + return None + is_src = "src" == segments[root_idx] + check_mvn_idx = root_idx if is_src else -1 + if (root_idx == 0 or is_src): + for i in range(root_idx + 1, len(segments) - 1): + segment = segments[i] + if "src" == segment or (is_src and (segment in ["java", "javatests"])): + next = segments[i + 1] + if next in ["com", "org", "net"]: + root_idx = i + elif "src" == segment: + check_mvn_idx = i + break + + if check_mvn_idx >= 0 and check_mvn_idx < len(segments) - 2: + next = segments[check_mvn_idx + 1] + if next in ["main", "test"]: + next = segments[check_mvn_idx + 2] + if next in ["java", "resources"]: + root_idx = check_mvn_idx + 2 + return segments[(root_idx + 1):] + +def _concat(*lists): + result = [] + for list in lists: + result.extend(list) + return result + +def _get_shared_native_deps_path( + linker_inputs, + link_opts, + linkstamps, + build_info_artifacts, + features, + is_test_target_partially_disabled_thin_lto): + """ + Returns the path of the shared native library. + + The name must be generated based on the rule-specific inputs to the link actions. At this point + this includes order-sensitive list of linker inputs and options collected from the transitive + closure and linkstamp-related artifacts that are compiled during linking. All those inputs can + be affected by modifying target attributes (srcs/deps/stamp/etc). However, target build + configuration can be ignored since it will either change output directory (in case of different + configuration instances) or will not affect anything (if two targets use same configuration). + Final goal is for all native libraries that use identical linker command to use same output + name. + +

TODO(bazel-team): (2010) Currently process of identifying parameters that can affect native + library name is manual and should be kept in sync with the code in the + CppLinkAction.Builder/CppLinkAction/Link classes which are responsible for generating linker + command line. Ideally we should reuse generated command line for both purposes - selecting a + name of the native library and using it as link action payload. For now, correctness of the + method below is only ensured by validations in the CppLinkAction.Builder.build() method. + """ + + fp = "" + for artifact in linker_inputs: + fp += artifact.short_path + fp += str(len(link_opts)) + for opt in link_opts: + fp += opt + for artifact in linkstamps: + fp += artifact.short_path + for artifact in build_info_artifacts: + fp += artifact.short_path + for feature in features: + fp += feature + + # Sharing of native dependencies may cause an ActionConflictException when ThinLTO is + # disabled for test and test-only targets that are statically linked, but enabled for other + # statically linked targets. This happens in case the artifacts for the shared native + # dependency are output by actions owned by the non-test and test targets both. To fix + # this, we allow creation of multiple artifacts for the shared native library - one shared + # among the test and test-only targets where ThinLTO is disabled, and the other shared among + # other targets where ThinLTO is enabled. + fp += "1" if is_test_target_partially_disabled_thin_lto else "0" + + fingerprint = "%x" % hash(fp) + return "_nativedeps/" + fingerprint + +def _check_and_get_one_version_attribute(ctx, attr): + value = getattr(semantics.find_java_toolchain(ctx), attr) + return value + +def _jar_and_target_arg_mapper(jar): + # Emit pretty labels for targets in the main repository. + label = str(jar.owner) + if label.startswith("@@//"): + label = label.lstrip("@") + return jar.path + "," + label + +def _get_feature_config(ctx): + cc_toolchain = find_cc_toolchain(ctx, mandatory = False) + if not cc_toolchain: + return None + feature_config = cc_common.configure_features( + ctx = ctx, + cc_toolchain = cc_toolchain, + requested_features = ctx.features + ["java_launcher_link", "static_linking_mode"], + unsupported_features = ctx.disabled_features, + ) + return feature_config + +def _should_strip_as_default(ctx, feature_config): + fission_is_active = ctx.fragments.cpp.fission_active_for_current_compilation_mode() + create_per_obj_debug_info = fission_is_active and cc_common.is_enabled( + feature_name = "per_object_debug_info", + feature_configuration = feature_config, + ) + compilation_mode = ctx.var["COMPILATION_MODE"] + strip_as_default = create_per_obj_debug_info and compilation_mode == "opt" + + return strip_as_default + +def _get_coverage_config(ctx, runner): + toolchain = semantics.find_java_toolchain(ctx) + if not ctx.configuration.coverage_enabled: + return None + runner = runner if ctx.attr.create_executable else None + manifest = ctx.actions.declare_file("runtime_classpath_for_coverage/%s/runtime_classpath.txt" % ctx.label.name) + singlejar = toolchain.single_jar + return struct( + runner = runner, + main_class = "com.google.testing.coverage.JacocoCoverageRunner", + manifest = manifest, + env = { + "JAVA_RUNTIME_CLASSPATH_FOR_COVERAGE": manifest.path, + "SINGLE_JAR_TOOL": singlejar.executable.path, + }, + support_files = [manifest, singlejar.executable], + ) + +def _get_java_executable(ctx, java_runtime_toolchain, launcher): + java_executable = launcher.short_path if launcher else java_runtime_toolchain.java_executable_runfiles_path + if not _is_absolute_target_platform_path(ctx, java_executable): + java_executable = ctx.workspace_name + "/" + java_executable + return paths.normalize(java_executable) + +def _has_target_constraints(ctx, constraints): + # Constraints is a label_list. + for constraint in constraints: + constraint_value = constraint[platform_common.ConstraintValueInfo] + if ctx.target_platform_has_constraint(constraint_value): + return True + return False + +def _is_target_platform_windows(ctx): + return _has_target_constraints(ctx, ctx.attr._windows_constraints) + +def _is_absolute_target_platform_path(ctx, path): + if _is_target_platform_windows(ctx): + return len(path) > 2 and path[1] == ":" + return path.startswith("/") + +def _runfiles_enabled(ctx): + return ctx.configuration.runfiles_enabled() + +def _get_test_support(ctx): + if ctx.attr.create_executable and ctx.attr.use_testrunner: + return ctx.attr._test_support + return None + +def _test_providers(ctx): + test_providers = [] + if _has_target_constraints(ctx, ctx.attr._apple_constraints): + test_providers.append(testing.ExecutionInfo({"requires-darwin": ""})) + + test_env = {} + test_env.update(cc_helper.get_expanded_env(ctx, {})) + + coverage_config = _get_coverage_config( + ctx, + runner = None, # we only need the environment + ) + if coverage_config: + test_env.update(coverage_config.env) + test_providers.append(testing.TestEnvironment( + environment = test_env, + inherited_environment = ctx.attr.env_inherit, + )) + + return test_providers + +def _executable_providers(ctx): + if ctx.attr.create_executable: + return [RunEnvironmentInfo(cc_helper.get_expanded_env(ctx, {}))] + return [] + +def _resource_mapper(file): + root_relative_path = paths.relativize( + path = file.path, + start = paths.join(file.root.path, file.owner.workspace_root), + ) + return "%s:%s" % ( + file.path, + semantics.get_default_resource_path(root_relative_path, segment_extractor = _java_segments), + ) + +def _create_single_jar( + actions, + toolchain, + output, + sources = depset(), + resources = depset(), + mnemonic = "JavaSingleJar", + progress_message = "Building singlejar jar %{output}", + build_target = None, + output_creator = None): + """Register singlejar action for the output jar. + + Args: + actions: (actions) ctx.actions + toolchain: (JavaToolchainInfo) The java toolchain + output: (File) Output file of the action. + sources: (depset[File]) The jar files to merge into the output jar. + resources: (depset[File]) The files to add to the output jar. + mnemonic: (str) The action identifier + progress_message: (str) The action progress message + build_target: (Label) The target label to stamp in the manifest. Optional. + output_creator: (str) The name of the tool to stamp in the manifest. Optional, + defaults to 'singlejar' + Returns: + (File) Output file which was used for registering the action. + """ + args = actions.args() + args.set_param_file_format("shell").use_param_file("@%s", use_always = True) + args.add("--output", output) + args.add_all( + [ + "--compression", + "--normalize", + "--exclude_build_data", + "--warn_duplicate_resources", + ], + ) + args.add_all("--sources", sources) + args.add_all("--resources", resources, map_each = _resource_mapper) + + args.add("--build_target", build_target) + args.add("--output_jar_creator", output_creator) + + actions.run( + mnemonic = mnemonic, + progress_message = progress_message, + executable = toolchain.single_jar, + toolchain = semantics.JAVA_TOOLCHAIN_TYPE, + inputs = depset(transitive = [resources, sources]), + tools = [toolchain.single_jar], + outputs = [output], + arguments = [args], + ) + return output + +# TODO(hvd): use skylib shell.quote() +def _shell_escape(s): + """Shell-escape a string + + Quotes a word so that it can be used, without further quoting, as an argument + (or part of an argument) in a shell command. + + Args: + s: (str) the string to escape + + Returns: + (str) the shell-escaped string + """ + if not s: + # Empty string is a special case: needs to be quoted to ensure that it + # gets treated as a separate argument. + return "''" + for c in s.elems(): + # We do this positively so as to be sure we don't inadvertently forget + # any unsafe characters. + if not c.isalnum() and c not in "@%-_+:,./": + return "'" + s.replace("'", "'\\''") + "'" + return s + +def _tokenize_javacopts(ctx = None, opts = []): + """Tokenizes a list or depset of options to a list. + + Iff opts is a depset, we reverse the flattened list to ensure right-most + duplicates are preserved in their correct position. + + If the ctx parameter is omitted, a slow, but pure Starlark, implementation + of shell tokenization is used. Otherwise, tokenization is performed using + ctx.tokenize() which has significantly better performance (up to 100x for + large options lists). + + Args: + ctx: (RuleContext|None) the rule context + opts: (depset[str]|[str]) the javac options to tokenize + Returns: + [str] list of tokenized options + """ + if hasattr(opts, "to_list"): + opts = reversed(opts.to_list()) + if ctx: + return [ + token + for opt in opts + for token in ctx.tokenize(opt) + ] + else: + return _semantics_tokenize_javacopts(opts) + +def _detokenize_javacopts(opts): + """Detokenizes a list of options to a depset. + + Args: + opts: ([str]) the javac options to detokenize + + Returns: + (depset[str]) depset of detokenized options + """ + return depset( + [" ".join([_shell_escape(opt) for opt in opts])], + order = "preorder", + ) + +def _derive_output_file(ctx, base_file, *, name_suffix = "", extension = None, extension_suffix = ""): + """Declares a new file whose name is derived from the given file + + This method allows appending a suffix to the name (before extension), changing + the extension or appending a suffix after the extension. The new file is declared + as a sibling of the given base file. At least one of the three options must be + specified. It is an error to specify both `extension` and `extension_suffix`. + + Args: + ctx: (RuleContext) the rule context. + base_file: (File) the file from which to derive the resultant file. + name_suffix: (str) Optional. The suffix to append to the name before the + extension. + extension: (str) Optional. The new extension to use (without '.'). By default, + the base_file's extension is used. + extension_suffix: (str) Optional. The suffix to append to the base_file's extension + + Returns: + (File) the derived file + """ + if not name_suffix and not extension_suffix and not extension: + fail("At least one of name_suffix, extension or extension_suffix is required") + if extension and extension_suffix: + fail("only one of extension or extension_suffix can be specified") + if extension == None: + extension = base_file.extension + new_basename = paths.replace_extension(base_file.basename, name_suffix + "." + extension + extension_suffix) + return ctx.actions.declare_file(new_basename, sibling = base_file) + +def _is_stamping_enabled(ctx, stamp): + if ctx.configuration.is_tool_configuration(): + return 0 + if stamp == 1 or stamp == 0: + return stamp + + # stamp == -1 / auto + return int(ctx.configuration.stamp_binaries()) + +helper = struct( + collect_all_targets_as_deps = _collect_all_targets_as_deps, + filter_launcher_for_target = _filter_launcher_for_target, + launcher_artifact_for_target = _launcher_artifact_for_target, + check_and_get_main_class = _check_and_get_main_class, + primary_class = _primary_class, + strip_extension = _strip_extension, + concat = _concat, + get_shared_native_deps_path = _get_shared_native_deps_path, + check_and_get_one_version_attribute = _check_and_get_one_version_attribute, + jar_and_target_arg_mapper = _jar_and_target_arg_mapper, + get_feature_config = _get_feature_config, + should_strip_as_default = _should_strip_as_default, + get_coverage_config = _get_coverage_config, + get_java_executable = _get_java_executable, + is_absolute_target_platform_path = _is_absolute_target_platform_path, + is_target_platform_windows = _is_target_platform_windows, + runfiles_enabled = _runfiles_enabled, + get_test_support = _get_test_support, + test_providers = _test_providers, + executable_providers = _executable_providers, + create_single_jar = _create_single_jar, + shell_escape = _shell_escape, + tokenize_javacopts = _tokenize_javacopts, + detokenize_javacopts = _detokenize_javacopts, + derive_output_file = _derive_output_file, + is_stamping_enabled = _is_stamping_enabled, +) diff --git a/java/common/rules/java_import.bzl b/java/common/rules/java_import.bzl new file mode 100644 index 00000000..7ba8065c --- /dev/null +++ b/java/common/rules/java_import.bzl @@ -0,0 +1,356 @@ +# Copyright 2021 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. + +""" +Definition of java_import rule. +""" + +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_semantics.bzl", "semantics") +load(":basic_java_library.bzl", "construct_defaultinfo") +load(":import_deps_check.bzl", "import_deps_check") +load(":proguard_validation.bzl", "validate_proguard_specs") + +visibility(["//java/..."]) + +_java_common_internal = java_common.internal_DO_NOT_USE() +_run_ijar_private_for_builtins = _java_common_internal.run_ijar_private_for_builtins + +def _filter_provider(provider, *attrs): + return [dep[provider] for attr in attrs for dep in attr if provider in dep] + +def _collect_jars(ctx, jars): + jars_dict = {} + for info in jars: + if JavaInfo in info: + fail("'jars' attribute cannot contain labels of Java targets") + for jar in info.files.to_list(): + jar_path = jar.dirname + jar.basename + if jars_dict.get(jar_path) != None: + fail("in jars attribute of java_import rule //" + ctx.label.package + ":" + ctx.attr.name + ": " + jar.basename + " is a duplicate") + jars_dict[jar_path] = jar + return [jar_tuple[1] for jar_tuple in jars_dict.items()] if len(jars_dict.items()) > 0 else [] + +def _process_with_ijars_if_needed(jars, ctx): + file_dict = {} + use_ijars = ctx.fragments.java.use_ijars() + for jar in jars: + interface_jar = jar + if use_ijars: + ijar_basename = jar.short_path.removeprefix("../").removesuffix("." + jar.extension) + "-ijar.jar" + interface_jar_directory = "_ijar/" + ctx.label.name + "/" + ijar_basename + + interface_jar = ctx.actions.declare_file(interface_jar_directory) + _run_ijar_private_for_builtins( + ctx.actions, + target_label = ctx.label, + jar = jar, + output = interface_jar, + java_toolchain = semantics.find_java_toolchain(ctx), + ) + file_dict[jar] = interface_jar + + return file_dict + +def _check_export_error(ctx, exports): + not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_exports") and not getattr(ctx.attr, "_allowlist_java_import_exports")[PackageSpecificationInfo].contains(ctx.label) + disallow_java_import_exports = ctx.fragments.java.disallow_java_import_exports() + + if len(exports) != 0 and (disallow_java_import_exports or not_in_allowlist): + fail("java_import.exports is no longer supported; use java_import.deps instead") + +def _check_empty_jars_error(ctx, jars): + # TODO(kotlaja): Remove temporary incompatible flag [disallow_java_import_empty_jars] once migration is done. + not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_empty_jars") and not getattr(ctx.attr, "_allowlist_java_import_empty_jars")[PackageSpecificationInfo].contains(ctx.label) + disallow_java_import_empty_jars = ctx.fragments.java.disallow_java_import_empty_jars() + + if len(jars) == 0 and disallow_java_import_empty_jars and not_in_allowlist: + fail("empty java_import.jars is no longer supported " + ctx.label.package) + +def _create_java_info_with_dummy_output_file(ctx, srcjar, all_deps, exports, runtime_deps_list, neverlink, cc_info_list, add_exports, add_opens): + dummy_jar = ctx.actions.declare_file(ctx.label.name + "_dummy.jar") + dummy_src_jar = srcjar + if dummy_src_jar == None: + dummy_src_jar = ctx.actions.declare_file(ctx.label.name + "_src_dummy.java") + ctx.actions.write(dummy_src_jar, "") + return java_common.compile( + ctx, + output = dummy_jar, + java_toolchain = semantics.find_java_toolchain(ctx), + source_files = [dummy_src_jar], + deps = all_deps, + runtime_deps = runtime_deps_list, + neverlink = neverlink, + exports = [export[JavaInfo] for export in exports if JavaInfo in export], # Watchout, maybe you need to add them there manually. + native_libraries = cc_info_list, + add_exports = add_exports, + add_opens = add_opens, + ) + +def bazel_java_import_rule( + ctx, + jars = [], + srcjar = None, + deps = [], + runtime_deps = [], + exports = [], + neverlink = False, + proguard_specs = [], + add_exports = [], + add_opens = []): + """Implements java_import. + + This rule allows the use of precompiled .jar files as libraries in other Java rules. + + Args: + ctx: (RuleContext) Used to register the actions. + jars: (list[Artifact]) List of output jars. + srcjar: (Artifact) The jar containing the sources. + deps: (list[Target]) The list of dependent libraries. + runtime_deps: (list[Target]) Runtime dependencies to attach to the rule. + exports: (list[Target]) The list of exported libraries. + neverlink: (bool) Whether this rule should only be used for compilation and not at runtime. + proguard_specs: (list[File]) Files to be used as Proguard specification. + add_exports: (list[str]) Allow this library to access the given /. + add_opens: (list[str]) Allow this library to reflectively access the given /. + + Returns: + (list[provider]) A list containing DefaultInfo, JavaInfo, + OutputGroupsInfo, ProguardSpecProvider providers. + """ + + _check_empty_jars_error(ctx, jars) + _check_export_error(ctx, exports) + + collected_jars = _collect_jars(ctx, jars) + all_deps = _filter_provider(JavaInfo, deps, exports) + + jdeps_artifact = None + merged_java_info = java_common.merge(all_deps) + not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_deps_checking") and not ctx.attr._allowlist_java_import_deps_checking[PackageSpecificationInfo].contains(ctx.label) + if len(collected_jars) > 0 and not_in_allowlist and "incomplete-deps" not in ctx.attr.tags: + jdeps_artifact = import_deps_check( + ctx, + collected_jars, + merged_java_info.compile_jars, + merged_java_info.transitive_compile_time_jars, + "java_import", + ) + + compilation_to_runtime_jar_map = _process_with_ijars_if_needed(collected_jars, ctx) + runtime_deps_list = [runtime_dep[JavaInfo] for runtime_dep in runtime_deps if JavaInfo in runtime_dep] + cc_info_list = [dep[CcInfo] for dep in deps if CcInfo in dep] + java_info = None + if len(collected_jars) > 0: + java_infos = [] + for jar in collected_jars: + java_infos.append(JavaInfo( + output_jar = jar, + compile_jar = compilation_to_runtime_jar_map[jar], + deps = all_deps, + runtime_deps = runtime_deps_list, + neverlink = neverlink, + source_jar = srcjar, + exports = [export[JavaInfo] for export in exports if JavaInfo in export], # Watchout, maybe you need to add them there manually. + native_libraries = cc_info_list, + add_exports = add_exports, + add_opens = add_opens, + )) + java_info = java_common.merge(java_infos) + else: + # TODO(kotlaja): Remove next line once all java_import targets with empty jars attribute are cleaned from depot (b/246559727). + java_info = _create_java_info_with_dummy_output_file(ctx, srcjar, all_deps, exports, runtime_deps_list, neverlink, cc_info_list, add_exports, add_opens) + + target = {"JavaInfo": java_info} + + target["ProguardSpecProvider"] = validate_proguard_specs( + ctx, + proguard_specs, + [deps, runtime_deps, exports], + ) + + # TODO(kotlaja): Revise if collected_runtimes can be added into construct_defaultinfo directly. + collected_runtimes = [] + for runtime_dep in ctx.attr.runtime_deps: + collected_runtimes.extend(runtime_dep.files.to_list()) + + target["DefaultInfo"] = construct_defaultinfo( + ctx, + collected_jars, + collected_jars + collected_runtimes, + neverlink, + exports, + ) + + output_group_src_jars = depset() if srcjar == None else depset([srcjar]) + target["OutputGroupInfo"] = OutputGroupInfo( + **{ + "_source_jars": output_group_src_jars, + "_direct_source_jars": output_group_src_jars, + "_validation": depset() if jdeps_artifact == None else depset([jdeps_artifact]), + "_hidden_top_level_INTERNAL_": target["ProguardSpecProvider"].specs, + } + ) + return target + +def _proxy(ctx): + return bazel_java_import_rule( + ctx, + ctx.attr.jars, + ctx.file.srcjar, + ctx.attr.deps, + ctx.attr.runtime_deps, + ctx.attr.exports, + ctx.attr.neverlink, + ctx.files.proguard_specs, + ctx.attr.add_exports, + ctx.attr.add_opens, + ).values() + +_ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT = [ + "java_library", + "java_import", + "cc_library", + "cc_binary", +] + +# buildifier: disable=attr-licenses +JAVA_IMPORT_ATTRS = { + "data": attr.label_list( + allow_files = True, + flags = ["SKIP_CONSTRAINTS_OVERRIDE"], + doc = """ +The list of files needed by this rule at runtime. + """, + ), + "deps": attr.label_list( + providers = [JavaInfo], + allow_rules = _ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT, + doc = """ +The list of other libraries to be linked in to the target. +See java_library.deps. + """, + ), + "exports": attr.label_list( + providers = [JavaInfo], + allow_rules = _ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT, + doc = """ +Targets to make available to users of this rule. +See java_library.exports. + """, + ), + "runtime_deps": attr.label_list( + allow_files = [".jar"], + allow_rules = _ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT, + providers = [[CcInfo], [JavaInfo]], + flags = ["SKIP_ANALYSIS_TIME_FILETYPE_CHECK"], + doc = """ +Libraries to make available to the final binary or test at runtime only. +See java_library.runtime_deps. + """, + ), + # JavaImportBazeRule attr + "jars": attr.label_list( + allow_files = [".jar"], + mandatory = True, + doc = """ +The list of JAR files provided to Java targets that depend on this target. + """, + ), + "srcjar": attr.label( + allow_single_file = [".srcjar", ".jar"], + flags = ["DIRECT_COMPILE_TIME_INPUT"], + doc = """ +A JAR file that contains source code for the compiled JAR files. + """, + ), + "neverlink": attr.bool( + default = False, + doc = """ +Only use this library for compilation and not at runtime. +Useful if the library will be provided by the runtime environment +during execution. Examples of libraries like this are IDE APIs +for IDE plug-ins or tools.jar for anything running on +a standard JDK. + """, + ), + "constraints": attr.string_list( + doc = """ +Extra constraints imposed on this rule as a Java library. + """, + ), + # ProguardLibraryRule attr + "proguard_specs": attr.label_list( + allow_files = True, + doc = """ +Files to be used as Proguard specification. +These will describe the set of specifications to be used by Proguard. If specified, +they will be added to any android_binary target depending on this library. + +The files included here must only have idempotent rules, namely -dontnote, -dontwarn, +assumenosideeffects, and rules that start with -keep. Other options can only appear in +android_binary's proguard_specs, to ensure non-tautological merges. + """, + ), + # Additional attrs + "add_exports": attr.string_list( + doc = """ +Allow this library to access the given module or package. +

+This corresponds to the javac and JVM --add-exports= flags. + """, + ), + "add_opens": attr.string_list( + doc = """ +Allow this library to reflectively access the given module or +package. +

+This corresponds to the javac and JVM --add-opens= flags. + """, + ), + "licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), + "_java_toolchain_type": attr.label(default = semantics.JAVA_TOOLCHAIN_TYPE), +} + +java_import = rule( + _proxy, + doc = """ +

+ This rule allows the use of precompiled .jar files as + libraries for java_library and + java_binary rules. +

+ +

Examples

+ +
+
+    java_import(
+        name = "maven_model",
+        jars = [
+            "maven_model/maven-aether-provider-3.2.3.jar",
+            "maven_model/maven-model-3.2.3.jar",
+            "maven_model/maven-model-builder-3.2.3.jar",
+        ],
+    )
+
+
+ """, + attrs = JAVA_IMPORT_ATTRS, + provides = [JavaInfo], + fragments = ["java", "cpp"], + toolchains = [semantics.JAVA_TOOLCHAIN], +) diff --git a/java/common/rules/java_library.bzl b/java/common/rules/java_library.bzl new file mode 100644 index 00000000..1ca788d5 --- /dev/null +++ b/java/common/rules/java_library.bzl @@ -0,0 +1,392 @@ +# Copyright 2021 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. + +""" +Definition of java_library rule. +""" + +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") +load("//java/common:java_semantics.bzl", "semantics") +load(":android_lint.bzl", "android_lint_subrule") +load(":basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS", "basic_java_library", "construct_defaultinfo") +load(":rule_util.bzl", "merge_attrs") + +visibility(["//java/..."]) + +BootClassPathInfo = java_common.BootClassPathInfo + +def bazel_java_library_rule( + ctx, + srcs = [], + deps = [], + runtime_deps = [], + plugins = [], + exports = [], + exported_plugins = [], + resources = [], + javacopts = [], + neverlink = False, + proguard_specs = [], + add_exports = [], + add_opens = [], + bootclasspath = None, + javabuilder_jvm_flags = None): + """Implements java_library. + + Use this call when you need to produce a fully fledged java_library from + another rule's implementation. + + Args: + ctx: (RuleContext) Used to register the actions. + srcs: (list[File]) The list of source files that are processed to create the target. + deps: (list[Target]) The list of other libraries to be linked in to the target. + runtime_deps: (list[Target]) Libraries to make available to the final binary or test at runtime only. + plugins: (list[Target]) Java compiler plugins to run at compile-time. + exports: (list[Target]) Exported libraries. + exported_plugins: (list[Target]) The list of `java_plugin`s (e.g. annotation + processors) to export to libraries that directly depend on this library. + resources: (list[File]) A list of data files to include in a Java jar. + javacopts: (list[str]) Extra compiler options for this library. + neverlink: (bool) Whether this library should only be used for compilation and not at runtime. + proguard_specs: (list[File]) Files to be used as Proguard specification. + add_exports: (list[str]) Allow this library to access the given /. + add_opens: (list[str]) Allow this library to reflectively access the given /. + bootclasspath: (Target) The JDK APIs to compile this library against. + javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. + Returns: + (dict[str, provider]) A list containing DefaultInfo, JavaInfo, + InstrumentedFilesInfo, OutputGroupsInfo, ProguardSpecProvider providers. + """ + if not srcs and deps: + fail("deps not allowed without srcs; move to runtime_deps?") + + target, base_info = basic_java_library( + ctx, + srcs, + deps, + runtime_deps, + plugins, + exports, + exported_plugins, + resources, + [], # resource_jars + [], # class_pathresources + javacopts, + neverlink, + proguard_specs = proguard_specs, + add_exports = add_exports, + add_opens = add_opens, + bootclasspath = bootclasspath, + javabuilder_jvm_flags = javabuilder_jvm_flags, + ) + + target["DefaultInfo"] = construct_defaultinfo( + ctx, + base_info.files_to_build, + base_info.runfiles, + neverlink, + exports, + runtime_deps, + ) + target["OutputGroupInfo"] = OutputGroupInfo(**base_info.output_groups) + + return target + +def _proxy(ctx): + return bazel_java_library_rule( + ctx, + ctx.files.srcs, + ctx.attr.deps, + ctx.attr.runtime_deps, + ctx.attr.plugins, + ctx.attr.exports, + ctx.attr.exported_plugins, + ctx.files.resources, + ctx.attr.javacopts, + ctx.attr.neverlink, + ctx.files.proguard_specs, + ctx.attr.add_exports, + ctx.attr.add_opens, + ctx.attr.bootclasspath, + ctx.attr.javabuilder_jvm_flags, + ).values() + +JAVA_LIBRARY_IMPLICIT_ATTRS = BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS + +JAVA_LIBRARY_ATTRS = merge_attrs( + JAVA_LIBRARY_IMPLICIT_ATTRS, + # buildifier: disable=attr-licenses + { + "srcs": attr.label_list( + allow_files = [".java", ".srcjar", ".properties"] + semantics.EXTRA_SRCS_TYPES, + flags = ["DIRECT_COMPILE_TIME_INPUT", "ORDER_INDEPENDENT"], + doc = """ +The list of source files that are processed to create the target. +This attribute is almost always required; see exceptions below. +

+Source files of type .java are compiled. In case of generated +.java files it is generally advisable to put the generating rule's name +here instead of the name of the file itself. This not only improves readability but +makes the rule more resilient to future changes: if the generating rule generates +different files in the future, you only need to fix one place: the outs of +the generating rule. You should not list the generating rule in deps +because it is a no-op. +

+

+Source files of type .srcjar are unpacked and compiled. (This is useful if +you need to generate a set of .java files with a genrule.) +

+

+Rules: if the rule (typically genrule or filegroup) generates +any of the files listed above, they will be used the same way as described for source +files. +

+

+Source files of type .properties are treated as resources. +

+ +

All other files are ignored, as long as there is at least one file of a +file type described above. Otherwise an error is raised.

+ +

+This argument is almost always required, except if you specify the runtime_deps argument. +

+ """, + ), + "data": attr.label_list( + allow_files = True, + flags = ["SKIP_CONSTRAINTS_OVERRIDE"], + doc = """ +The list of files needed by this library at runtime. +See general comments about data at +Typical attributes defined by +most build rules. +

+ When building a java_library, Bazel doesn't put these files anywhere; if the + data files are generated files then Bazel generates them. When building a + test that depends on this java_library Bazel copies or links the + data files into the runfiles area. +

+ """ + semantics.DOCS.for_attribute("data"), + ), + "resources": attr.label_list( + allow_files = True, + flags = ["SKIP_CONSTRAINTS_OVERRIDE", "ORDER_INDEPENDENT"], + doc = """ +A list of data files to include in a Java jar. +

+Resources may be source files or generated files. +

+ """ + semantics.DOCS.for_attribute("resources"), + ), + "plugins": attr.label_list( + providers = [JavaPluginInfo], + allow_files = True, + cfg = "exec", + doc = """ +Java compiler plugins to run at compile-time. +Every java_plugin specified in this attribute will be run whenever this rule +is built. A library may also inherit plugins from dependencies that use +exported_plugins. Resources +generated by the plugin will be included in the resulting jar of this rule. + """, + ), + "deps": attr.label_list( + allow_files = [".jar"], + allow_rules = semantics.ALLOWED_RULES_IN_DEPS + semantics.ALLOWED_RULES_IN_DEPS_WITH_WARNING, + providers = [ + [CcInfo], + [JavaInfo], + ], + flags = ["SKIP_ANALYSIS_TIME_FILETYPE_CHECK"], + doc = """ +The list of libraries to link into this library. +See general comments about deps at +Typical attributes defined by +most build rules. +

+ The jars built by java_library rules listed in deps will be on + the compile-time classpath of this rule. Furthermore the transitive closure of their + deps, runtime_deps and exports will be on the + runtime classpath. +

+

+ By contrast, targets in the data attribute are included in the runfiles but + on neither the compile-time nor runtime classpath. +

+ """, + ), + "runtime_deps": attr.label_list( + allow_files = [".jar"], + allow_rules = semantics.ALLOWED_RULES_IN_DEPS, + providers = [[CcInfo], [JavaInfo]], + flags = ["SKIP_ANALYSIS_TIME_FILETYPE_CHECK"], + doc = """ +Libraries to make available to the final binary or test at runtime only. +Like ordinary deps, these will appear on the runtime classpath, but unlike +them, not on the compile-time classpath. Dependencies needed only at runtime should be +listed here. Dependency-analysis tools should ignore targets that appear in both +runtime_deps and deps. + """, + ), + "exports": attr.label_list( + allow_rules = semantics.ALLOWED_RULES_IN_DEPS, + providers = [[JavaInfo], [CcInfo]], + doc = """ +Exported libraries. +

+ Listing rules here will make them available to parent rules, as if the parents explicitly + depended on these rules. This is not true for regular (non-exported) deps. +

+

+ Summary: a rule X can access the code in Y if there exists a dependency + path between them that begins with a deps edge followed by zero or more + exports edges. Let's see some examples to illustrate this. +

+

+ Assume A depends on B and B depends on C. In this case + C is a transitive dependency of A, so changing C's sources and rebuilding A will + correctly rebuild everything. However A will not be able to use classes in C. To allow + that, either A has to declare C in its deps, or B can make it easier for A + (and anything that may depend on A) by declaring C in its (B's) exports + attribute. +

+

+ The closure of exported libraries is available to all direct parent rules. Take a slightly + different example: A depends on B, B depends on C and D, and also exports C but not D. + Now A has access to C but not to D. Now, if C and D exported some libraries, C' and D' + respectively, A could only access C' but not D'. +

+

+ Important: an exported rule is not a regular dependency. Sticking to the previous example, + if B exports C and wants to also use C, it has to also list it in its own + deps. +

+ """, + ), + "exported_plugins": attr.label_list( + providers = [JavaPluginInfo], + cfg = "exec", + doc = """ +The list of java_plugins (e.g. annotation +processors) to export to libraries that directly depend on this library. +

+ The specified list of java_plugins will be applied to any library which + directly depends on this library, just as if that library had explicitly declared these + labels in plugins. +

+ """, + ), + "bootclasspath": attr.label( + providers = [BootClassPathInfo], + flags = ["SKIP_CONSTRAINTS_OVERRIDE"], + doc = """Restricted API, do not use!""", + ), + "javabuilder_jvm_flags": attr.string_list(doc = """Restricted API, do not use!"""), + "javacopts": attr.string_list( + doc = """ +Extra compiler options for this library. +Subject to "Make variable" substitution and +Bourne shell tokenization. +

These compiler options are passed to javac after the global compiler options.

+ """, + ), + "neverlink": attr.bool( + doc = """ +Whether this library should only be used for compilation and not at runtime. +Useful if the library will be provided by the runtime environment during execution. Examples +of such libraries are the IDE APIs for IDE plug-ins or tools.jar for anything +running on a standard JDK. +

+ Note that neverlink = 1 does not prevent the compiler from inlining material + from this library into compilation targets that depend on it, as permitted by the Java + Language Specification (e.g., static final constants of String + or of primitive types). The preferred use case is therefore when the runtime library is + identical to the compilation library. +

+

+ If the runtime library differs from the compilation library then you must ensure that it + differs only in places that the JLS forbids compilers to inline (and that must hold for + all future versions of the JLS). +

+ """, + ), + "resource_strip_prefix": attr.string( + doc = """ +The path prefix to strip from Java resources. +

+If specified, this path prefix is stripped from every file in the resources +attribute. It is an error for a resource file not to be under this directory. If not +specified (the default), the path of resource file is determined according to the same +logic as the Java package of source files. For example, a source file at +stuff/java/foo/bar/a.txt will be located at foo/bar/a.txt. +

+ """, + ), + "proguard_specs": attr.label_list( + allow_files = True, + doc = """ +Files to be used as Proguard specification. +These will describe the set of specifications to be used by Proguard. If specified, +they will be added to any android_binary target depending on this library. + +The files included here must only have idempotent rules, namely -dontnote, -dontwarn, +assumenosideeffects, and rules that start with -keep. Other options can only appear in +android_binary's proguard_specs, to ensure non-tautological merges. + """, + ), + "add_exports": attr.string_list( + doc = """ +Allow this library to access the given module or package. +

+This corresponds to the javac and JVM --add-exports= flags. + """, + ), + "add_opens": attr.string_list( + doc = """ +Allow this library to reflectively access the given module or +package. +

+This corresponds to the javac and JVM --add-opens= flags. + """, + ), + "licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), + "_java_toolchain_type": attr.label(default = semantics.JAVA_TOOLCHAIN_TYPE), + }, +) + +java_library = rule( + _proxy, + doc = """ +

This rule compiles and links sources into a .jar file.

+ +

Implicit outputs

+
    +
  • libname.jar: A Java archive containing the class files.
  • +
  • libname-src.jar: An archive containing the sources ("source + jar").
  • +
+ """, + attrs = JAVA_LIBRARY_ATTRS, + provides = [JavaInfo], + outputs = { + "classjar": "lib%{name}.jar", + "sourcejar": "lib%{name}-src.jar", + }, + fragments = ["java", "cpp"], + toolchains = [semantics.JAVA_TOOLCHAIN], + subrules = [android_lint_subrule], +) diff --git a/java/common/rules/java_package_configuration.bzl b/java/common/rules/java_package_configuration.bzl new file mode 100644 index 00000000..32e3abd1 --- /dev/null +++ b/java/common/rules/java_package_configuration.bzl @@ -0,0 +1,115 @@ +# Copyright 2023 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 for the java_package_configuration rule""" + +load("//java/common:java_common.bzl", "java_common") +load(":java_helper.bzl", "helper") + +visibility(["//java/..."]) + +_java_common_internal = java_common.internal_DO_NOT_USE() + +JavaPackageConfigurationInfo = provider( + "A provider for Java per-package configuration", + fields = [ + "data", + "javac_opts", + "matches", + "package_specs", + ], +) + +def _matches(package_specs, label): + for spec in package_specs: + if spec.contains(label): + return True + return False + +def _rule_impl(ctx): + javacopts = _java_common_internal.expand_java_opts(ctx, "javacopts", tokenize = True) + javacopts_depset = helper.detokenize_javacopts(javacopts) + package_specs = [package[PackageSpecificationInfo] for package in ctx.attr.packages] + return [ + DefaultInfo(), + JavaPackageConfigurationInfo( + data = depset(ctx.files.data), + javac_opts = javacopts_depset, + matches = lambda label: _matches(package_specs, label), + package_specs = package_specs, + ), + ] + +java_package_configuration = rule( + implementation = _rule_impl, + doc = """ +

+Configuration to apply to a set of packages. +Configurations can be added to +java_toolchain.javacoptss. +

+ +

Example:

+ +
+
+
+java_package_configuration(
+    name = "my_configuration",
+    packages = [":my_packages"],
+    javacopts = ["-Werror"],
+)
+
+package_group(
+    name = "my_packages",
+    packages = [
+        "//com/my/project/...",
+        "-//com/my/project/testing/...",
+    ],
+)
+
+java_toolchain(
+    ...,
+    package_configuration = [
+        ":my_configuration",
+    ]
+)
+
+
+
+ """, + attrs = { + "packages": attr.label_list( + cfg = "exec", + providers = [PackageSpecificationInfo], + doc = """ +The set of package_groups +the configuration should be applied to. + """, + ), + "javacopts": attr.string_list( + doc = """ +Java compiler flags. + """, + ), + "data": attr.label_list( + allow_files = True, + doc = """ +The list of files needed by this configuration at runtime. + """, + ), + # buildifier: disable=attr-licenses + "output_licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), + }, +) diff --git a/java/common/rules/java_plugin.bzl b/java/common/rules/java_plugin.bzl new file mode 100644 index 00000000..4dbf4e90 --- /dev/null +++ b/java/common/rules/java_plugin.bzl @@ -0,0 +1,185 @@ +# Copyright 2021 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. + +""" +Definition of java_plugin rule. +""" + +load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") +load("//java/common:java_semantics.bzl", "semantics") +load(":android_lint.bzl", "android_lint_subrule") +load(":basic_java_library.bzl", "basic_java_library", "construct_defaultinfo") +load(":java_library.bzl", "JAVA_LIBRARY_ATTRS", "JAVA_LIBRARY_IMPLICIT_ATTRS") +load(":rule_util.bzl", "merge_attrs") + +visibility(["//java/..."]) + +def bazel_java_plugin_rule( + ctx, + srcs = [], + data = [], + generates_api = False, + processor_class = "", + deps = [], + plugins = [], + resources = [], + javacopts = [], + neverlink = False, + proguard_specs = [], + add_exports = [], + add_opens = []): + """Implements java_plugin rule. + + Use this call when you need to produce a fully fledged java_plugin from + another rule's implementation. + + Args: + ctx: (RuleContext) Used to register the actions. + srcs: (list[File]) The list of source files that are processed to create the target. + data: (list[File]) The list of files needed by this plugin at runtime. + generates_api: (bool) This attribute marks annotation processors that generate API code. + processor_class: (str) The processor class is the fully qualified type of + the class that the Java compiler should use as entry point to the annotation processor. + deps: (list[Target]) The list of other libraries to be linked in to the target. + plugins: (list[Target]) Java compiler plugins to run at compile-time. + resources: (list[File]) A list of data files to include in a Java jar. + javacopts: (list[str]) Extra compiler options for this library. + neverlink: (bool) Whether this library should only be used for compilation and not at runtime. + proguard_specs: (list[File]) Files to be used as Proguard specification. + add_exports: (list[str]) Allow this library to access the given /. + add_opens: (list[str]) Allow this library to reflectively access the given /. + Returns: + (list[provider]) A list containing DefaultInfo, JavaInfo, + InstrumentedFilesInfo, OutputGroupsInfo, ProguardSpecProvider providers. + """ + target, base_info = basic_java_library( + ctx, + srcs, + deps, + [], # runtime_deps + plugins, + [], # exports + [], # exported_plugins + resources, + [], # resource_jars + [], # classpath_resources + javacopts, + neverlink, + proguard_specs = proguard_specs, + add_exports = add_exports, + add_opens = add_opens, + ) + java_info = target.pop("JavaInfo") + + # Replace JavaInfo with JavaPluginInfo + target["JavaPluginInfo"] = JavaPluginInfo( + runtime_deps = [java_info], + processor_class = processor_class if processor_class else None, # ignore empty string (default) + data = data, + generates_api = generates_api, + ) + target["DefaultInfo"] = construct_defaultinfo( + ctx, + base_info.files_to_build, + base_info.runfiles, + neverlink, + ) + target["OutputGroupInfo"] = OutputGroupInfo(**base_info.output_groups) + + return target + +def _proxy(ctx): + return bazel_java_plugin_rule( + ctx, + ctx.files.srcs, + ctx.files.data, + ctx.attr.generates_api, + ctx.attr.processor_class, + ctx.attr.deps, + ctx.attr.plugins, + ctx.files.resources, + ctx.attr.javacopts, + ctx.attr.neverlink, + ctx.files.proguard_specs, + ctx.attr.add_exports, + ctx.attr.add_opens, + ).values() + +JAVA_PLUGIN_ATTRS = merge_attrs( + JAVA_LIBRARY_ATTRS, + { + "generates_api": attr.bool(doc = """ +This attribute marks annotation processors that generate API code. +

If a rule uses an API-generating annotation processor, other rules +depending on it can refer to the generated code only if their +compilation actions are scheduled after the generating rule. This +attribute instructs Bazel to introduce scheduling constraints when +--java_header_compilation is enabled. +

WARNING: This attribute affects build +performance, use it only if necessary.

+ """), + "processor_class": attr.string(doc = """ +The processor class is the fully qualified type of the class that the Java compiler should +use as entry point to the annotation processor. If not specified, this rule will not +contribute an annotation processor to the Java compiler's annotation processing, but its +runtime classpath will still be included on the compiler's annotation processor path. (This +is primarily intended for use by +Error Prone plugins, which are loaded +from the annotation processor path using + +java.util.ServiceLoader.) + """), + # buildifier: disable=attr-licenses + "output_licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), + }, + remove_attrs = ["runtime_deps", "exports", "exported_plugins"], +) + +JAVA_PLUGIN_IMPLICIT_ATTRS = JAVA_LIBRARY_IMPLICIT_ATTRS + +java_plugin = rule( + _proxy, + doc = """ +

+ java_plugin defines plugins for the Java compiler run by Bazel. The + only supported kind of plugins are annotation processors. A java_library or + java_binary rule can run plugins by depending on them via the plugins + attribute. A java_library can also automatically export plugins to libraries that + directly depend on it using + exported_plugins. +

+ +

Implicit output targets

+
    +
  • libname.jar: A Java archive.
  • +
+ +

+ Arguments are identical to java_library, except + for the addition of the processor_class argument. +

+ """, + attrs = merge_attrs( + JAVA_PLUGIN_ATTRS, + JAVA_PLUGIN_IMPLICIT_ATTRS, + ), + provides = [JavaPluginInfo], + outputs = { + "classjar": "lib%{name}.jar", + "sourcejar": "lib%{name}-src.jar", + }, + fragments = ["java", "cpp"], + toolchains = [semantics.JAVA_TOOLCHAIN], + subrules = [android_lint_subrule], +) diff --git a/java/common/rules/java_runtime.bzl b/java/common/rules/java_runtime.bzl new file mode 100644 index 00000000..af76f498 --- /dev/null +++ b/java/common/rules/java_runtime.bzl @@ -0,0 +1,260 @@ +# Copyright 2023 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. + +""" +Definition of java_runtime rule and JavaRuntimeInfo provider. +""" + +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") +load("//java/common:java_semantics.bzl", "PLATFORMS_ROOT") +load("//third_party/bazel_skylib/lib:paths.bzl", "paths") +load(":java_helper.bzl", "helper") + +visibility(["//java/..."]) + +ToolchainInfo = platform_common.ToolchainInfo + +def _init_java_runtime_info(**_kwargs): + fail("instantiating JavaRuntimeInfo is a private API") + +JavaRuntimeInfo, _new_javaruntimeinfo = provider( + doc = "Information about the Java runtime used by the java rules.", + fields = { + "default_cds": "Returns the JDK default CDS archive.", + "files": "Returns the files in the Java runtime.", + "hermetic_files": "Returns the files in the Java runtime needed for hermetic deployments.", + "hermetic_static_libs": "Returns the JDK static libraries.", + "java_executable_exec_path": "Returns the execpath of the Java executable.", + "java_executable_runfiles_path": """Returns the path of the Java executable in + runfiles trees. This should only be used when one needs to access the + JVM during the execution of a binary or a test built by Bazel. In particular, + when one needs to invoke the JVM during an action, java_executable_exec_path + should be used instead.""", + "java_home": "Returns the execpath of the root of the Java installation.", + "java_home_runfiles_path": """Returns the path of the Java installation in runfiles trees. + This should only be used when one needs to access the JDK during the execution + of a binary or a test built by Bazel. In particular, when one needs the JDK + during an action, java_home should be used instead.""", + "lib_ct_sym": "Returns the lib/ct.sym file.", + "lib_modules": "Returns the lib/modules file.", + "version": "The Java feature version of the runtime. This is 0 if the version is unknown.", + }, + init = _init_java_runtime_info, +) + +def _is_main_repo(label): + return label.workspace_name == "" + +def _default_java_home(label): + if _is_main_repo(label): + return label.package + else: + return paths.get_relative(label.workspace_root, label.package) + +def _get_bin_java(ctx): + is_windows = helper.is_target_platform_windows(ctx) + return "bin/java.exe" if is_windows else "bin/java" + +def _get_runfiles_java_executable(ctx, java_home, label): + if paths.is_absolute(java_home) or _is_main_repo(label): + return paths.get_relative(java_home, _get_bin_java(ctx)) + else: + repo_runfiles_path = "" if _is_main_repo(label) else paths.get_relative("..", label.workspace_name) + return paths.get_relative(repo_runfiles_path, _get_bin_java(ctx)) + +def _is_java_binary(path): + return path.endswith("bin/java") or path.endswith("bin/java.exe") + +def _get_lib_ct_sym(srcs, explicit_lib_ct_sym): + if explicit_lib_ct_sym: + return explicit_lib_ct_sym + candidates = [src for src in srcs if src.path.endswith("/lib/ct.sym")] + if len(candidates) == 1: + return candidates[0] + else: + return None + +def _java_runtime_rule_impl(ctx): + all_files = [] # [depset[File]] + all_files.append(depset(ctx.files.srcs)) + + java_home = _default_java_home(ctx.label) + if ctx.attr.java_home: + java_home_attr = ctx.expand_make_variables("java_home", ctx.attr.java_home, {}) + if ctx.files.srcs and paths.is_absolute(java_home_attr): + fail("'java_home' with an absolute path requires 'srcs' to be empty.") + java_home = paths.get_relative(java_home, java_home_attr) + + java_binary_exec_path = paths.get_relative(java_home, _get_bin_java(ctx)) + java_binary_runfiles_path = _get_runfiles_java_executable(ctx, java_home, ctx.label) + + java = ctx.file.java + if java: + if paths.is_absolute(java_home): + fail("'java_home' with an absolute path requires 'java' to be empty.") + java_binary_exec_path = java.path + java_binary_runfiles_path = java.short_path + if not _is_java_binary(java_binary_exec_path): + fail("the path to 'java' must end in 'bin/java'.") + java_home = paths.dirname(paths.dirname(java_binary_exec_path)) + all_files.append(depset([java])) + + java_home_runfiles_path = paths.dirname(paths.dirname(java_binary_runfiles_path)) + + hermetic_inputs = depset(ctx.files.hermetic_srcs) + all_files.append(hermetic_inputs) + + lib_ct_sym = _get_lib_ct_sym(ctx.files.srcs, ctx.file.lib_ct_sym) + lib_modules = ctx.file.lib_modules + hermetic_static_libs = [dep[CcInfo] for dep in ctx.attr.hermetic_static_libs] + + # If a runtime does not set default_cds in hermetic mode, it is not fatal. + # We can skip the default CDS in the check below. + default_cds = ctx.file.default_cds + + if (hermetic_inputs or lib_modules or hermetic_static_libs) and ( + not hermetic_inputs or not lib_modules or not hermetic_static_libs + ): + fail("hermetic specified, all of java_runtime.lib_modules, java_runtime.hermetic_srcs and java_runtime.hermetic_static_libs must be specified") + + files = depset(transitive = all_files) + + java_runtime_info = _new_javaruntimeinfo( + default_cds = default_cds, + files = files, + hermetic_files = hermetic_inputs, + hermetic_static_libs = hermetic_static_libs, + java_executable_exec_path = java_binary_exec_path, + java_executable_runfiles_path = java_binary_runfiles_path, + java_home = java_home, + java_home_runfiles_path = java_home_runfiles_path, + lib_ct_sym = lib_ct_sym, + lib_modules = lib_modules, + version = ctx.attr.version, + ) + return [ + DefaultInfo( + files = files, + runfiles = ctx.runfiles(transitive_files = files), + ), + java_runtime_info, + platform_common.TemplateVariableInfo({ + "JAVA": java_binary_exec_path, + "JAVABASE": java_home, + }), + ToolchainInfo(java_runtime = java_runtime_info), + ] + +java_runtime = rule( + implementation = _java_runtime_rule_impl, + doc = """ +

+Specifies the configuration for a Java runtime. +

+ +

Example:

+ +
+
+
+java_runtime(
+    name = "jdk-9-ea+153",
+    srcs = glob(["jdk9-ea+153/**"]),
+    java_home = "jdk9-ea+153",
+)
+
+
+
+ """, + attrs = { + "default_cds": attr.label( + allow_single_file = True, + executable = True, + cfg = "target", + doc = """ +Default CDS archive for hermetic java_runtime. When hermetic +is enabled for a java_binary target and if the target does not +provide its own CDS archive by specifying the +classlist attribute, +the java_runtime default CDS is packaged in the hermetic deploy JAR. + """, + ), + "hermetic_srcs": attr.label_list( + allow_files = True, + doc = """ +Files in the runtime needed for hermetic deployments. + """, + ), + "hermetic_static_libs": attr.label_list( + providers = [CcInfo], + doc = """ +The libraries that are statically linked with the launcher for hermetic deployments + """, + ), + "java": attr.label( + allow_single_file = True, + executable = True, + cfg = "target", + doc = """ +The path to the java executable. + """, + ), + "java_home": attr.string( + doc = """ +The path to the root of the runtime. +Subject to "Make" variable substitution. +If this path is absolute, the rule denotes a non-hermetic Java runtime with a well-known +path. In that case, the srcs and java attributes must be empty. + """, + ), + "lib_ct_sym": attr.label( + allow_single_file = True, + doc = """ +The lib/ct.sym file needed for compilation with --release. If not specified and +there is exactly one file in srcs whose path ends with +/lib/ct.sym, that file is used. + """, + ), + "lib_modules": attr.label( + allow_single_file = True, + executable = True, + cfg = "target", + doc = """ +The lib/modules file needed for hermetic deployments. + """, + ), + "srcs": attr.label_list( + allow_files = True, + doc = """ +All files in the runtime. + """, + ), + "version": attr.int( + doc = """ +The feature version of the Java runtime. I.e., the integer returned by +Runtime.version().feature(). + """, + ), + # buildifier: disable=attr-licenses + "output_licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), + "_windows_constraints": attr.label_list( + default = [paths.join(PLATFORMS_ROOT, "os:windows")], + ), + }, + fragments = ["java"], + provides = [ + JavaRuntimeInfo, + platform_common.TemplateVariableInfo, + ], +) diff --git a/java/common/rules/java_toolchain.bzl b/java/common/rules/java_toolchain.bzl new file mode 100644 index 00000000..8e0f5837 --- /dev/null +++ b/java/common/rules/java_toolchain.bzl @@ -0,0 +1,604 @@ +# Copyright 2023 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. + +""" +Definition of java_toolchain rule and JavaToolchainInfo provider. +""" + +load("//java/common:java_semantics.bzl", "semantics") +load(":java_helper.bzl", "helper") +load(":java_package_configuration.bzl", "JavaPackageConfigurationInfo") +load(":java_runtime.bzl", "JavaRuntimeInfo") + +visibility(["//java/..."]) + +_java_common_internal = java_common.internal_DO_NOT_USE() +ToolchainInfo = platform_common.ToolchainInfo +BootClassPathInfo = java_common.BootClassPathInfo +JavaPluginDataInfo = _java_common_internal.JavaPluginDataInfo + +def _java_toolchain_info_init(**_kwargs): + fail("JavaToolchainInfo instantiation is a private API") + +_PRIVATE_API_DOC_STRING = "internal API, DO NOT USE!" + +JavaToolchainInfo, _new_javatoolchaininfo = provider( + doc = "Information about the JDK used by the java_* rules.", + fields = { + "bootclasspath": "(depset[File]) The Java target bootclasspath entries. Corresponds to javac's -bootclasspath flag.", + "ijar": "(FilesToRunProvider) The ijar executable.", + "jacocorunner": "(FilesToRunProvider) The jacocorunner used by the toolchain.", + "java_runtime": "(JavaRuntimeInfo) The java runtime information.", + "jvm_opt": "(depset[str]) The default options for the JVM running the java compiler and associated tools.", + "label": "(label) The toolchain label.", + "proguard_allowlister": "(FilesToRunProvider) The binary to validate proguard configuration.", + "single_jar": "(FilesToRunProvider) The SingleJar deploy jar.", + "source_version": "(str) The java source version.", + "target_version": "(str) The java target version.", + "tools": "(depset[File]) The compilation tools.", + # private + "_android_linter": _PRIVATE_API_DOC_STRING, + "_bootclasspath_info": _PRIVATE_API_DOC_STRING, + "_bytecode_optimizer": _PRIVATE_API_DOC_STRING, + "_compatible_javacopts": _PRIVATE_API_DOC_STRING, + "_deps_checker": _PRIVATE_API_DOC_STRING, + "_forcibly_disable_header_compilation": _PRIVATE_API_DOC_STRING, + "_gen_class": _PRIVATE_API_DOC_STRING, + "_header_compiler": _PRIVATE_API_DOC_STRING, + "_header_compiler_builtin_processors": _PRIVATE_API_DOC_STRING, + "_header_compiler_direct": _PRIVATE_API_DOC_STRING, + "_javabuilder": _PRIVATE_API_DOC_STRING, + "_javacopts": _PRIVATE_API_DOC_STRING, + "_javacopts_list": _PRIVATE_API_DOC_STRING, + "_javac_supports_workers": _PRIVATE_API_DOC_STRING, + "_javac_supports_multiplex_workers": _PRIVATE_API_DOC_STRING, + "_javac_supports_worker_cancellation": _PRIVATE_API_DOC_STRING, + "_javac_supports_worker_multiplex_sandboxing": _PRIVATE_API_DOC_STRING, + "_jspecify_info": _PRIVATE_API_DOC_STRING, + "_local_java_optimization_config": _PRIVATE_API_DOC_STRING, + "_one_version_tool": _PRIVATE_API_DOC_STRING, + "_one_version_allowlist": _PRIVATE_API_DOC_STRING, + "_one_version_allowlist_for_tests": _PRIVATE_API_DOC_STRING, + "_package_configuration": _PRIVATE_API_DOC_STRING, + "_reduced_classpath_incompatible_processors": _PRIVATE_API_DOC_STRING, + "_timezone_data": _PRIVATE_API_DOC_STRING, + }, + init = _java_toolchain_info_init, +) + +def _java_toolchain_impl(ctx): + javac_opts_list = _get_javac_opts(ctx) + bootclasspath_info = _get_bootclasspath_info(ctx) + java_runtime = _get_java_runtime(ctx) + if java_runtime and java_runtime.lib_ct_sym: + header_compiler_direct_data = [java_runtime.lib_ct_sym] + header_compiler_direct_jvm_opts = ["-Dturbine.ctSymPath=" + java_runtime.lib_ct_sym.path] + elif java_runtime and java_runtime.java_home: + # Turbine finds ct.sym relative to java.home. + header_compiler_direct_data = [] + header_compiler_direct_jvm_opts = ["-Djava.home=" + java_runtime.java_home] + else: + header_compiler_direct_data = [] + header_compiler_direct_jvm_opts = [] + java_toolchain_info = _new_javatoolchaininfo( + bootclasspath = bootclasspath_info.bootclasspath, + ijar = ctx.attr.ijar.files_to_run if ctx.attr.ijar else None, + jacocorunner = ctx.attr.jacocorunner.files_to_run if ctx.attr.jacocorunner else None, + java_runtime = java_runtime, + jvm_opt = depset(_java_common_internal.expand_java_opts(ctx, "jvm_opts", tokenize = False, exec_paths = True)), + label = ctx.label, + proguard_allowlister = ctx.attr.proguard_allowlister.files_to_run if ctx.attr.proguard_allowlister else None, + single_jar = ctx.attr.singlejar.files_to_run, + source_version = ctx.attr.source_version, + target_version = ctx.attr.target_version, + tools = depset(ctx.files.tools), + # private + _android_linter = _get_android_lint_tool(ctx), + _bootclasspath_info = bootclasspath_info, + _bytecode_optimizer = _get_tool_from_executable(ctx, "_bytecode_optimizer"), + _compatible_javacopts = _get_compatible_javacopts(ctx), + _deps_checker = ctx.file.deps_checker, + _forcibly_disable_header_compilation = ctx.attr.forcibly_disable_header_compilation, + _gen_class = ctx.file.genclass, + _header_compiler = _get_tool_from_ctx(ctx, "header_compiler", "turbine_data", "turbine_jvm_opts"), + _header_compiler_builtin_processors = depset(ctx.attr.header_compiler_builtin_processors), + _header_compiler_direct = _get_tool_from_executable( + ctx, + "header_compiler_direct", + data = header_compiler_direct_data, + jvm_opts = header_compiler_direct_jvm_opts, + ), + _javabuilder = _get_tool_from_ctx(ctx, "javabuilder", "javabuilder_data", "javabuilder_jvm_opts"), + _javacopts = helper.detokenize_javacopts(javac_opts_list), + _javacopts_list = javac_opts_list, + _javac_supports_workers = ctx.attr.javac_supports_workers, + _javac_supports_multiplex_workers = ctx.attr.javac_supports_multiplex_workers, + _javac_supports_worker_cancellation = ctx.attr.javac_supports_worker_cancellation, + _javac_supports_worker_multiplex_sandboxing = ctx.attr.javac_supports_worker_multiplex_sandboxing, + _jspecify_info = _get_jspecify_info(ctx), + _local_java_optimization_config = ctx.files._local_java_optimization_configuration, + _one_version_tool = ctx.attr.oneversion.files_to_run if ctx.attr.oneversion else None, + _one_version_allowlist = ctx.file.oneversion_whitelist, + _one_version_allowlist_for_tests = ctx.file.oneversion_allowlist_for_tests, + _package_configuration = [dep[JavaPackageConfigurationInfo] for dep in ctx.attr.package_configuration], + _reduced_classpath_incompatible_processors = depset(ctx.attr.reduced_classpath_incompatible_processors, order = "preorder"), + _timezone_data = ctx.file.timezone_data, + ) + toolchain_info = ToolchainInfo(java = java_toolchain_info) + return [java_toolchain_info, toolchain_info, DefaultInfo()] + +def _get_bootclasspath_info(ctx): + bootclasspath_infos = [dep[BootClassPathInfo] for dep in ctx.attr.bootclasspath if BootClassPathInfo in dep] + if bootclasspath_infos: + if len(bootclasspath_infos) != 1: + fail("in attribute 'bootclasspath': expected exactly one entry with a BootClassPathInfo provider") + else: + return bootclasspath_infos[0] + else: + return BootClassPathInfo(bootclasspath = ctx.files.bootclasspath) + +def _get_java_runtime(ctx): + if not ctx.attr.java_runtime: + return None + return ctx.attr.java_runtime[ToolchainInfo].java_runtime + +def _get_javac_opts(ctx): + opts = [] + if ctx.attr.source_version: + opts.extend(["-source", ctx.attr.source_version]) + if ctx.attr.target_version: + opts.extend(["-target", ctx.attr.target_version]) + if ctx.attr.xlint: + opts.append("-Xlint:" + ",".join(ctx.attr.xlint)) + opts.extend(_java_common_internal.expand_java_opts(ctx, "misc", tokenize = True)) + opts.extend(_java_common_internal.expand_java_opts(ctx, "javacopts", tokenize = True)) + return opts + +def _get_android_lint_tool(ctx): + if not ctx.attr.android_lint_runner: + return None + files_to_run = ctx.attr.android_lint_runner.files_to_run + if not files_to_run or not files_to_run.executable: + fail(ctx.attr.android_lint_runner.label, "does not refer to a valid executable target") + return struct( + tool = files_to_run, + data = depset(ctx.files.android_lint_data), + jvm_opts = depset([ctx.expand_location(opt, ctx.attr.android_lint_data) for opt in ctx.attr.android_lint_jvm_opts]), + lint_opts = [ctx.expand_location(opt, ctx.attr.android_lint_data) for opt in ctx.attr.android_lint_opts], + package_config = [dep[JavaPackageConfigurationInfo] for dep in ctx.attr.android_lint_package_configuration], + ) + +def _get_tool_from_ctx(ctx, tool_attr, data_attr, opts_attr): + dep = getattr(ctx.attr, tool_attr) + if not dep: + return None + files_to_run = dep.files_to_run + if not files_to_run or not files_to_run.executable: + fail(dep.label, "does not refer to a valid executable target") + data = getattr(ctx.attr, data_attr) + return struct( + tool = files_to_run, + data = depset(getattr(ctx.files, data_attr)), + jvm_opts = depset([ctx.expand_location(opt, data) for opt in getattr(ctx.attr, opts_attr)]), + ) + +def _get_tool_from_executable(ctx, attr_name, data = [], jvm_opts = []): + dep = getattr(ctx.attr, attr_name) + if not dep: + return None + files_to_run = dep.files_to_run + if not files_to_run or not files_to_run.executable: + fail(dep.label, "does not refer to a valid executable target") + return struct(tool = files_to_run, data = depset(data), jvm_opts = depset(jvm_opts)) + +def _get_compatible_javacopts(ctx): + result = {} + for key, opt_list in ctx.attr.compatible_javacopts.items(): + result[key] = helper.detokenize_javacopts([token for opt in opt_list for token in ctx.tokenize(opt)]) + return result + +def _get_jspecify_info(ctx): + if not ctx.attr.jspecify_processor_class: + return None + stubs = ctx.files.jspecify_stubs + javacopts = [] + javacopts.extend(ctx.attr.jspecify_javacopts) + if stubs: + javacopts.append("-Astubs=" + ":".join([file.path for file in stubs])) + return struct( + processor = JavaPluginDataInfo( + processor_classes = depset([ctx.attr.jspecify_processor_class]), + processor_jars = depset([ctx.file.jspecify_processor]), + processor_data = depset(stubs), + ), + implicit_deps = depset([ctx.file.jspecify_implicit_deps]), + javacopts = javacopts, + packages = [target[PackageSpecificationInfo] for target in ctx.attr.jspecify_packages], + ) + +def _extract_singleton_list_value(dict, key): + if key in dict and type(dict[key]) == type([]): + list = dict[key] + if len(list) > 1: + fail("expected a single value for:", key, "got: ", list) + elif len(list) == 1: + dict[key] = dict[key][0] + else: + dict[key] = None + +_LEGACY_ANY_TYPE_ATTRS = [ + "genclass", + "deps_checker", + "header_compiler", + "header_compiler_direct", + "ijar", + "javabuilder", + "singlejar", +] + +def _java_toolchain_initializer(**kwargs): + # these attributes are defined as executable `label_list`s in native but are + # expected to be singleton values. Since this is not supported in Starlark, + # we just inline the value from the list (if present) before invoking the + # rule. + for attr in _LEGACY_ANY_TYPE_ATTRS: + _extract_singleton_list_value(kwargs, attr) + + return kwargs + +java_toolchain = rule( + implementation = _java_toolchain_impl, + initializer = _java_toolchain_initializer, + doc = """ +

+Specifies the configuration for the Java compiler. Which toolchain to be used can be changed through +the --java_toolchain argument. Normally you should not write those kind of rules unless you want to +tune your Java compiler. +

+ +

Examples

+ +

A simple example would be: +

+ +
+
+
+java_toolchain(
+    name = "toolchain",
+    source_version = "7",
+    target_version = "7",
+    bootclasspath = ["//tools/jdk:bootclasspath"],
+    xlint = [ "classfile", "divzero", "empty", "options", "path" ],
+    javacopts = [ "-g" ],
+    javabuilder = ":JavaBuilder_deploy.jar",
+)
+
+
+ """, + # buildifier: disable=attr-licenses + attrs = { + "android_lint_data": attr.label_list( + cfg = "exec", + allow_files = True, + doc = """ +Labels of tools available for label-expansion in android_lint_jvm_opts. + """, + ), + "android_lint_opts": attr.string_list( + default = [], + doc = """ +The list of Android Lint arguments. + """, + ), + "android_lint_jvm_opts": attr.string_list( + default = [], + doc = """ +The list of arguments for the JVM when invoking Android Lint. + """, + ), + "android_lint_package_configuration": attr.label_list( + cfg = "exec", + providers = [JavaPackageConfigurationInfo], + allow_files = True, + doc = """ +Android Lint Configuration that should be applied to the specified package groups. + """, + ), + "android_lint_runner": attr.label( + cfg = "exec", + executable = True, + allow_single_file = True, + doc = """ +Label of the Android Lint runner, if any. + """, + ), + "bootclasspath": attr.label_list( + default = [], + allow_files = True, + doc = """ +The Java target bootclasspath entries. Corresponds to javac's -bootclasspath flag. + """, + ), + "compatible_javacopts": attr.string_list_dict( + doc = """Internal API, do not use!""", + ), + "deps_checker": attr.label( + allow_single_file = True, + cfg = "exec", + executable = True, + doc = """ +Label of the ImportDepsChecker deploy jar. + """, + ), + "forcibly_disable_header_compilation": attr.bool( + default = False, + doc = """ +Overrides --java_header_compilation to disable header compilation on platforms that do not +support it, e.g. JDK 7 Bazel. + """, + ), + "genclass": attr.label( + allow_single_file = True, + cfg = "exec", + executable = True, + doc = """ +Label of the GenClass deploy jar. + """, + ), + "header_compiler": attr.label( + allow_single_file = True, + cfg = "exec", + executable = True, + doc = """ +Label of the header compiler. Required if --java_header_compilation is enabled. + """, + ), + "header_compiler_direct": attr.label( + allow_single_file = True, + cfg = "exec", + executable = True, + doc = """ +Optional label of the header compiler to use for direct classpath actions that do not +include any API-generating annotation processors. + +

This tool does not support annotation processing. + """, + ), + "header_compiler_builtin_processors": attr.string_list( + doc = """Internal API, do not use!""", + ), + "ijar": attr.label( + cfg = "exec", + allow_files = True, + executable = True, + doc = """ +Label of the ijar executable. + """, + ), + "jacocorunner": attr.label( + cfg = "exec", + allow_single_file = True, + executable = True, + doc = """ +Label of the JacocoCoverageRunner deploy jar. + """, + ), + "javabuilder": attr.label( + cfg = "exec", + allow_single_file = True, + executable = True, + doc = """ +Label of the JavaBuilder deploy jar. + """, + ), + "javabuilder_data": attr.label_list( + cfg = "exec", + allow_files = True, + doc = """ +Labels of data available for label-expansion in javabuilder_jvm_opts. + """, + ), + "javabuilder_jvm_opts": attr.string_list( + doc = """ +The list of arguments for the JVM when invoking JavaBuilder. + """, + ), + "java_runtime": attr.label( + cfg = "exec", + providers = [JavaRuntimeInfo], + doc = """ +The java_runtime to use with this toolchain. It defaults to java_runtime +in execution configuration. + """, + ), + "javac_supports_workers": attr.bool( + default = True, + doc = """ +True if JavaBuilder supports running as a persistent worker, false if it doesn't. + """, + ), + "javac_supports_multiplex_workers": attr.bool( + default = True, + doc = """ +True if JavaBuilder supports running as a multiplex persistent worker, false if it doesn't. + """, + ), + "javac_supports_worker_cancellation": attr.bool( + default = True, + doc = """ +True if JavaBuilder supports cancellation of persistent workers, false if it doesn't. + """, + ), + "javac_supports_worker_multiplex_sandboxing": attr.bool( + default = False, + doc = """ +True if JavaBuilder supports running as a multiplex persistent worker with sandboxing, false if it doesn't. + """, + ), + "javacopts": attr.string_list( + default = [], + doc = """ +The list of extra arguments for the Java compiler. Please refer to the Java compiler +documentation for the extensive list of possible Java compiler flags. + """, + ), + "jspecify_implicit_deps": attr.label( + cfg = "exec", + allow_single_file = True, + executable = True, + doc = """Experimental, do not use!""", + ), + "jspecify_javacopts": attr.string_list( + doc = """Experimental, do not use!""", + ), + "jspecify_packages": attr.label_list( + cfg = "exec", + allow_files = True, + providers = [PackageSpecificationInfo], + doc = """Experimental, do not use!""", + ), + "jspecify_processor": attr.label( + cfg = "exec", + allow_single_file = True, + executable = True, + doc = """Experimental, do not use!""", + ), + "jspecify_processor_class": attr.string( + doc = """Experimental, do not use!""", + ), + "jspecify_stubs": attr.label_list( + cfg = "exec", + allow_files = True, + doc = """Experimental, do not use!""", + ), + "jvm_opts": attr.string_list( + default = [], + doc = """ +The list of arguments for the JVM when invoking the Java compiler. Please refer to the Java +virtual machine documentation for the extensive list of possible flags for this option. + """, + ), + "misc": attr.string_list( + default = [], + doc = """Deprecated: use javacopts instead""", + ), + "oneversion": attr.label( + cfg = "exec", + allow_files = True, + executable = True, + doc = """ +Label of the one-version enforcement binary. + """, + ), + "oneversion_whitelist": attr.label( + allow_single_file = True, + doc = """ +Label of the one-version allowlist. + """, + ), + "oneversion_allowlist_for_tests": attr.label( + allow_single_file = True, + doc = """ +Label of the one-version allowlist for tests. + """, + ), + "package_configuration": attr.label_list( + cfg = "exec", + providers = [JavaPackageConfigurationInfo], + doc = """ +Configuration that should be applied to the specified package groups. + """, + ), + "proguard_allowlister": attr.label( + cfg = "exec", + executable = True, + allow_files = True, + default = semantics.PROGUARD_ALLOWLISTER_LABEL, + doc = """ +Label of the Proguard allowlister. + """, + ), + "reduced_classpath_incompatible_processors": attr.string_list( + doc = """Internal API, do not use!""", + ), + "singlejar": attr.label( + cfg = "exec", + allow_files = True, + executable = True, + doc = """ +Label of the SingleJar deploy jar. + """, + ), + "source_version": attr.string( + doc = """ +The Java source version (e.g., '6' or '7'). It specifies which set of code structures +are allowed in the Java source code. + """, + ), + "target_version": attr.string( + doc = """ +The Java target version (e.g., '6' or '7'). It specifies for which Java runtime the class +should be build. + """, + ), + "timezone_data": attr.label( + cfg = "exec", + allow_single_file = True, + doc = """ +Label of a resource jar containing timezone data. If set, the timezone data is added as an +implicitly runtime dependency of all java_binary rules. + """, + ), + "tools": attr.label_list( + cfg = "exec", + allow_files = True, + doc = """ +Labels of tools available for label-expansion in jvm_opts. + """, + ), + "turbine_data": attr.label_list( + cfg = "exec", + allow_files = True, + doc = """ +Labels of data available for label-expansion in turbine_jvm_opts. + """, + ), + "turbine_jvm_opts": attr.string_list( + doc = """ +The list of arguments for the JVM when invoking turbine. + """, + ), + "xlint": attr.string_list( + default = [], + doc = """ +The list of warning to add or removes from default list. Precedes it with a dash to +removes it. Please see the Javac documentation on the -Xlint options for more information. + """, + ), + "licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), + "_bytecode_optimizer": attr.label( + cfg = "exec", + executable = True, + default = configuration_field(fragment = "java", name = "java_toolchain_bytecode_optimizer"), + ), + "_local_java_optimization_configuration": attr.label( + cfg = "exec", + default = configuration_field(fragment = "java", name = "local_java_optimization_configuration"), + allow_files = True, + ), + "_legacy_any_type_attrs": attr.string_list(default = _LEGACY_ANY_TYPE_ATTRS), + }, + fragments = ["java"], +) diff --git a/java/common/rules/proguard_validation.bzl b/java/common/rules/proguard_validation.bzl new file mode 100644 index 00000000..18142b35 --- /dev/null +++ b/java/common/rules/proguard_validation.bzl @@ -0,0 +1,71 @@ +# Copyright 2021 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. + +""" +Proguard +""" + +load("//java/common:java_semantics.bzl", "semantics") +load("//java/common:proguard_spec_info.bzl", "ProguardSpecInfo") + +visibility("private") + +def _filter_provider(provider, *attrs): + return [dep[provider] for attr in attrs for dep in attr if provider in dep] + +def _validate_spec(ctx, spec_file): + validated_proguard_spec = ctx.actions.declare_file( + "validated_proguard/%s/%s_valid" % (ctx.label.name, spec_file.path), + ) + + toolchain = semantics.find_java_toolchain(ctx) + + args = ctx.actions.args() + args.add("--path", spec_file) + args.add("--output", validated_proguard_spec) + + ctx.actions.run( + mnemonic = "ValidateProguard", + progress_message = "Validating proguard configuration %{input}", + executable = toolchain.proguard_allowlister, + arguments = [args], + inputs = [spec_file], + outputs = [validated_proguard_spec], + toolchain = Label(semantics.JAVA_TOOLCHAIN_TYPE), + ) + + return validated_proguard_spec + +def validate_proguard_specs(ctx, proguard_specs = [], transitive_attrs = []): + """ + Creates actions that validate Proguard specification and returns ProguardSpecProvider. + + Use transtive_attrs parameter to collect Proguard validations from `deps`, + `runtime_deps`, `exports`, `plugins`, and `exported_plugins` attributes. + + Args: + ctx: (RuleContext) Used to register the actions. + proguard_specs: (list[File]) List of Proguard specs files. + transitive_attrs: (list[list[Target]]) Attributes to collect transitive + proguard validations from. + Returns: + (ProguardSpecProvider) A ProguardSpecProvider. + """ + proguard_validations = _filter_provider(ProguardSpecInfo, *transitive_attrs) + return ProguardSpecInfo( + depset( + [_validate_spec(ctx, spec_file) for spec_file in proguard_specs], + transitive = [validation.specs for validation in proguard_validations], + ), + ) diff --git a/java/common/rules/rule_util.bzl b/java/common/rules/rule_util.bzl new file mode 100644 index 00000000..2b1423af --- /dev/null +++ b/java/common/rules/rule_util.bzl @@ -0,0 +1,50 @@ +# Copyright 2021 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. +"""Defines rule utilities.""" + +visibility(["//java/..."]) + +def merge_attrs(*attribute_dicts, override_attrs = {}, remove_attrs = []): + """Merges attributes together. + + Attributes are first merged, then overridden and removed. + + If there are duplicate definitions of an attribute, the last one is used. + (Current API doesn't let us compare) + + Overridden and removed attributes need to be present. + + Args: + *attribute_dicts: (*dict[str,Attribute]) A list of attribute dictionaries + to merge together. + override_attrs: (dict[str,Attribute]) A dictionary of attributes to override + remove_attrs: (list[str]) A list of attributes to remove. + Returns: + (dict[str,Attribute]) The merged attributes dictionary. + """ + all_attributes = {} + for attribute_dict in attribute_dicts: + for key, attr in attribute_dict.items(): + all_attributes.setdefault(key, attr) + for key, attr in override_attrs.items(): + if all_attributes.get(key) == None: + fail("Trying to override attribute %s where there is none." % key) + all_attributes[key] = attr + for key in remove_attrs: + if key in override_attrs: + fail("Trying to remove overridden attribute %s." % key) + if key not in all_attributes: + fail("Trying to remove non-existent attribute %s." % key) + all_attributes.pop(key) + return all_attributes From 54fde1126cb45911d34d0b8a28ba88e694f6cc5e Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Sep 2024 06:03:28 -0700 Subject: [PATCH 019/465] Fix `load()` paths for `@bazel_skylib` PiperOrigin-RevId: 672931686 Change-Id: If498e5ca04d0fd203e9ce7565835315965bb87a4 --- java/bazel/rules/bazel_java_binary.bzl | 2 +- java/common/rules/java_binary.bzl | 2 +- java/common/rules/java_helper.bzl | 2 +- java/common/rules/java_runtime.bzl | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl index 9317cc29..87f36e51 100644 --- a/java/bazel/rules/bazel_java_binary.bzl +++ b/java/bazel/rules/bazel_java_binary.bzl @@ -13,6 +13,7 @@ # limitations under the License. """Bazel java_binary rule""" +load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc:find_cc_toolchain.bzl", "use_cc_toolchain") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") @@ -24,7 +25,6 @@ load("//java/common/rules:java_binary.bzl", "BASE_TEST_ATTRIBUTES", "BASIC_JAVA_ load("//java/common/rules:java_binary_deploy_jar.bzl", "create_deploy_archives") load("//java/common/rules:java_helper.bzl", "helper") load("//java/common/rules:rule_util.bzl", "merge_attrs") -load("//third_party/bazel_skylib/lib:paths.bzl", "paths") visibility("private") diff --git a/java/common/rules/java_binary.bzl b/java/common/rules/java_binary.bzl index 74a5ab9a..79d6ff5d 100644 --- a/java/common/rules/java_binary.bzl +++ b/java/common/rules/java_binary.bzl @@ -14,13 +14,13 @@ """ Implementation of java_binary for bazel """ +load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/common:java_semantics.bzl", "PLATFORMS_ROOT", "semantics") -load("//third_party/bazel_skylib/lib:paths.bzl", "paths") load("//third_party/protobuf/bazel/common:proto_info.bzl", "ProtoInfo") load(":basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS", "basic_java_library", "collect_deps") load(":java_binary_deploy_jar.bzl", "create_deploy_archive") diff --git a/java/common/rules/java_helper.bzl b/java/common/rules/java_helper.bzl index c0aa231a..f461a7f9 100644 --- a/java/common/rules/java_helper.bzl +++ b/java/common/rules/java_helper.bzl @@ -14,6 +14,7 @@ """Common util functions for java_* rules""" +load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cc_toolchain") load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_helper.bzl", "cc_helper") @@ -22,7 +23,6 @@ load( "semantics", _semantics_tokenize_javacopts = "tokenize_javacopts", ) -load("//third_party/bazel_skylib/lib:paths.bzl", "paths") visibility(["//java/..."]) diff --git a/java/common/rules/java_runtime.bzl b/java/common/rules/java_runtime.bzl index af76f498..0876639c 100644 --- a/java/common/rules/java_runtime.bzl +++ b/java/common/rules/java_runtime.bzl @@ -16,9 +16,9 @@ Definition of java_runtime rule and JavaRuntimeInfo provider. """ +load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_semantics.bzl", "PLATFORMS_ROOT") -load("//third_party/bazel_skylib/lib:paths.bzl", "paths") load(":java_helper.bzl", "helper") visibility(["//java/..."]) From 2f6c7e1e543ed97d9e4aed475843d03af195e75d Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 11 Sep 2024 11:33:12 -0700 Subject: [PATCH 020/465] Split rule bzl files into definitions and implementations The repo structure is: - `//java/bazel/rules/` : Bazel rule class definitions & implementation functions - `//java/common/rules/` : Common rule attr/subrule/utility definitions - `//java/common/rules/impl/` : Common implementation functions PiperOrigin-RevId: 673471782 Change-Id: Ic94f7cfdc745a044531c8110f4039bc7171e53f3 --- java/bazel/rules/bazel_java_binary.bzl | 154 +----- .../bazel/rules/bazel_java_binary_wrapper.bzl | 2 +- java/bazel/rules/bazel_java_import.bzl | 68 +++ java/bazel/rules/bazel_java_library.bzl | 67 +++ java/bazel/rules/bazel_java_plugin.bzl | 156 ++++++ java/bazel/rules/bazel_java_test.bzl | 150 ++++++ java/bazel/rules/empty.bzl | 14 - java/common/BUILD | 4 +- java/common/rules/BUILD | 8 + java/common/rules/android_lint.bzl | 10 +- java/common/rules/basic_java_library.bzl | 241 --------- java/common/rules/impl/BUILD | 7 + .../rules/impl/basic_java_library_impl.bzl | 265 ++++++++++ .../rules/impl/bazel_java_import_impl.bzl | 207 ++++++++ .../rules/impl/bazel_java_library_impl.bzl | 98 ++++ .../rules/{ => impl}/compile_action.bzl | 0 .../rules/{ => impl}/import_deps_check.bzl | 2 +- .../{ => impl}/java_binary_deploy_jar.bzl | 0 java/common/rules/impl/java_binary_impl.bzl | 467 ++++++++++++++++++ java/common/rules/{ => impl}/java_helper.bzl | 35 +- .../rules/{ => impl}/proguard_validation.bzl | 0 java/common/rules/java_binary.bzl | 445 +---------------- java/common/rules/java_import.bzl | 229 --------- java/common/rules/java_library.bzl | 122 +---- .../rules/java_package_configuration.bzl | 2 +- java/common/rules/java_plugin.bzl | 135 +---- java/common/rules/java_runtime.bzl | 2 +- java/common/rules/java_toolchain.bzl | 2 +- 28 files changed, 1530 insertions(+), 1362 deletions(-) create mode 100644 java/bazel/rules/bazel_java_import.bzl create mode 100644 java/bazel/rules/bazel_java_library.bzl create mode 100644 java/bazel/rules/bazel_java_plugin.bzl create mode 100644 java/bazel/rules/bazel_java_test.bzl delete mode 100644 java/bazel/rules/empty.bzl create mode 100644 java/common/rules/impl/BUILD create mode 100644 java/common/rules/impl/basic_java_library_impl.bzl create mode 100644 java/common/rules/impl/bazel_java_import_impl.bzl create mode 100644 java/common/rules/impl/bazel_java_library_impl.bzl rename java/common/rules/{ => impl}/compile_action.bzl (100%) rename java/common/rules/{ => impl}/import_deps_check.bzl (98%) rename java/common/rules/{ => impl}/java_binary_deploy_jar.bzl (100%) create mode 100644 java/common/rules/impl/java_binary_impl.bzl rename java/common/rules/{ => impl}/java_helper.bzl (94%) rename java/common/rules/{ => impl}/proguard_validation.bzl (100%) diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl index 87f36e51..f3680c12 100644 --- a/java/bazel/rules/bazel_java_binary.bzl +++ b/java/bazel/rules/bazel_java_binary.bzl @@ -21,20 +21,27 @@ load( "//java/common/rules:android_lint.bzl", "android_lint_subrule", ) -load("//java/common/rules:java_binary.bzl", "BASE_TEST_ATTRIBUTES", "BASIC_JAVA_BINARY_ATTRIBUTES", "basic_java_binary") -load("//java/common/rules:java_binary_deploy_jar.bzl", "create_deploy_archives") -load("//java/common/rules:java_helper.bzl", "helper") +load("//java/common/rules:java_binary.bzl", "BASIC_JAVA_BINARY_ATTRIBUTES") load("//java/common/rules:rule_util.bzl", "merge_attrs") +load("//java/common/rules/impl:java_binary_deploy_jar.bzl", "create_deploy_archives") +load("//java/common/rules/impl:java_binary_impl.bzl", "basic_java_binary") +load("//java/common/rules/impl:java_helper.bzl", "helper") visibility("private") def _bazel_java_binary_impl(ctx): - return _bazel_base_binary_impl(ctx, is_test_rule_class = False) + helper.executable_providers(ctx) + return bazel_base_binary_impl(ctx, is_test_rule_class = False) + helper.executable_providers(ctx) -def _bazel_java_test_impl(ctx): - return _bazel_base_binary_impl(ctx, is_test_rule_class = True) + helper.test_providers(ctx) +def bazel_base_binary_impl(ctx, is_test_rule_class): + """Common implementation for binaries and tests -def _bazel_base_binary_impl(ctx, is_test_rule_class): + Args: + ctx: (RuleContext) + is_test_rule_class: (bool) + + Returns: + [Provider] + """ deps = _collect_all_targets_as_deps(ctx, classpath_type = "compile_only") runtime_deps = _collect_all_targets_as_deps(ctx) @@ -288,7 +295,7 @@ def _short_path(file): def _compute_test_support(use_testrunner): return Label(semantics.JAVA_TEST_RUNNER_LABEL) if use_testrunner else None -def _make_binary_rule(implementation, *, doc, attrs, executable = False, test = False, initializer = None): +def make_binary_rule(implementation, *, doc, attrs, executable = False, test = False, initializer = None): return rule( implementation = implementation, initializer = initializer, @@ -315,7 +322,7 @@ def _make_binary_rule(implementation, *, doc, attrs, executable = False, test = subrules = [android_lint_subrule], ) -_BASE_BINARY_ATTRS = merge_attrs( +BASE_BINARY_ATTRS = merge_attrs( BASIC_JAVA_BINARY_ATTRIBUTES, { "resource_strip_prefix": attr.string( @@ -345,7 +352,7 @@ logic as the Java package of source files. For example, a source file at ) def make_java_binary(executable): - return _make_binary_rule( + return make_binary_rule( _bazel_java_binary_impl, doc = """

@@ -439,7 +446,7 @@ java_binary( """, attrs = merge_attrs( - _BASE_BINARY_ATTRS, + BASE_BINARY_ATTRS, ({} if executable else { "args": attr.string_list(), "output_licenses": attr.string_list(), @@ -449,128 +456,3 @@ java_binary( ) java_binary = make_java_binary(executable = True) - -def _java_test_initializer(**kwargs): - if "stamp" in kwargs and type(kwargs["stamp"]) == type(True): - kwargs["stamp"] = 1 if kwargs["stamp"] else 0 - if "use_launcher" in kwargs and not kwargs["use_launcher"]: - kwargs["launcher"] = None - else: - # If launcher is not set or None, set it to config flag - if "launcher" not in kwargs or not kwargs["launcher"]: - kwargs["launcher"] = semantics.LAUNCHER_FLAG_LABEL - return kwargs - -java_test = _make_binary_rule( - _bazel_java_test_impl, - doc = """ -

-A java_test() rule compiles a Java test. A test is a binary wrapper around your -test code. The test runner's main method is invoked instead of the main class being compiled. -

- -

Implicit output targets

-
    -
  • name.jar: A Java archive.
  • -
  • name_deploy.jar: A Java archive suitable - for deployment. (Only built if explicitly requested.) See the description of the - name_deploy.jar output from - java_binary for more details.
  • -
- -

-See the section on java_binary() arguments. This rule also -supports all attributes common -to all test rules (*_test). -

- -

Examples

- -
-
-
-java_library(
-    name = "tests",
-    srcs = glob(["*.java"]),
-    deps = [
-        "//java/com/foo/base:testResources",
-        "//java/com/foo/testing/util",
-    ],
-)
-
-java_test(
-    name = "AllTests",
-    size = "small",
-    runtime_deps = [
-        ":tests",
-        "//util/mysql",
-    ],
-)
-
-
- """, - attrs = merge_attrs( - BASE_TEST_ATTRIBUTES, - _BASE_BINARY_ATTRS, - { - "_lcov_merger": attr.label( - cfg = "exec", - default = configuration_field( - fragment = "coverage", - name = "output_generator", - ), - ), - "_collect_cc_coverage": attr.label( - cfg = "exec", - allow_single_file = True, - default = "@bazel_tools//tools/test:collect_cc_coverage", - ), - }, - override_attrs = { - "use_testrunner": attr.bool( - default = True, - doc = semantics.DOCS.for_attribute("use_testrunner") + """ -
-You can use this to override the default -behavior, which is to use test runner for -java_test rules, -and not use it for java_binary rules. It is unlikely -you will want to do this. One use is for AllTest -rules that are invoked by another rule (to set up a database -before running the tests, for example). The AllTest -rule must be declared as a java_binary, but should -still use the test runner as its main entry point. - -The name of a test runner class can be overridden with main_class attribute. - """, - ), - "stamp": attr.int( - default = 0, - values = [-1, 0, 1], - doc = """ -Whether to encode build information into the binary. Possible values: -
    -
  • - stamp = 1: Always stamp the build information into the binary, even in - --nostamp builds. This - setting should be avoided, since it potentially kills remote caching for the - binary and any downstream actions that depend on it. -
  • -
  • - stamp = 0: Always replace build information by constant values. This - gives good build result caching. -
  • -
  • - stamp = -1: Embedding of build information is controlled by the - --[no]stamp flag. -
  • -
-

Stamped binaries are not rebuilt unless their dependencies change.

- """, - ), - }, - remove_attrs = ["deploy_env"], - ), - test = True, - initializer = _java_test_initializer, -) diff --git a/java/bazel/rules/bazel_java_binary_wrapper.bzl b/java/bazel/rules/bazel_java_binary_wrapper.bzl index 31696bcc..15e8f6b2 100644 --- a/java/bazel/rules/bazel_java_binary_wrapper.bzl +++ b/java/bazel/rules/bazel_java_binary_wrapper.bzl @@ -29,7 +29,7 @@ load(":bazel_java_binary_nonexec.bzl", java_bin_nonexec = "java_binary") _java_common_internal = java_common.internal_DO_NOT_USE() -visibility("private") +visibility(["//java"]) def java_binary(**kwargs): if _java_common_internal.incompatible_disable_non_executable_java_binary(): diff --git a/java/bazel/rules/bazel_java_import.bzl b/java/bazel/rules/bazel_java_import.bzl new file mode 100644 index 00000000..02951d52 --- /dev/null +++ b/java/bazel/rules/bazel_java_import.bzl @@ -0,0 +1,68 @@ +# Copyright 2021 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. + +""" +Definition of java_import rule. +""" + +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_import.bzl", "JAVA_IMPORT_ATTRS") +load("//java/common/rules/impl:bazel_java_import_impl.bzl", "bazel_java_import_rule") + +visibility(["//java"]) + +def _proxy(ctx): + return bazel_java_import_rule( + ctx, + ctx.attr.jars, + ctx.file.srcjar, + ctx.attr.deps, + ctx.attr.runtime_deps, + ctx.attr.exports, + ctx.attr.neverlink, + ctx.files.proguard_specs, + ctx.attr.add_exports, + ctx.attr.add_opens, + ).values() + +java_import = rule( + _proxy, + doc = """ +

+ This rule allows the use of precompiled .jar files as + libraries for java_library and + java_binary rules. +

+ +

Examples

+ +
+
+    java_import(
+        name = "maven_model",
+        jars = [
+            "maven_model/maven-aether-provider-3.2.3.jar",
+            "maven_model/maven-model-3.2.3.jar",
+            "maven_model/maven-model-builder-3.2.3.jar",
+        ],
+    )
+
+
+ """, + attrs = JAVA_IMPORT_ATTRS, + provides = [JavaInfo], + fragments = ["java", "cpp"], + toolchains = [semantics.JAVA_TOOLCHAIN], +) diff --git a/java/bazel/rules/bazel_java_library.bzl b/java/bazel/rules/bazel_java_library.bzl new file mode 100644 index 00000000..e70d54fd --- /dev/null +++ b/java/bazel/rules/bazel_java_library.bzl @@ -0,0 +1,67 @@ +# Copyright 2021 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. + +""" +Definition of java_library rule. +""" + +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:android_lint.bzl", "android_lint_subrule") +load("//java/common/rules:java_library.bzl", "JAVA_LIBRARY_ATTRS") +load("//java/common/rules/impl:bazel_java_library_impl.bzl", "bazel_java_library_rule") + +visibility(["//java/..."]) + +def _proxy(ctx): + return bazel_java_library_rule( + ctx, + ctx.files.srcs, + ctx.attr.deps, + ctx.attr.runtime_deps, + ctx.attr.plugins, + ctx.attr.exports, + ctx.attr.exported_plugins, + ctx.files.resources, + ctx.attr.javacopts, + ctx.attr.neverlink, + ctx.files.proguard_specs, + ctx.attr.add_exports, + ctx.attr.add_opens, + ctx.attr.bootclasspath, + ctx.attr.javabuilder_jvm_flags, + ).values() + +java_library = rule( + _proxy, + doc = """ +

This rule compiles and links sources into a .jar file.

+ +

Implicit outputs

+
    +
  • libname.jar: A Java archive containing the class files.
  • +
  • libname-src.jar: An archive containing the sources ("source + jar").
  • +
+ """, + attrs = JAVA_LIBRARY_ATTRS, + provides = [JavaInfo], + outputs = { + "classjar": "lib%{name}.jar", + "sourcejar": "lib%{name}-src.jar", + }, + fragments = ["java", "cpp"], + toolchains = [semantics.JAVA_TOOLCHAIN], + subrules = [android_lint_subrule], +) diff --git a/java/bazel/rules/bazel_java_plugin.bzl b/java/bazel/rules/bazel_java_plugin.bzl new file mode 100644 index 00000000..462df8c3 --- /dev/null +++ b/java/bazel/rules/bazel_java_plugin.bzl @@ -0,0 +1,156 @@ +# Copyright 2021 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. + +""" +Definition of java_plugin rule. +""" + +load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") +load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:android_lint.bzl", "android_lint_subrule") +load("//java/common/rules:java_library.bzl", "JAVA_LIBRARY_IMPLICIT_ATTRS") +load("//java/common/rules:java_plugin.bzl", "JAVA_PLUGIN_ATTRS") +load("//java/common/rules:rule_util.bzl", "merge_attrs") +load("//java/common/rules/impl:basic_java_library_impl.bzl", "basic_java_library", "construct_defaultinfo") + +visibility(["//java/..."]) + +def bazel_java_plugin_rule( + ctx, + srcs = [], + data = [], + generates_api = False, + processor_class = "", + deps = [], + plugins = [], + resources = [], + javacopts = [], + neverlink = False, + proguard_specs = [], + add_exports = [], + add_opens = []): + """Implements java_plugin rule. + + Use this call when you need to produce a fully fledged java_plugin from + another rule's implementation. + + Args: + ctx: (RuleContext) Used to register the actions. + srcs: (list[File]) The list of source files that are processed to create the target. + data: (list[File]) The list of files needed by this plugin at runtime. + generates_api: (bool) This attribute marks annotation processors that generate API code. + processor_class: (str) The processor class is the fully qualified type of + the class that the Java compiler should use as entry point to the annotation processor. + deps: (list[Target]) The list of other libraries to be linked in to the target. + plugins: (list[Target]) Java compiler plugins to run at compile-time. + resources: (list[File]) A list of data files to include in a Java jar. + javacopts: (list[str]) Extra compiler options for this library. + neverlink: (bool) Whether this library should only be used for compilation and not at runtime. + proguard_specs: (list[File]) Files to be used as Proguard specification. + add_exports: (list[str]) Allow this library to access the given /. + add_opens: (list[str]) Allow this library to reflectively access the given /. + Returns: + (list[provider]) A list containing DefaultInfo, JavaInfo, + InstrumentedFilesInfo, OutputGroupsInfo, ProguardSpecProvider providers. + """ + target, base_info = basic_java_library( + ctx, + srcs, + deps, + [], # runtime_deps + plugins, + [], # exports + [], # exported_plugins + resources, + [], # resource_jars + [], # classpath_resources + javacopts, + neverlink, + proguard_specs = proguard_specs, + add_exports = add_exports, + add_opens = add_opens, + ) + java_info = target.pop("JavaInfo") + + # Replace JavaInfo with JavaPluginInfo + target["JavaPluginInfo"] = JavaPluginInfo( + runtime_deps = [java_info], + processor_class = processor_class if processor_class else None, # ignore empty string (default) + data = data, + generates_api = generates_api, + ) + target["DefaultInfo"] = construct_defaultinfo( + ctx, + base_info.files_to_build, + base_info.runfiles, + neverlink, + ) + target["OutputGroupInfo"] = OutputGroupInfo(**base_info.output_groups) + + return target + +def _proxy(ctx): + return bazel_java_plugin_rule( + ctx, + ctx.files.srcs, + ctx.files.data, + ctx.attr.generates_api, + ctx.attr.processor_class, + ctx.attr.deps, + ctx.attr.plugins, + ctx.files.resources, + ctx.attr.javacopts, + ctx.attr.neverlink, + ctx.files.proguard_specs, + ctx.attr.add_exports, + ctx.attr.add_opens, + ).values() + +_JAVA_PLUGIN_IMPLICIT_ATTRS = JAVA_LIBRARY_IMPLICIT_ATTRS + +java_plugin = rule( + _proxy, + doc = """ +

+ java_plugin defines plugins for the Java compiler run by Bazel. The + only supported kind of plugins are annotation processors. A java_library or + java_binary rule can run plugins by depending on them via the plugins + attribute. A java_library can also automatically export plugins to libraries that + directly depend on it using + exported_plugins. +

+ +

Implicit output targets

+
    +
  • libname.jar: A Java archive.
  • +
+ +

+ Arguments are identical to java_library, except + for the addition of the processor_class argument. +

+ """, + attrs = merge_attrs( + JAVA_PLUGIN_ATTRS, + _JAVA_PLUGIN_IMPLICIT_ATTRS, + ), + provides = [JavaPluginInfo], + outputs = { + "classjar": "lib%{name}.jar", + "sourcejar": "lib%{name}-src.jar", + }, + fragments = ["java", "cpp"], + toolchains = [semantics.JAVA_TOOLCHAIN], + subrules = [android_lint_subrule], +) diff --git a/java/bazel/rules/bazel_java_test.bzl b/java/bazel/rules/bazel_java_test.bzl new file mode 100644 index 00000000..a019b867 --- /dev/null +++ b/java/bazel/rules/bazel_java_test.bzl @@ -0,0 +1,150 @@ +# 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. +"""Bazel java_test rule""" + +load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_binary.bzl", "BASE_TEST_ATTRIBUTES") +load("//java/common/rules:rule_util.bzl", "merge_attrs") +load("//java/common/rules/impl:java_helper.bzl", "helper") +load(":bazel_java_binary.bzl", "BASE_BINARY_ATTRS", "bazel_base_binary_impl", "make_binary_rule") + +visibility(["//java"]) + +def _bazel_java_test_impl(ctx): + return bazel_base_binary_impl(ctx, is_test_rule_class = True) + helper.test_providers(ctx) + +def _java_test_initializer(**kwargs): + if "stamp" in kwargs and type(kwargs["stamp"]) == type(True): + kwargs["stamp"] = 1 if kwargs["stamp"] else 0 + if "use_launcher" in kwargs and not kwargs["use_launcher"]: + kwargs["launcher"] = None + else: + # If launcher is not set or None, set it to config flag + if "launcher" not in kwargs or not kwargs["launcher"]: + kwargs["launcher"] = semantics.LAUNCHER_FLAG_LABEL + return kwargs + +java_test = make_binary_rule( + _bazel_java_test_impl, + doc = """ +

+A java_test() rule compiles a Java test. A test is a binary wrapper around your +test code. The test runner's main method is invoked instead of the main class being compiled. +

+ +

Implicit output targets

+
    +
  • name.jar: A Java archive.
  • +
  • name_deploy.jar: A Java archive suitable + for deployment. (Only built if explicitly requested.) See the description of the + name_deploy.jar output from + java_binary for more details.
  • +
+ +

+See the section on java_binary() arguments. This rule also +supports all attributes common +to all test rules (*_test). +

+ +

Examples

+ +
+
+
+java_library(
+    name = "tests",
+    srcs = glob(["*.java"]),
+    deps = [
+        "//java/com/foo/base:testResources",
+        "//java/com/foo/testing/util",
+    ],
+)
+
+java_test(
+    name = "AllTests",
+    size = "small",
+    runtime_deps = [
+        ":tests",
+        "//util/mysql",
+    ],
+)
+
+
+ """, + attrs = merge_attrs( + BASE_TEST_ATTRIBUTES, + BASE_BINARY_ATTRS, + { + "_lcov_merger": attr.label( + cfg = "exec", + default = configuration_field( + fragment = "coverage", + name = "output_generator", + ), + ), + "_collect_cc_coverage": attr.label( + cfg = "exec", + allow_single_file = True, + default = "@bazel_tools//tools/test:collect_cc_coverage", + ), + }, + override_attrs = { + "use_testrunner": attr.bool( + default = True, + doc = semantics.DOCS.for_attribute("use_testrunner") + """ +
+You can use this to override the default +behavior, which is to use test runner for +java_test rules, +and not use it for java_binary rules. It is unlikely +you will want to do this. One use is for AllTest +rules that are invoked by another rule (to set up a database +before running the tests, for example). The AllTest +rule must be declared as a java_binary, but should +still use the test runner as its main entry point. + +The name of a test runner class can be overridden with main_class attribute. + """, + ), + "stamp": attr.int( + default = 0, + values = [-1, 0, 1], + doc = """ +Whether to encode build information into the binary. Possible values: +
    +
  • + stamp = 1: Always stamp the build information into the binary, even in + --nostamp builds. This + setting should be avoided, since it potentially kills remote caching for the + binary and any downstream actions that depend on it. +
  • +
  • + stamp = 0: Always replace build information by constant values. This + gives good build result caching. +
  • +
  • + stamp = -1: Embedding of build information is controlled by the + --[no]stamp flag. +
  • +
+

Stamped binaries are not rebuilt unless their dependencies change.

+ """, + ), + }, + remove_attrs = ["deploy_env"], + ), + test = True, + initializer = _java_test_initializer, +) diff --git a/java/bazel/rules/empty.bzl b/java/bazel/rules/empty.bzl deleted file mode 100644 index 6981db7e..00000000 --- a/java/bazel/rules/empty.bzl +++ /dev/null @@ -1,14 +0,0 @@ -# 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. -"""Empty file as a placeholder for migration""" diff --git a/java/common/BUILD b/java/common/BUILD index e9d0165b..e8b08c0e 100644 --- a/java/common/BUILD +++ b/java/common/BUILD @@ -6,7 +6,9 @@ licenses(["notice"]) filegroup( name = "srcs", - srcs = glob(["**"]), + srcs = glob(["**"]) + [ + "//java/common/rules:srcs", + ], visibility = ["//java:__pkg__"], ) diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD index ffd0fb0c..5031de89 100644 --- a/java/common/rules/BUILD +++ b/java/common/rules/BUILD @@ -1 +1,9 @@ package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "srcs", + srcs = glob(["**"]) + [ + "//java/common/rules/impl:srcs", + ], + visibility = ["//java/common:__pkg__"], +) diff --git a/java/common/rules/android_lint.bzl b/java/common/rules/android_lint.bzl index 9d23681b..4c96c16e 100644 --- a/java/common/rules/android_lint.bzl +++ b/java/common/rules/android_lint.bzl @@ -14,13 +14,17 @@ """Creates the android lint action for java rules""" -load("//java/common:java_semantics.bzl", "semantics") -load("//java/common/rules:java_helper.bzl", "helper") +load( + "//java/common:java_semantics.bzl", + "semantics", + _semantics_tokenize_javacopts = "tokenize_javacopts", +) visibility(["//java/..."]) def _tokenize_opts(opts_depset): - return helper.tokenize_javacopts(ctx = None, opts = opts_depset) + opts = reversed(opts_depset.to_list()) + return _semantics_tokenize_javacopts(opts) def _android_lint_action(ctx, source_files, source_jars, compilation_info): """ diff --git a/java/common/rules/basic_java_library.bzl b/java/common/rules/basic_java_library.bzl index 221baca4..c8a13fb5 100644 --- a/java/common/rules/basic_java_library.bzl +++ b/java/common/rules/basic_java_library.bzl @@ -16,256 +16,15 @@ Common code for reuse across java_* rules """ -load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_common.bzl", "java_common") -load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/common:java_semantics.bzl", "semantics") -load(":android_lint.bzl", "android_lint_subrule") -load(":compile_action.bzl", "compile_action") -load(":proguard_validation.bzl", "validate_proguard_specs") load(":rule_util.bzl", "merge_attrs") visibility([ "//java/...", ]) -_java_common_internal = java_common.internal_DO_NOT_USE() -BootClassPathInfo = java_common.BootClassPathInfo -target_kind = _java_common_internal.target_kind - -def _filter_srcs(srcs, ext): - return [f for f in srcs if f.extension == ext] - -def _filter_provider(provider, *attrs): - return [dep[provider] for attr in attrs for dep in attr if provider in dep] - -# TODO(b/11285003): disallow jar files in deps, require java_import instead -def _filter_javainfo_and_legacy_jars(attr): - dep_list = [] - - # Native code collected data into a NestedSet, using add for legacy jars and - # addTransitive for JavaInfo. This resulted in legacy jars being first in the list. - for dep in attr: - kind = target_kind(dep) - if not JavaInfo in dep or kind == "java_binary" or kind == "java_test": - for file in dep[DefaultInfo].files.to_list(): - if file.extension == "jar": - # Native doesn't construct JavaInfo - java_info = JavaInfo(output_jar = file, compile_jar = file) - dep_list.append(java_info) - - for dep in attr: - if JavaInfo in dep: - dep_list.append(dep[JavaInfo]) - return dep_list - -def basic_java_library( - ctx, - srcs, - deps = [], - runtime_deps = [], - plugins = [], - exports = [], - exported_plugins = [], - resources = [], - resource_jars = [], - classpath_resources = [], - javacopts = [], - neverlink = False, - enable_compile_jar_action = True, - coverage_config = None, - proguard_specs = None, - add_exports = [], - add_opens = [], - bootclasspath = None, - javabuilder_jvm_flags = None): - """ - Creates actions that compile and lint Java sources, sets up coverage and returns JavaInfo, InstrumentedFilesInfo and output groups. - - The call creates actions and providers needed and shared by `java_library`, - `java_plugin`,`java_binary`, and `java_test` rules and it is primarily - intended to be used in those rules. - - Before compilation coverage.runner is added to the dependencies and if - present plugins are extended with the value of `--plugin` flag. - - Args: - ctx: (RuleContext) Used to register the actions. - srcs: (list[File]) The list of source files that are processed to create the target. - deps: (list[Target]) The list of other libraries to be linked in to the target. - runtime_deps: (list[Target]) Libraries to make available to the final binary or test at runtime only. - plugins: (list[Target]) Java compiler plugins to run at compile-time. - exports: (list[Target]) Exported libraries. - exported_plugins: (list[Target]) The list of `java_plugin`s (e.g. annotation - processors) to export to libraries that directly depend on this library. - resources: (list[File]) A list of data files to include in a Java jar. - resource_jars: (list[File]) A list of jar files to unpack and include in a - Java jar. - classpath_resources: (list[File]) - javacopts: (list[str]) - neverlink: (bool) Whether this library should only be used for compilation and not at runtime. - enable_compile_jar_action: (bool) Enables header compilation or ijar creation. - coverage_config: (struct{runner:JavaInfo, support_files:list[File]|depset[File], env:dict[str,str]}) - Coverage configuration. `runner` is added to dependencies during - compilation, `support_files` and `env` is returned in InstrumentedFilesInfo. - proguard_specs: (list[File]) Files to be used as Proguard specification. - Proguard validation is done only when the parameter is set. - add_exports: (list[str]) Allow this library to access the given /. - add_opens: (list[str]) Allow this library to reflectively access the given /. - bootclasspath: (Target) The JDK APIs to compile this library against. - javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. - Returns: - (dict[str, Provider], - {files_to_build: list[File], - runfiles: list[File], - output_groups: dict[str,list[File]]}) - """ - source_files = _filter_srcs(srcs, "java") - source_jars = _filter_srcs(srcs, "srcjar") - - plugins_javaplugininfo = _collect_plugins(plugins) - plugins_javaplugininfo.append(ctx.attr._java_plugins[JavaPluginInfo]) - - properties = _filter_srcs(srcs, "properties") - if properties: - resources = list(resources) - resources.extend(properties) - - java_info, compilation_info = compile_action( - ctx, - ctx.outputs.classjar, - ctx.outputs.sourcejar, - source_files, - source_jars, - collect_deps(deps) + ([coverage_config.runner] if coverage_config and coverage_config.runner else []), - collect_deps(runtime_deps), - plugins_javaplugininfo, - collect_deps(exports), - _collect_plugins(exported_plugins), - resources, - resource_jars, - classpath_resources, - _collect_native_libraries(deps, runtime_deps, exports), - javacopts, - neverlink, - ctx.fragments.java.strict_java_deps, - enable_compile_jar_action, - add_exports = add_exports, - add_opens = add_opens, - bootclasspath = bootclasspath[BootClassPathInfo] if bootclasspath else None, - javabuilder_jvm_flags = javabuilder_jvm_flags, - ) - target = {"JavaInfo": java_info} - - output_groups = dict( - compilation_outputs = compilation_info.files_to_build, - _source_jars = java_info.transitive_source_jars, - _direct_source_jars = java_info.source_jars, - ) - - if ctx.fragments.java.run_android_lint: - generated_source_jars = [ - output.generated_source_jar - for output in java_info.java_outputs - if output.generated_source_jar != None - ] - lint_output = android_lint_subrule( - source_files, - source_jars + generated_source_jars, - compilation_info, - ) - if lint_output: - output_groups["_validation"] = [lint_output] - - target["InstrumentedFilesInfo"] = coverage_common.instrumented_files_info( - ctx, - source_attributes = ["srcs"], - dependency_attributes = ["deps", "data", "resources", "resource_jars", "exports", "runtime_deps", "jars"], - coverage_support_files = coverage_config.support_files if coverage_config else depset(), - coverage_environment = coverage_config.env if coverage_config else {}, - ) - - if proguard_specs != None: - target["ProguardSpecProvider"] = validate_proguard_specs( - ctx, - proguard_specs, - [deps, runtime_deps, exports], - ) - output_groups["_hidden_top_level_INTERNAL_"] = target["ProguardSpecProvider"].specs - - return target, struct( - files_to_build = compilation_info.files_to_build, - runfiles = compilation_info.runfiles, - output_groups = output_groups, - ) - -def _collect_plugins(plugins): - """Collects plugins from an attribute. - - Use this call to collect plugins from `plugins` or `exported_plugins` attribute. - - The call simply extracts JavaPluginInfo provider. - - Args: - plugins: (list[Target]) Attribute to collect plugins from. - Returns: - (list[JavaPluginInfo]) The plugins. - """ - return _filter_provider(JavaPluginInfo, plugins) - -def collect_deps(deps): - """Collects dependencies from an attribute. - - Use this call to collect plugins from `deps`, `runtime_deps`, or `exports` attribute. - - The call extracts JavaInfo and additionaly also "legacy jars". "legacy jars" - are wrapped into a JavaInfo. - - Args: - deps: (list[Target]) Attribute to collect dependencies from. - Returns: - (list[JavaInfo]) The dependencies. - """ - return _filter_javainfo_and_legacy_jars(deps) - -def _collect_native_libraries(*attrs): - """Collects native libraries from a list of attributes. - - Use this call to collect native libraries from `deps`, `runtime_deps`, or `exports` attributes. - - The call simply extracts CcInfo provider. - Args: - *attrs: (*list[Target]) Attribute to collect native libraries from. - Returns: - (list[CcInfo]) The native library dependencies. - """ - return _filter_provider(CcInfo, *attrs) - -def construct_defaultinfo(ctx, files_to_build, files, neverlink, *extra_attrs): - """Constructs DefaultInfo for Java library like rule. - - Args: - ctx: (RuleContext) Used to construct the runfiles. - files_to_build: (list[File]) List of the files built by the rule. - files: (list[File]) List of the files include in runfiles. - neverlink: (bool) When true empty runfiles are constructed. - *extra_attrs: (list[Target]) Extra attributes to merge runfiles from. - - Returns: - (DefaultInfo) DefaultInfo provider. - """ - if neverlink: - runfiles = None - else: - runfiles = ctx.runfiles(files = files, collect_default = True) - runfiles = runfiles.merge_all([dep[DefaultInfo].default_runfiles for attr in extra_attrs for dep in attr]) - default_info = DefaultInfo( - files = depset(files_to_build), - runfiles = runfiles, - ) - return default_info - BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS = merge_attrs( { "_java_plugins": attr.label( diff --git a/java/common/rules/impl/BUILD b/java/common/rules/impl/BUILD new file mode 100644 index 00000000..e755396a --- /dev/null +++ b/java/common/rules/impl/BUILD @@ -0,0 +1,7 @@ +package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "srcs", + srcs = glob(["**"]), + visibility = ["//java/common/rules:__pkg__"], +) diff --git a/java/common/rules/impl/basic_java_library_impl.bzl b/java/common/rules/impl/basic_java_library_impl.bzl new file mode 100644 index 00000000..8ba53430 --- /dev/null +++ b/java/common/rules/impl/basic_java_library_impl.bzl @@ -0,0 +1,265 @@ +# Copyright 2021 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 code for reuse across java_* rules +""" + +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") +load("//java/common/rules:android_lint.bzl", "android_lint_subrule") +load(":compile_action.bzl", "compile_action") +load(":proguard_validation.bzl", "validate_proguard_specs") + +visibility([ + "//java/...", +]) + +_java_common_internal = java_common.internal_DO_NOT_USE() +BootClassPathInfo = java_common.BootClassPathInfo +target_kind = _java_common_internal.target_kind + +def _filter_srcs(srcs, ext): + return [f for f in srcs if f.extension == ext] + +def _filter_provider(provider, *attrs): + return [dep[provider] for attr in attrs for dep in attr if provider in dep] + +# TODO(b/11285003): disallow jar files in deps, require java_import instead +def _filter_javainfo_and_legacy_jars(attr): + dep_list = [] + + # Native code collected data into a NestedSet, using add for legacy jars and + # addTransitive for JavaInfo. This resulted in legacy jars being first in the list. + for dep in attr: + kind = target_kind(dep) + if not JavaInfo in dep or kind == "java_binary" or kind == "java_test": + for file in dep[DefaultInfo].files.to_list(): + if file.extension == "jar": + # Native doesn't construct JavaInfo + java_info = JavaInfo(output_jar = file, compile_jar = file) + dep_list.append(java_info) + + for dep in attr: + if JavaInfo in dep: + dep_list.append(dep[JavaInfo]) + return dep_list + +def basic_java_library( + ctx, + srcs, + deps = [], + runtime_deps = [], + plugins = [], + exports = [], + exported_plugins = [], + resources = [], + resource_jars = [], + classpath_resources = [], + javacopts = [], + neverlink = False, + enable_compile_jar_action = True, + coverage_config = None, + proguard_specs = None, + add_exports = [], + add_opens = [], + bootclasspath = None, + javabuilder_jvm_flags = None): + """ + Creates actions that compile and lint Java sources, sets up coverage and returns JavaInfo, InstrumentedFilesInfo and output groups. + + The call creates actions and providers needed and shared by `java_library`, + `java_plugin`,`java_binary`, and `java_test` rules and it is primarily + intended to be used in those rules. + + Before compilation coverage.runner is added to the dependencies and if + present plugins are extended with the value of `--plugin` flag. + + Args: + ctx: (RuleContext) Used to register the actions. + srcs: (list[File]) The list of source files that are processed to create the target. + deps: (list[Target]) The list of other libraries to be linked in to the target. + runtime_deps: (list[Target]) Libraries to make available to the final binary or test at runtime only. + plugins: (list[Target]) Java compiler plugins to run at compile-time. + exports: (list[Target]) Exported libraries. + exported_plugins: (list[Target]) The list of `java_plugin`s (e.g. annotation + processors) to export to libraries that directly depend on this library. + resources: (list[File]) A list of data files to include in a Java jar. + resource_jars: (list[File]) A list of jar files to unpack and include in a + Java jar. + classpath_resources: (list[File]) + javacopts: (list[str]) + neverlink: (bool) Whether this library should only be used for compilation and not at runtime. + enable_compile_jar_action: (bool) Enables header compilation or ijar creation. + coverage_config: (struct{runner:JavaInfo, support_files:list[File]|depset[File], env:dict[str,str]}) + Coverage configuration. `runner` is added to dependencies during + compilation, `support_files` and `env` is returned in InstrumentedFilesInfo. + proguard_specs: (list[File]) Files to be used as Proguard specification. + Proguard validation is done only when the parameter is set. + add_exports: (list[str]) Allow this library to access the given /. + add_opens: (list[str]) Allow this library to reflectively access the given /. + bootclasspath: (Target) The JDK APIs to compile this library against. + javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. + Returns: + (dict[str, Provider], + {files_to_build: list[File], + runfiles: list[File], + output_groups: dict[str,list[File]]}) + """ + source_files = _filter_srcs(srcs, "java") + source_jars = _filter_srcs(srcs, "srcjar") + + plugins_javaplugininfo = _collect_plugins(plugins) + plugins_javaplugininfo.append(ctx.attr._java_plugins[JavaPluginInfo]) + + properties = _filter_srcs(srcs, "properties") + if properties: + resources = list(resources) + resources.extend(properties) + + java_info, compilation_info = compile_action( + ctx, + ctx.outputs.classjar, + ctx.outputs.sourcejar, + source_files, + source_jars, + collect_deps(deps) + ([coverage_config.runner] if coverage_config and coverage_config.runner else []), + collect_deps(runtime_deps), + plugins_javaplugininfo, + collect_deps(exports), + _collect_plugins(exported_plugins), + resources, + resource_jars, + classpath_resources, + _collect_native_libraries(deps, runtime_deps, exports), + javacopts, + neverlink, + ctx.fragments.java.strict_java_deps, + enable_compile_jar_action, + add_exports = add_exports, + add_opens = add_opens, + bootclasspath = bootclasspath[BootClassPathInfo] if bootclasspath else None, + javabuilder_jvm_flags = javabuilder_jvm_flags, + ) + target = {"JavaInfo": java_info} + + output_groups = dict( + compilation_outputs = compilation_info.files_to_build, + _source_jars = java_info.transitive_source_jars, + _direct_source_jars = java_info.source_jars, + ) + + if ctx.fragments.java.run_android_lint: + generated_source_jars = [ + output.generated_source_jar + for output in java_info.java_outputs + if output.generated_source_jar != None + ] + lint_output = android_lint_subrule( + source_files, + source_jars + generated_source_jars, + compilation_info, + ) + if lint_output: + output_groups["_validation"] = [lint_output] + + target["InstrumentedFilesInfo"] = coverage_common.instrumented_files_info( + ctx, + source_attributes = ["srcs"], + dependency_attributes = ["deps", "data", "resources", "resource_jars", "exports", "runtime_deps", "jars"], + coverage_support_files = coverage_config.support_files if coverage_config else depset(), + coverage_environment = coverage_config.env if coverage_config else {}, + ) + + if proguard_specs != None: + target["ProguardSpecProvider"] = validate_proguard_specs( + ctx, + proguard_specs, + [deps, runtime_deps, exports], + ) + output_groups["_hidden_top_level_INTERNAL_"] = target["ProguardSpecProvider"].specs + + return target, struct( + files_to_build = compilation_info.files_to_build, + runfiles = compilation_info.runfiles, + output_groups = output_groups, + ) + +def _collect_plugins(plugins): + """Collects plugins from an attribute. + + Use this call to collect plugins from `plugins` or `exported_plugins` attribute. + + The call simply extracts JavaPluginInfo provider. + + Args: + plugins: (list[Target]) Attribute to collect plugins from. + Returns: + (list[JavaPluginInfo]) The plugins. + """ + return _filter_provider(JavaPluginInfo, plugins) + +def collect_deps(deps): + """Collects dependencies from an attribute. + + Use this call to collect plugins from `deps`, `runtime_deps`, or `exports` attribute. + + The call extracts JavaInfo and additionaly also "legacy jars". "legacy jars" + are wrapped into a JavaInfo. + + Args: + deps: (list[Target]) Attribute to collect dependencies from. + Returns: + (list[JavaInfo]) The dependencies. + """ + return _filter_javainfo_and_legacy_jars(deps) + +def _collect_native_libraries(*attrs): + """Collects native libraries from a list of attributes. + + Use this call to collect native libraries from `deps`, `runtime_deps`, or `exports` attributes. + + The call simply extracts CcInfo provider. + Args: + *attrs: (*list[Target]) Attribute to collect native libraries from. + Returns: + (list[CcInfo]) The native library dependencies. + """ + return _filter_provider(CcInfo, *attrs) + +def construct_defaultinfo(ctx, files_to_build, files, neverlink, *extra_attrs): + """Constructs DefaultInfo for Java library like rule. + + Args: + ctx: (RuleContext) Used to construct the runfiles. + files_to_build: (list[File]) List of the files built by the rule. + files: (list[File]) List of the files include in runfiles. + neverlink: (bool) When true empty runfiles are constructed. + *extra_attrs: (list[Target]) Extra attributes to merge runfiles from. + + Returns: + (DefaultInfo) DefaultInfo provider. + """ + if neverlink: + runfiles = None + else: + runfiles = ctx.runfiles(files = files, collect_default = True) + runfiles = runfiles.merge_all([dep[DefaultInfo].default_runfiles for attr in extra_attrs for dep in attr]) + default_info = DefaultInfo( + files = depset(files_to_build), + runfiles = runfiles, + ) + return default_info diff --git a/java/common/rules/impl/bazel_java_import_impl.bzl b/java/common/rules/impl/bazel_java_import_impl.bzl new file mode 100644 index 00000000..1c84fb79 --- /dev/null +++ b/java/common/rules/impl/bazel_java_import_impl.bzl @@ -0,0 +1,207 @@ +# Copyright 2021 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. + +""" +Definition of java_import rule. +""" + +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules/impl:basic_java_library_impl.bzl", "construct_defaultinfo") +load("//java/common/rules/impl:import_deps_check.bzl", "import_deps_check") +load(":proguard_validation.bzl", "validate_proguard_specs") + +visibility(["//java/..."]) + +_java_common_internal = java_common.internal_DO_NOT_USE() +_run_ijar_private_for_builtins = _java_common_internal.run_ijar_private_for_builtins + +def _filter_provider(provider, *attrs): + return [dep[provider] for attr in attrs for dep in attr if provider in dep] + +def _collect_jars(ctx, jars): + jars_dict = {} + for info in jars: + if JavaInfo in info: + fail("'jars' attribute cannot contain labels of Java targets") + for jar in info.files.to_list(): + jar_path = jar.dirname + jar.basename + if jars_dict.get(jar_path) != None: + fail("in jars attribute of java_import rule //" + ctx.label.package + ":" + ctx.attr.name + ": " + jar.basename + " is a duplicate") + jars_dict[jar_path] = jar + return [jar_tuple[1] for jar_tuple in jars_dict.items()] if len(jars_dict.items()) > 0 else [] + +def _process_with_ijars_if_needed(jars, ctx): + file_dict = {} + use_ijars = ctx.fragments.java.use_ijars() + for jar in jars: + interface_jar = jar + if use_ijars: + ijar_basename = jar.short_path.removeprefix("../").removesuffix("." + jar.extension) + "-ijar.jar" + interface_jar_directory = "_ijar/" + ctx.label.name + "/" + ijar_basename + + interface_jar = ctx.actions.declare_file(interface_jar_directory) + _run_ijar_private_for_builtins( + ctx.actions, + target_label = ctx.label, + jar = jar, + output = interface_jar, + java_toolchain = semantics.find_java_toolchain(ctx), + ) + file_dict[jar] = interface_jar + + return file_dict + +def _check_export_error(ctx, exports): + not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_exports") and not getattr(ctx.attr, "_allowlist_java_import_exports")[PackageSpecificationInfo].contains(ctx.label) + disallow_java_import_exports = ctx.fragments.java.disallow_java_import_exports() + + if len(exports) != 0 and (disallow_java_import_exports or not_in_allowlist): + fail("java_import.exports is no longer supported; use java_import.deps instead") + +def _check_empty_jars_error(ctx, jars): + # TODO(kotlaja): Remove temporary incompatible flag [disallow_java_import_empty_jars] once migration is done. + not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_empty_jars") and not getattr(ctx.attr, "_allowlist_java_import_empty_jars")[PackageSpecificationInfo].contains(ctx.label) + disallow_java_import_empty_jars = ctx.fragments.java.disallow_java_import_empty_jars() + + if len(jars) == 0 and disallow_java_import_empty_jars and not_in_allowlist: + fail("empty java_import.jars is no longer supported " + ctx.label.package) + +def _create_java_info_with_dummy_output_file(ctx, srcjar, all_deps, exports, runtime_deps_list, neverlink, cc_info_list, add_exports, add_opens): + dummy_jar = ctx.actions.declare_file(ctx.label.name + "_dummy.jar") + dummy_src_jar = srcjar + if dummy_src_jar == None: + dummy_src_jar = ctx.actions.declare_file(ctx.label.name + "_src_dummy.java") + ctx.actions.write(dummy_src_jar, "") + return java_common.compile( + ctx, + output = dummy_jar, + java_toolchain = semantics.find_java_toolchain(ctx), + source_files = [dummy_src_jar], + deps = all_deps, + runtime_deps = runtime_deps_list, + neverlink = neverlink, + exports = [export[JavaInfo] for export in exports if JavaInfo in export], # Watchout, maybe you need to add them there manually. + native_libraries = cc_info_list, + add_exports = add_exports, + add_opens = add_opens, + ) + +def bazel_java_import_rule( + ctx, + jars = [], + srcjar = None, + deps = [], + runtime_deps = [], + exports = [], + neverlink = False, + proguard_specs = [], + add_exports = [], + add_opens = []): + """Implements java_import. + + This rule allows the use of precompiled .jar files as libraries in other Java rules. + + Args: + ctx: (RuleContext) Used to register the actions. + jars: (list[Artifact]) List of output jars. + srcjar: (Artifact) The jar containing the sources. + deps: (list[Target]) The list of dependent libraries. + runtime_deps: (list[Target]) Runtime dependencies to attach to the rule. + exports: (list[Target]) The list of exported libraries. + neverlink: (bool) Whether this rule should only be used for compilation and not at runtime. + proguard_specs: (list[File]) Files to be used as Proguard specification. + add_exports: (list[str]) Allow this library to access the given /. + add_opens: (list[str]) Allow this library to reflectively access the given /. + + Returns: + (list[provider]) A list containing DefaultInfo, JavaInfo, + OutputGroupsInfo, ProguardSpecProvider providers. + """ + + _check_empty_jars_error(ctx, jars) + _check_export_error(ctx, exports) + + collected_jars = _collect_jars(ctx, jars) + all_deps = _filter_provider(JavaInfo, deps, exports) + + jdeps_artifact = None + merged_java_info = java_common.merge(all_deps) + not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_deps_checking") and not ctx.attr._allowlist_java_import_deps_checking[PackageSpecificationInfo].contains(ctx.label) + if len(collected_jars) > 0 and not_in_allowlist and "incomplete-deps" not in ctx.attr.tags: + jdeps_artifact = import_deps_check( + ctx, + collected_jars, + merged_java_info.compile_jars, + merged_java_info.transitive_compile_time_jars, + "java_import", + ) + + compilation_to_runtime_jar_map = _process_with_ijars_if_needed(collected_jars, ctx) + runtime_deps_list = [runtime_dep[JavaInfo] for runtime_dep in runtime_deps if JavaInfo in runtime_dep] + cc_info_list = [dep[CcInfo] for dep in deps if CcInfo in dep] + java_info = None + if len(collected_jars) > 0: + java_infos = [] + for jar in collected_jars: + java_infos.append(JavaInfo( + output_jar = jar, + compile_jar = compilation_to_runtime_jar_map[jar], + deps = all_deps, + runtime_deps = runtime_deps_list, + neverlink = neverlink, + source_jar = srcjar, + exports = [export[JavaInfo] for export in exports if JavaInfo in export], # Watchout, maybe you need to add them there manually. + native_libraries = cc_info_list, + add_exports = add_exports, + add_opens = add_opens, + )) + java_info = java_common.merge(java_infos) + else: + # TODO(kotlaja): Remove next line once all java_import targets with empty jars attribute are cleaned from depot (b/246559727). + java_info = _create_java_info_with_dummy_output_file(ctx, srcjar, all_deps, exports, runtime_deps_list, neverlink, cc_info_list, add_exports, add_opens) + + target = {"JavaInfo": java_info} + + target["ProguardSpecProvider"] = validate_proguard_specs( + ctx, + proguard_specs, + [deps, runtime_deps, exports], + ) + + # TODO(kotlaja): Revise if collected_runtimes can be added into construct_defaultinfo directly. + collected_runtimes = [] + for runtime_dep in ctx.attr.runtime_deps: + collected_runtimes.extend(runtime_dep.files.to_list()) + + target["DefaultInfo"] = construct_defaultinfo( + ctx, + collected_jars, + collected_jars + collected_runtimes, + neverlink, + exports, + ) + + output_group_src_jars = depset() if srcjar == None else depset([srcjar]) + target["OutputGroupInfo"] = OutputGroupInfo( + **{ + "_source_jars": output_group_src_jars, + "_direct_source_jars": output_group_src_jars, + "_validation": depset() if jdeps_artifact == None else depset([jdeps_artifact]), + "_hidden_top_level_INTERNAL_": target["ProguardSpecProvider"].specs, + } + ) + return target diff --git a/java/common/rules/impl/bazel_java_library_impl.bzl b/java/common/rules/impl/bazel_java_library_impl.bzl new file mode 100644 index 00000000..f0a22748 --- /dev/null +++ b/java/common/rules/impl/bazel_java_library_impl.bzl @@ -0,0 +1,98 @@ +# Copyright 2021 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. + +""" +Definition of java_library rule. +""" + +load("//java/common/rules/impl:basic_java_library_impl.bzl", "basic_java_library", "construct_defaultinfo") + +visibility(["//java/..."]) + +def bazel_java_library_rule( + ctx, + srcs = [], + deps = [], + runtime_deps = [], + plugins = [], + exports = [], + exported_plugins = [], + resources = [], + javacopts = [], + neverlink = False, + proguard_specs = [], + add_exports = [], + add_opens = [], + bootclasspath = None, + javabuilder_jvm_flags = None): + """Implements java_library. + + Use this call when you need to produce a fully fledged java_library from + another rule's implementation. + + Args: + ctx: (RuleContext) Used to register the actions. + srcs: (list[File]) The list of source files that are processed to create the target. + deps: (list[Target]) The list of other libraries to be linked in to the target. + runtime_deps: (list[Target]) Libraries to make available to the final binary or test at runtime only. + plugins: (list[Target]) Java compiler plugins to run at compile-time. + exports: (list[Target]) Exported libraries. + exported_plugins: (list[Target]) The list of `java_plugin`s (e.g. annotation + processors) to export to libraries that directly depend on this library. + resources: (list[File]) A list of data files to include in a Java jar. + javacopts: (list[str]) Extra compiler options for this library. + neverlink: (bool) Whether this library should only be used for compilation and not at runtime. + proguard_specs: (list[File]) Files to be used as Proguard specification. + add_exports: (list[str]) Allow this library to access the given /. + add_opens: (list[str]) Allow this library to reflectively access the given /. + bootclasspath: (Target) The JDK APIs to compile this library against. + javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. + Returns: + (dict[str, provider]) A list containing DefaultInfo, JavaInfo, + InstrumentedFilesInfo, OutputGroupsInfo, ProguardSpecProvider providers. + """ + if not srcs and deps: + fail("deps not allowed without srcs; move to runtime_deps?") + + target, base_info = basic_java_library( + ctx, + srcs, + deps, + runtime_deps, + plugins, + exports, + exported_plugins, + resources, + [], # resource_jars + [], # class_pathresources + javacopts, + neverlink, + proguard_specs = proguard_specs, + add_exports = add_exports, + add_opens = add_opens, + bootclasspath = bootclasspath, + javabuilder_jvm_flags = javabuilder_jvm_flags, + ) + + target["DefaultInfo"] = construct_defaultinfo( + ctx, + base_info.files_to_build, + base_info.runfiles, + neverlink, + exports, + runtime_deps, + ) + target["OutputGroupInfo"] = OutputGroupInfo(**base_info.output_groups) + + return target diff --git a/java/common/rules/compile_action.bzl b/java/common/rules/impl/compile_action.bzl similarity index 100% rename from java/common/rules/compile_action.bzl rename to java/common/rules/impl/compile_action.bzl diff --git a/java/common/rules/import_deps_check.bzl b/java/common/rules/impl/import_deps_check.bzl similarity index 98% rename from java/common/rules/import_deps_check.bzl rename to java/common/rules/impl/import_deps_check.bzl index 1981f13f..306a40ca 100644 --- a/java/common/rules/import_deps_check.bzl +++ b/java/common/rules/impl/import_deps_check.bzl @@ -16,7 +16,7 @@ load("//java/common:java_semantics.bzl", "semantics") -visibility("private") +visibility(["//java/common/rules/..."]) def import_deps_check( ctx, diff --git a/java/common/rules/java_binary_deploy_jar.bzl b/java/common/rules/impl/java_binary_deploy_jar.bzl similarity index 100% rename from java/common/rules/java_binary_deploy_jar.bzl rename to java/common/rules/impl/java_binary_deploy_jar.bzl diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl new file mode 100644 index 00000000..03f2cbe2 --- /dev/null +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -0,0 +1,467 @@ +# 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. + +""" Implementation of java_binary for bazel """ + +load("@rules_cc//cc/common:cc_common.bzl", "cc_common") +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules/impl:basic_java_library_impl.bzl", "basic_java_library", "collect_deps") +load("//third_party/protobuf/bazel/common:proto_info.bzl", "ProtoInfo") +load(":java_binary_deploy_jar.bzl", "create_deploy_archive") +load(":java_helper.bzl", "helper") + +visibility(["//java/..."]) + +_java_common_internal = java_common.internal_DO_NOT_USE() +JavaCompilationInfo = _java_common_internal.JavaCompilationInfo +collect_native_deps_dirs = _java_common_internal.collect_native_deps_dirs +get_runtime_classpath_for_archive = _java_common_internal.get_runtime_classpath_for_archive +to_java_binary_info = _java_common_internal.to_java_binary_info + +InternalDeployJarInfo = provider( + "Provider for passing info to deploy jar rule", + fields = [ + "java_attrs", + "strip_as_default", + "add_exports", + "add_opens", + ], +) + +def basic_java_binary( + ctx, + deps, + runtime_deps, + resources, + main_class, + coverage_main_class, + coverage_config, + launcher_info, + executable, + strip_as_default, + extension_registry_provider = None, + is_test_rule_class = False): + """Creates actions for compiling and linting java sources, coverage support, and sources jar (_deploy-src.jar). + + Args: + ctx: (RuleContext) The rule context + deps: (list[Target]) The list of other targets to be compiled with + runtime_deps: (list[Target]) The list of other targets to be linked in + resources: (list[File]) The list of data files to be included in the class jar + main_class: (String) FQN of the java main class + coverage_main_class: (String) FQN of the actual main class if coverage is enabled + coverage_config: (Struct|None) If coverage is enabled, a struct with fields (runner, manifest, env, support_files), None otherwise + launcher_info: (Struct) Structure with fields (launcher, unstripped_launcher, runfiles, runtime_jars, jvm_flags, classpath_resources) + executable: (File) The executable output of the rule + strip_as_default: (bool) Whether this target outputs a stripped launcher and deploy jar + extension_registry_provider: (GeneratedExtensionRegistryProvider) internal param, do not use + is_test_rule_class: (bool) Whether this rule is a test rule + + Returns: + Tuple( + dict[str, Provider], // providers + Struct( // default info + files_to_build: depset(File), + runfiles: Runfiles, + executable: File + ), + list[String] // jvm flags + ) + + """ + if not ctx.attr.create_executable and (ctx.attr.launcher and cc_common.launcher_provider in ctx.attr.launcher): + fail("launcher specified but create_executable is false") + if not ctx.attr.use_launcher and (ctx.attr.launcher and ctx.attr.launcher.label != semantics.LAUNCHER_FLAG_LABEL): + fail("launcher specified but use_launcher is false") + + if not ctx.attr.srcs and ctx.attr.deps: + fail("deps not allowed without srcs; move to runtime_deps?") + + module_flags = [dep[JavaInfo].module_flags_info for dep in runtime_deps if JavaInfo in dep] + add_exports = depset(ctx.attr.add_exports, transitive = [m.add_exports for m in module_flags]) + add_opens = depset(ctx.attr.add_opens, transitive = [m.add_opens for m in module_flags]) + + classpath_resources = [] + classpath_resources.extend(launcher_info.classpath_resources) + if hasattr(ctx.files, "classpath_resources"): + classpath_resources.extend(ctx.files.classpath_resources) + + toolchain = semantics.find_java_toolchain(ctx) + timezone_data = [toolchain._timezone_data] if toolchain._timezone_data else [] + target, common_info = basic_java_library( + ctx, + srcs = ctx.files.srcs, + deps = deps, + runtime_deps = runtime_deps, + plugins = ctx.attr.plugins, + resources = resources, + resource_jars = timezone_data, + classpath_resources = classpath_resources, + javacopts = ctx.attr.javacopts, + neverlink = ctx.attr.neverlink, + enable_compile_jar_action = False, + coverage_config = coverage_config, + add_exports = ctx.attr.add_exports, + add_opens = ctx.attr.add_opens, + bootclasspath = ctx.attr.bootclasspath, + ) + java_info = target["JavaInfo"] + compilation_info = java_info.compilation_info + runtime_classpath = depset( + order = "preorder", + transitive = [ + java_info.transitive_runtime_jars + for java_info in ( + collect_deps(ctx.attr.runtime_deps + deps) + + ([coverage_config.runner] if coverage_config and coverage_config.runner else []) + ) + ], + ) + if extension_registry_provider: + runtime_classpath = depset(order = "preorder", direct = [extension_registry_provider.class_jar], transitive = [runtime_classpath]) + java_info = java_common.merge( + [ + java_info, + JavaInfo( + output_jar = extension_registry_provider.class_jar, + compile_jar = None, + source_jar = extension_registry_provider.src_jar, + ), + ], + ) + compilation_info = JavaCompilationInfo( + compilation_classpath = compilation_info.compilation_classpath, + runtime_classpath = runtime_classpath, + boot_classpath = compilation_info.boot_classpath, + javac_options = compilation_info.javac_options, + ) + + java_attrs = _collect_attrs(ctx, runtime_classpath, classpath_resources) + + jvm_flags = [] + + jvm_flags.extend(launcher_info.jvm_flags) + + native_libs_depsets = [] + for dep in runtime_deps: + if JavaInfo in dep: + native_libs_depsets.append(dep[JavaInfo].transitive_native_libraries) + if CcInfo in dep: + native_libs_depsets.append(dep[CcInfo].transitive_native_libraries()) + native_libs_dirs = collect_native_deps_dirs(depset(transitive = native_libs_depsets)) + if native_libs_dirs: + prefix = "${JAVA_RUNFILES}/" + ctx.workspace_name + "/" + jvm_flags.append("-Djava.library.path=%s" % ( + ":".join([prefix + d for d in native_libs_dirs]) + )) + + jvm_flags.extend(ctx.fragments.java.default_jvm_opts) + jvm_flags.extend([ctx.expand_make_variables( + "jvm_flags", + ctx.expand_location(flag, ctx.attr.data, short_paths = True), + {}, + ) for flag in ctx.attr.jvm_flags]) + + # TODO(cushon): make string formatting lazier once extend_template support is added + # https://github.com/bazelbuild/proposals#:~:text=2022%2D04%2D25,Starlark + jvm_flags.extend(["--add-exports=%s=ALL-UNNAMED" % x for x in add_exports.to_list()]) + jvm_flags.extend(["--add-opens=%s=ALL-UNNAMED" % x for x in add_opens.to_list()]) + + files_to_build = [] + + if executable: + files_to_build.append(executable) + + output_groups = common_info.output_groups + + if coverage_config: + _generate_coverage_manifest(ctx, coverage_config.manifest, java_attrs.runtime_classpath) + files_to_build.append(coverage_config.manifest) + + if extension_registry_provider: + files_to_build.append(extension_registry_provider.class_jar) + output_groups["_direct_source_jars"] = ( + output_groups["_direct_source_jars"] + [extension_registry_provider.src_jar] + ) + output_groups["_source_jars"] = depset( + direct = [extension_registry_provider.src_jar], + transitive = [output_groups["_source_jars"]], + ) + + if (ctx.fragments.java.one_version_enforcement_on_java_tests or not is_test_rule_class): + one_version_output = _create_one_version_check(ctx, java_attrs.runtime_classpath, is_test_rule_class) + else: + one_version_output = None + + validation_outputs = [one_version_output] if one_version_output else [] + + _create_deploy_sources_jar(ctx, output_groups["_source_jars"]) + + files = depset(files_to_build + common_info.files_to_build) + + transitive_runfiles_artifacts = depset(transitive = [ + files, + java_attrs.runtime_classpath, + depset(transitive = launcher_info.runfiles), + ]) + + runfiles = ctx.runfiles( + transitive_files = transitive_runfiles_artifacts, + collect_default = True, + ) + + if launcher_info.launcher: + default_launcher = helper.filter_launcher_for_target(ctx) + default_launcher_artifact = helper.launcher_artifact_for_target(ctx) + default_launcher_runfiles = default_launcher[DefaultInfo].default_runfiles + if default_launcher_artifact == launcher_info.launcher: + runfiles = runfiles.merge(default_launcher_runfiles) + else: + # N.B. The "default launcher" referred to here is the launcher target specified through + # an attribute or flag. We wish to retain the runfiles of the default launcher, *except* + # for the original cc_binary artifact, because we've swapped it out with our custom + # launcher. Hence, instead of calling builder.addTarget(), or adding an odd method + # to Runfiles.Builder, we "unravel" the call and manually add things to the builder. + # Because the NestedSet representing each target's launcher runfiles is re-built here, + # we may see increased memory consumption for representing the target's runfiles. + runfiles = runfiles.merge( + ctx.runfiles( + files = [launcher_info.launcher], + transitive_files = depset([ + file + for file in default_launcher_runfiles.files.to_list() + if file != default_launcher_artifact + ]), + symlinks = default_launcher_runfiles.symlinks, + root_symlinks = default_launcher_runfiles.root_symlinks, + ), + ) + + runfiles = runfiles.merge_all([ + dep[DefaultInfo].default_runfiles + for dep in ctx.attr.runtime_deps + if DefaultInfo in dep + ]) + + if validation_outputs: + output_groups["_validation"] = output_groups.get("_validation", []) + validation_outputs + + _filter_validation_output_group(ctx, output_groups) + + java_binary_info = to_java_binary_info(java_info, compilation_info) + + internal_deploy_jar_info = InternalDeployJarInfo( + java_attrs = java_attrs, + strip_as_default = strip_as_default, + add_exports = add_exports, + add_opens = add_opens, + ) + + # "temporary" workaround for https://github.com/bazelbuild/intellij/issues/5845 + extra_files = [] + if is_test_rule_class and ctx.fragments.java.auto_create_java_test_deploy_jars(): + extra_files.append(_auto_create_deploy_jar(ctx, internal_deploy_jar_info, launcher_info, main_class, coverage_main_class)) + + default_info = struct( + files = depset(extra_files, transitive = [files]), + runfiles = runfiles, + executable = executable, + ) + + return { + "OutputGroupInfo": OutputGroupInfo(**output_groups), + "JavaInfo": java_binary_info, + "InstrumentedFilesInfo": target["InstrumentedFilesInfo"], + "JavaRuntimeClasspathInfo": java_common.JavaRuntimeClasspathInfo(runtime_classpath = java_info.transitive_runtime_jars), + "InternalDeployJarInfo": internal_deploy_jar_info, + }, default_info, jvm_flags + +def _collect_attrs(ctx, runtime_classpath, classpath_resources): + deploy_env_jars = depset(transitive = [ + dep[java_common.JavaRuntimeClasspathInfo].runtime_classpath + for dep in ctx.attr.deploy_env + ]) if hasattr(ctx.attr, "deploy_env") else depset() + + runtime_classpath_for_archive = get_runtime_classpath_for_archive(runtime_classpath, deploy_env_jars) + runtime_jars = [ctx.outputs.classjar] + + resources = [p for p in ctx.files.srcs if p.extension == "properties"] + transitive_resources = [] + for r in ctx.attr.resources: + transitive_resources.append( + r[ProtoInfo].transitive_sources if ProtoInfo in r else r.files, + ) + + resource_names = dict() + for r in classpath_resources: + if r.basename in resource_names: + fail("entries must have different file names (duplicate: %s)" % r.basename) + resource_names[r.basename] = None + + return struct( + runtime_jars = depset(runtime_jars), + runtime_classpath_for_archive = runtime_classpath_for_archive, + classpath_resources = depset(classpath_resources), + runtime_classpath = depset(order = "preorder", direct = runtime_jars, transitive = [runtime_classpath]), + resources = depset(resources, transitive = transitive_resources), + ) + +def _generate_coverage_manifest(ctx, output, runtime_classpath): + ctx.actions.write( + output = output, + content = "\n".join([file.short_path for file in runtime_classpath.to_list()]), + ) + +def _create_one_version_check(ctx, inputs, is_test_rule_class): + one_version_level = ctx.fragments.java.one_version_enforcement_level + if one_version_level == "OFF": + return None + tool = helper.check_and_get_one_version_attribute(ctx, "_one_version_tool") + + if is_test_rule_class: + toolchain = semantics.find_java_toolchain(ctx) + allowlist = toolchain._one_version_allowlist_for_tests + else: + allowlist = helper.check_and_get_one_version_attribute(ctx, "_one_version_allowlist") + + if not tool: # On Mac oneversion tool is not available + return None + + output = ctx.actions.declare_file("%s-one-version.txt" % ctx.label.name) + + args = ctx.actions.args() + args.set_param_file_format("shell").use_param_file("@%s", use_always = True) + + one_version_inputs = [] + args.add("--output", output) + if allowlist: + args.add("--whitelist", allowlist) + one_version_inputs.append(allowlist) + if one_version_level == "WARNING": + args.add("--succeed_on_found_violations") + args.add_all( + "--inputs", + inputs, + map_each = helper.jar_and_target_arg_mapper, + ) + + ctx.actions.run( + mnemonic = "JavaOneVersion", + progress_message = "Checking for one-version violations in %{label}", + executable = tool, + toolchain = semantics.JAVA_TOOLCHAIN_TYPE, + inputs = depset(one_version_inputs, transitive = [inputs]), + tools = [tool], + outputs = [output], + arguments = [args], + ) + + return output + +def _create_deploy_sources_jar(ctx, sources): + helper.create_single_jar( + ctx.actions, + toolchain = semantics.find_java_toolchain(ctx), + output = ctx.outputs.deploysrcjar, + sources = sources, + ) + +def _filter_validation_output_group(ctx, output_group): + to_exclude = depset(transitive = [ + dep[OutputGroupInfo]._validation + for dep in ctx.attr.deploy_env + if OutputGroupInfo in dep and hasattr(dep[OutputGroupInfo], "_validation") + ]) if hasattr(ctx.attr, "deploy_env") else depset() + if to_exclude: + transitive_validations = depset(transitive = [ + _get_validations_from_attr(ctx, attr_name) + for attr_name in dir(ctx.attr) + # we also exclude implicit, cfg=host/exec and tool attributes + if not attr_name.startswith("_") and + attr_name not in [ + "deploy_env", + "applicable_licenses", + "package_metadata", + "plugins", + "translations", + # special ignored attributes + "compatible_with", + "restricted_to", + "exec_compatible_with", + "target_compatible_with", + ] + ]) + if not ctx.attr.create_executable: + excluded_set = {x: None for x in to_exclude.to_list()} + transitive_validations = [ + x + for x in transitive_validations.to_list() + if x not in excluded_set + ] + output_group["_validation_transitive"] = transitive_validations + +def _get_validations_from_attr(ctx, attr_name): + attr = getattr(ctx.attr, attr_name) + if type(attr) == "list": + return depset(transitive = [_get_validations_from_target(t) for t in attr]) + else: + return _get_validations_from_target(attr) + +def _get_validations_from_target(target): + if ( + type(target) == "Target" and + OutputGroupInfo in target and + hasattr(target[OutputGroupInfo], "_validation") + ): + return target[OutputGroupInfo]._validation + else: + return depset() + +# TODO: bazelbuild/intellij/issues/5845 - remove this once no longer required +# this need not be completely identical to the regular deploy jar since we only +# care about packaging the classpath +def _auto_create_deploy_jar(ctx, info, launcher_info, main_class, coverage_main_class): + output = ctx.actions.declare_file(ctx.label.name + "_auto_deploy.jar") + java_attrs = info.java_attrs + runtime_classpath = depset( + direct = launcher_info.runtime_jars, + transitive = [ + java_attrs.runtime_jars, + java_attrs.runtime_classpath_for_archive, + ], + order = "preorder", + ) + create_deploy_archive( + ctx, + launcher = launcher_info.launcher, + main_class = main_class, + coverage_main_class = coverage_main_class, + resources = java_attrs.resources, + classpath_resources = java_attrs.classpath_resources, + runtime_classpath = runtime_classpath, + manifest_lines = info.manifest_lines, + build_info_files = [], + build_target = str(ctx.label), + output = output, + one_version_level = ctx.fragments.java.one_version_enforcement_level, + one_version_allowlist = helper.check_and_get_one_version_attribute(ctx, "_one_version_allowlist"), + multi_release = ctx.fragments.java.multi_release_deploy_jars, + hermetic = hasattr(ctx.attr, "hermetic") and ctx.attr.hermetic, + add_exports = info.add_exports, + add_opens = info.add_opens, + ) + return output diff --git a/java/common/rules/java_helper.bzl b/java/common/rules/impl/java_helper.bzl similarity index 94% rename from java/common/rules/java_helper.bzl rename to java/common/rules/impl/java_helper.bzl index f461a7f9..82897db6 100644 --- a/java/common/rules/java_helper.bzl +++ b/java/common/rules/impl/java_helper.bzl @@ -18,11 +18,7 @@ load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cc_toolchain") load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_helper.bzl", "cc_helper") -load( - "//java/common:java_semantics.bzl", - "semantics", - _semantics_tokenize_javacopts = "tokenize_javacopts", -) +load("//java/common:java_semantics.bzl", "semantics") visibility(["//java/..."]) @@ -397,34 +393,6 @@ def _shell_escape(s): return "'" + s.replace("'", "'\\''") + "'" return s -def _tokenize_javacopts(ctx = None, opts = []): - """Tokenizes a list or depset of options to a list. - - Iff opts is a depset, we reverse the flattened list to ensure right-most - duplicates are preserved in their correct position. - - If the ctx parameter is omitted, a slow, but pure Starlark, implementation - of shell tokenization is used. Otherwise, tokenization is performed using - ctx.tokenize() which has significantly better performance (up to 100x for - large options lists). - - Args: - ctx: (RuleContext|None) the rule context - opts: (depset[str]|[str]) the javac options to tokenize - Returns: - [str] list of tokenized options - """ - if hasattr(opts, "to_list"): - opts = reversed(opts.to_list()) - if ctx: - return [ - token - for opt in opts - for token in ctx.tokenize(opt) - ] - else: - return _semantics_tokenize_javacopts(opts) - def _detokenize_javacopts(opts): """Detokenizes a list of options to a depset. @@ -500,7 +468,6 @@ helper = struct( executable_providers = _executable_providers, create_single_jar = _create_single_jar, shell_escape = _shell_escape, - tokenize_javacopts = _tokenize_javacopts, detokenize_javacopts = _detokenize_javacopts, derive_output_file = _derive_output_file, is_stamping_enabled = _is_stamping_enabled, diff --git a/java/common/rules/proguard_validation.bzl b/java/common/rules/impl/proguard_validation.bzl similarity index 100% rename from java/common/rules/proguard_validation.bzl rename to java/common/rules/impl/proguard_validation.bzl diff --git a/java/common/rules/java_binary.bzl b/java/common/rules/java_binary.bzl index 79d6ff5d..5bdcd480 100644 --- a/java/common/rules/java_binary.bzl +++ b/java/common/rules/java_binary.bzl @@ -15,462 +15,19 @@ """ Implementation of java_binary for bazel """ load("@bazel_skylib//lib:paths.bzl", "paths") -load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/common:java_semantics.bzl", "PLATFORMS_ROOT", "semantics") -load("//third_party/protobuf/bazel/common:proto_info.bzl", "ProtoInfo") -load(":basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS", "basic_java_library", "collect_deps") -load(":java_binary_deploy_jar.bzl", "create_deploy_archive") -load(":java_helper.bzl", "helper") +load(":basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS") load(":rule_util.bzl", "merge_attrs") visibility(["//java/..."]) BootClassPathInfo = java_common.BootClassPathInfo -CcLauncherInfo = cc_common.launcher_provider _java_common_internal = java_common.internal_DO_NOT_USE() -JavaCompilationInfo = _java_common_internal.JavaCompilationInfo -collect_native_deps_dirs = _java_common_internal.collect_native_deps_dirs -get_runtime_classpath_for_archive = _java_common_internal.get_runtime_classpath_for_archive -to_java_binary_info = _java_common_internal.to_java_binary_info - -InternalDeployJarInfo = provider( - "Provider for passing info to deploy jar rule", - fields = [ - "java_attrs", - "strip_as_default", - "add_exports", - "add_opens", - ], -) - -def basic_java_binary( - ctx, - deps, - runtime_deps, - resources, - main_class, - coverage_main_class, - coverage_config, - launcher_info, - executable, - strip_as_default, - extension_registry_provider = None, - is_test_rule_class = False): - """Creates actions for compiling and linting java sources, coverage support, and sources jar (_deploy-src.jar). - - Args: - ctx: (RuleContext) The rule context - deps: (list[Target]) The list of other targets to be compiled with - runtime_deps: (list[Target]) The list of other targets to be linked in - resources: (list[File]) The list of data files to be included in the class jar - main_class: (String) FQN of the java main class - coverage_main_class: (String) FQN of the actual main class if coverage is enabled - coverage_config: (Struct|None) If coverage is enabled, a struct with fields (runner, manifest, env, support_files), None otherwise - launcher_info: (Struct) Structure with fields (launcher, unstripped_launcher, runfiles, runtime_jars, jvm_flags, classpath_resources) - executable: (File) The executable output of the rule - strip_as_default: (bool) Whether this target outputs a stripped launcher and deploy jar - extension_registry_provider: (GeneratedExtensionRegistryProvider) internal param, do not use - is_test_rule_class: (bool) Whether this rule is a test rule - - Returns: - Tuple( - dict[str, Provider], // providers - Struct( // default info - files_to_build: depset(File), - runfiles: Runfiles, - executable: File - ), - list[String] // jvm flags - ) - - """ - if not ctx.attr.create_executable and (ctx.attr.launcher and cc_common.launcher_provider in ctx.attr.launcher): - fail("launcher specified but create_executable is false") - if not ctx.attr.use_launcher and (ctx.attr.launcher and ctx.attr.launcher.label != semantics.LAUNCHER_FLAG_LABEL): - fail("launcher specified but use_launcher is false") - - if not ctx.attr.srcs and ctx.attr.deps: - fail("deps not allowed without srcs; move to runtime_deps?") - - module_flags = [dep[JavaInfo].module_flags_info for dep in runtime_deps if JavaInfo in dep] - add_exports = depset(ctx.attr.add_exports, transitive = [m.add_exports for m in module_flags]) - add_opens = depset(ctx.attr.add_opens, transitive = [m.add_opens for m in module_flags]) - - classpath_resources = [] - classpath_resources.extend(launcher_info.classpath_resources) - if hasattr(ctx.files, "classpath_resources"): - classpath_resources.extend(ctx.files.classpath_resources) - - toolchain = semantics.find_java_toolchain(ctx) - timezone_data = [toolchain._timezone_data] if toolchain._timezone_data else [] - target, common_info = basic_java_library( - ctx, - srcs = ctx.files.srcs, - deps = deps, - runtime_deps = runtime_deps, - plugins = ctx.attr.plugins, - resources = resources, - resource_jars = timezone_data, - classpath_resources = classpath_resources, - javacopts = ctx.attr.javacopts, - neverlink = ctx.attr.neverlink, - enable_compile_jar_action = False, - coverage_config = coverage_config, - add_exports = ctx.attr.add_exports, - add_opens = ctx.attr.add_opens, - bootclasspath = ctx.attr.bootclasspath, - ) - java_info = target["JavaInfo"] - compilation_info = java_info.compilation_info - runtime_classpath = depset( - order = "preorder", - transitive = [ - java_info.transitive_runtime_jars - for java_info in ( - collect_deps(ctx.attr.runtime_deps + deps) + - ([coverage_config.runner] if coverage_config and coverage_config.runner else []) - ) - ], - ) - if extension_registry_provider: - runtime_classpath = depset(order = "preorder", direct = [extension_registry_provider.class_jar], transitive = [runtime_classpath]) - java_info = java_common.merge( - [ - java_info, - JavaInfo( - output_jar = extension_registry_provider.class_jar, - compile_jar = None, - source_jar = extension_registry_provider.src_jar, - ), - ], - ) - compilation_info = JavaCompilationInfo( - compilation_classpath = compilation_info.compilation_classpath, - runtime_classpath = runtime_classpath, - boot_classpath = compilation_info.boot_classpath, - javac_options = compilation_info.javac_options, - ) - - java_attrs = _collect_attrs(ctx, runtime_classpath, classpath_resources) - - jvm_flags = [] - - jvm_flags.extend(launcher_info.jvm_flags) - - native_libs_depsets = [] - for dep in runtime_deps: - if JavaInfo in dep: - native_libs_depsets.append(dep[JavaInfo].transitive_native_libraries) - if CcInfo in dep: - native_libs_depsets.append(dep[CcInfo].transitive_native_libraries()) - native_libs_dirs = collect_native_deps_dirs(depset(transitive = native_libs_depsets)) - if native_libs_dirs: - prefix = "${JAVA_RUNFILES}/" + ctx.workspace_name + "/" - jvm_flags.append("-Djava.library.path=%s" % ( - ":".join([prefix + d for d in native_libs_dirs]) - )) - - jvm_flags.extend(ctx.fragments.java.default_jvm_opts) - jvm_flags.extend([ctx.expand_make_variables( - "jvm_flags", - ctx.expand_location(flag, ctx.attr.data, short_paths = True), - {}, - ) for flag in ctx.attr.jvm_flags]) - - # TODO(cushon): make string formatting lazier once extend_template support is added - # https://github.com/bazelbuild/proposals#:~:text=2022%2D04%2D25,Starlark - jvm_flags.extend(["--add-exports=%s=ALL-UNNAMED" % x for x in add_exports.to_list()]) - jvm_flags.extend(["--add-opens=%s=ALL-UNNAMED" % x for x in add_opens.to_list()]) - - files_to_build = [] - - if executable: - files_to_build.append(executable) - - output_groups = common_info.output_groups - - if coverage_config: - _generate_coverage_manifest(ctx, coverage_config.manifest, java_attrs.runtime_classpath) - files_to_build.append(coverage_config.manifest) - - if extension_registry_provider: - files_to_build.append(extension_registry_provider.class_jar) - output_groups["_direct_source_jars"] = ( - output_groups["_direct_source_jars"] + [extension_registry_provider.src_jar] - ) - output_groups["_source_jars"] = depset( - direct = [extension_registry_provider.src_jar], - transitive = [output_groups["_source_jars"]], - ) - - if (ctx.fragments.java.one_version_enforcement_on_java_tests or not is_test_rule_class): - one_version_output = _create_one_version_check(ctx, java_attrs.runtime_classpath, is_test_rule_class) - else: - one_version_output = None - - validation_outputs = [one_version_output] if one_version_output else [] - - _create_deploy_sources_jar(ctx, output_groups["_source_jars"]) - - files = depset(files_to_build + common_info.files_to_build) - - transitive_runfiles_artifacts = depset(transitive = [ - files, - java_attrs.runtime_classpath, - depset(transitive = launcher_info.runfiles), - ]) - - runfiles = ctx.runfiles( - transitive_files = transitive_runfiles_artifacts, - collect_default = True, - ) - - if launcher_info.launcher: - default_launcher = helper.filter_launcher_for_target(ctx) - default_launcher_artifact = helper.launcher_artifact_for_target(ctx) - default_launcher_runfiles = default_launcher[DefaultInfo].default_runfiles - if default_launcher_artifact == launcher_info.launcher: - runfiles = runfiles.merge(default_launcher_runfiles) - else: - # N.B. The "default launcher" referred to here is the launcher target specified through - # an attribute or flag. We wish to retain the runfiles of the default launcher, *except* - # for the original cc_binary artifact, because we've swapped it out with our custom - # launcher. Hence, instead of calling builder.addTarget(), or adding an odd method - # to Runfiles.Builder, we "unravel" the call and manually add things to the builder. - # Because the NestedSet representing each target's launcher runfiles is re-built here, - # we may see increased memory consumption for representing the target's runfiles. - runfiles = runfiles.merge( - ctx.runfiles( - files = [launcher_info.launcher], - transitive_files = depset([ - file - for file in default_launcher_runfiles.files.to_list() - if file != default_launcher_artifact - ]), - symlinks = default_launcher_runfiles.symlinks, - root_symlinks = default_launcher_runfiles.root_symlinks, - ), - ) - - runfiles = runfiles.merge_all([ - dep[DefaultInfo].default_runfiles - for dep in ctx.attr.runtime_deps - if DefaultInfo in dep - ]) - - if validation_outputs: - output_groups["_validation"] = output_groups.get("_validation", []) + validation_outputs - - _filter_validation_output_group(ctx, output_groups) - - java_binary_info = to_java_binary_info(java_info, compilation_info) - - internal_deploy_jar_info = InternalDeployJarInfo( - java_attrs = java_attrs, - strip_as_default = strip_as_default, - add_exports = add_exports, - add_opens = add_opens, - ) - - # "temporary" workaround for https://github.com/bazelbuild/intellij/issues/5845 - extra_files = [] - if is_test_rule_class and ctx.fragments.java.auto_create_java_test_deploy_jars(): - extra_files.append(_auto_create_deploy_jar(ctx, internal_deploy_jar_info, launcher_info, main_class, coverage_main_class)) - - default_info = struct( - files = depset(extra_files, transitive = [files]), - runfiles = runfiles, - executable = executable, - ) - - return { - "OutputGroupInfo": OutputGroupInfo(**output_groups), - "JavaInfo": java_binary_info, - "InstrumentedFilesInfo": target["InstrumentedFilesInfo"], - "JavaRuntimeClasspathInfo": java_common.JavaRuntimeClasspathInfo(runtime_classpath = java_info.transitive_runtime_jars), - "InternalDeployJarInfo": internal_deploy_jar_info, - }, default_info, jvm_flags - -def _collect_attrs(ctx, runtime_classpath, classpath_resources): - deploy_env_jars = depset(transitive = [ - dep[java_common.JavaRuntimeClasspathInfo].runtime_classpath - for dep in ctx.attr.deploy_env - ]) if hasattr(ctx.attr, "deploy_env") else depset() - - runtime_classpath_for_archive = get_runtime_classpath_for_archive(runtime_classpath, deploy_env_jars) - runtime_jars = [ctx.outputs.classjar] - - resources = [p for p in ctx.files.srcs if p.extension == "properties"] - transitive_resources = [] - for r in ctx.attr.resources: - transitive_resources.append( - r[ProtoInfo].transitive_sources if ProtoInfo in r else r.files, - ) - - resource_names = dict() - for r in classpath_resources: - if r.basename in resource_names: - fail("entries must have different file names (duplicate: %s)" % r.basename) - resource_names[r.basename] = None - - return struct( - runtime_jars = depset(runtime_jars), - runtime_classpath_for_archive = runtime_classpath_for_archive, - classpath_resources = depset(classpath_resources), - runtime_classpath = depset(order = "preorder", direct = runtime_jars, transitive = [runtime_classpath]), - resources = depset(resources, transitive = transitive_resources), - ) - -def _generate_coverage_manifest(ctx, output, runtime_classpath): - ctx.actions.write( - output = output, - content = "\n".join([file.short_path for file in runtime_classpath.to_list()]), - ) - -def _create_one_version_check(ctx, inputs, is_test_rule_class): - one_version_level = ctx.fragments.java.one_version_enforcement_level - if one_version_level == "OFF": - return None - tool = helper.check_and_get_one_version_attribute(ctx, "_one_version_tool") - - if is_test_rule_class: - toolchain = semantics.find_java_toolchain(ctx) - allowlist = toolchain._one_version_allowlist_for_tests - else: - allowlist = helper.check_and_get_one_version_attribute(ctx, "_one_version_allowlist") - - if not tool: # On Mac oneversion tool is not available - return None - - output = ctx.actions.declare_file("%s-one-version.txt" % ctx.label.name) - - args = ctx.actions.args() - args.set_param_file_format("shell").use_param_file("@%s", use_always = True) - - one_version_inputs = [] - args.add("--output", output) - if allowlist: - args.add("--whitelist", allowlist) - one_version_inputs.append(allowlist) - if one_version_level == "WARNING": - args.add("--succeed_on_found_violations") - args.add_all( - "--inputs", - inputs, - map_each = helper.jar_and_target_arg_mapper, - ) - - ctx.actions.run( - mnemonic = "JavaOneVersion", - progress_message = "Checking for one-version violations in %{label}", - executable = tool, - toolchain = semantics.JAVA_TOOLCHAIN_TYPE, - inputs = depset(one_version_inputs, transitive = [inputs]), - tools = [tool], - outputs = [output], - arguments = [args], - ) - - return output - -def _create_deploy_sources_jar(ctx, sources): - helper.create_single_jar( - ctx.actions, - toolchain = semantics.find_java_toolchain(ctx), - output = ctx.outputs.deploysrcjar, - sources = sources, - ) - -def _filter_validation_output_group(ctx, output_group): - to_exclude = depset(transitive = [ - dep[OutputGroupInfo]._validation - for dep in ctx.attr.deploy_env - if OutputGroupInfo in dep and hasattr(dep[OutputGroupInfo], "_validation") - ]) if hasattr(ctx.attr, "deploy_env") else depset() - if to_exclude: - transitive_validations = depset(transitive = [ - _get_validations_from_attr(ctx, attr_name) - for attr_name in dir(ctx.attr) - # we also exclude implicit, cfg=host/exec and tool attributes - if not attr_name.startswith("_") and - attr_name not in [ - "deploy_env", - "applicable_licenses", - "package_metadata", - "plugins", - "translations", - # special ignored attributes - "compatible_with", - "restricted_to", - "exec_compatible_with", - "target_compatible_with", - ] - ]) - if not ctx.attr.create_executable: - excluded_set = {x: None for x in to_exclude.to_list()} - transitive_validations = [ - x - for x in transitive_validations.to_list() - if x not in excluded_set - ] - output_group["_validation_transitive"] = transitive_validations - -def _get_validations_from_attr(ctx, attr_name): - attr = getattr(ctx.attr, attr_name) - if type(attr) == "list": - return depset(transitive = [_get_validations_from_target(t) for t in attr]) - else: - return _get_validations_from_target(attr) - -def _get_validations_from_target(target): - if ( - type(target) == "Target" and - OutputGroupInfo in target and - hasattr(target[OutputGroupInfo], "_validation") - ): - return target[OutputGroupInfo]._validation - else: - return depset() - -# TODO: bazelbuild/intellij/issues/5845 - remove this once no longer required -# this need not be completely identical to the regular deploy jar since we only -# care about packaging the classpath -def _auto_create_deploy_jar(ctx, info, launcher_info, main_class, coverage_main_class): - output = ctx.actions.declare_file(ctx.label.name + "_auto_deploy.jar") - java_attrs = info.java_attrs - runtime_classpath = depset( - direct = launcher_info.runtime_jars, - transitive = [ - java_attrs.runtime_jars, - java_attrs.runtime_classpath_for_archive, - ], - order = "preorder", - ) - create_deploy_archive( - ctx, - launcher = launcher_info.launcher, - main_class = main_class, - coverage_main_class = coverage_main_class, - resources = java_attrs.resources, - classpath_resources = java_attrs.classpath_resources, - runtime_classpath = runtime_classpath, - manifest_lines = info.manifest_lines, - build_info_files = [], - build_target = str(ctx.label), - output = output, - one_version_level = ctx.fragments.java.one_version_enforcement_level, - one_version_allowlist = helper.check_and_get_one_version_attribute(ctx, "_one_version_allowlist"), - multi_release = ctx.fragments.java.multi_release_deploy_jars, - hermetic = hasattr(ctx.attr, "hermetic") and ctx.attr.hermetic, - add_exports = info.add_exports, - add_opens = info.add_opens, - ) - return output BASIC_JAVA_BINARY_ATTRIBUTES = merge_attrs( BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS, diff --git a/java/common/rules/java_import.bzl b/java/common/rules/java_import.bzl index 7ba8065c..eb8f09ea 100644 --- a/java/common/rules/java_import.bzl +++ b/java/common/rules/java_import.bzl @@ -16,210 +16,11 @@ Definition of java_import rule. """ -load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") -load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") -load(":basic_java_library.bzl", "construct_defaultinfo") -load(":import_deps_check.bzl", "import_deps_check") -load(":proguard_validation.bzl", "validate_proguard_specs") visibility(["//java/..."]) -_java_common_internal = java_common.internal_DO_NOT_USE() -_run_ijar_private_for_builtins = _java_common_internal.run_ijar_private_for_builtins - -def _filter_provider(provider, *attrs): - return [dep[provider] for attr in attrs for dep in attr if provider in dep] - -def _collect_jars(ctx, jars): - jars_dict = {} - for info in jars: - if JavaInfo in info: - fail("'jars' attribute cannot contain labels of Java targets") - for jar in info.files.to_list(): - jar_path = jar.dirname + jar.basename - if jars_dict.get(jar_path) != None: - fail("in jars attribute of java_import rule //" + ctx.label.package + ":" + ctx.attr.name + ": " + jar.basename + " is a duplicate") - jars_dict[jar_path] = jar - return [jar_tuple[1] for jar_tuple in jars_dict.items()] if len(jars_dict.items()) > 0 else [] - -def _process_with_ijars_if_needed(jars, ctx): - file_dict = {} - use_ijars = ctx.fragments.java.use_ijars() - for jar in jars: - interface_jar = jar - if use_ijars: - ijar_basename = jar.short_path.removeprefix("../").removesuffix("." + jar.extension) + "-ijar.jar" - interface_jar_directory = "_ijar/" + ctx.label.name + "/" + ijar_basename - - interface_jar = ctx.actions.declare_file(interface_jar_directory) - _run_ijar_private_for_builtins( - ctx.actions, - target_label = ctx.label, - jar = jar, - output = interface_jar, - java_toolchain = semantics.find_java_toolchain(ctx), - ) - file_dict[jar] = interface_jar - - return file_dict - -def _check_export_error(ctx, exports): - not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_exports") and not getattr(ctx.attr, "_allowlist_java_import_exports")[PackageSpecificationInfo].contains(ctx.label) - disallow_java_import_exports = ctx.fragments.java.disallow_java_import_exports() - - if len(exports) != 0 and (disallow_java_import_exports or not_in_allowlist): - fail("java_import.exports is no longer supported; use java_import.deps instead") - -def _check_empty_jars_error(ctx, jars): - # TODO(kotlaja): Remove temporary incompatible flag [disallow_java_import_empty_jars] once migration is done. - not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_empty_jars") and not getattr(ctx.attr, "_allowlist_java_import_empty_jars")[PackageSpecificationInfo].contains(ctx.label) - disallow_java_import_empty_jars = ctx.fragments.java.disallow_java_import_empty_jars() - - if len(jars) == 0 and disallow_java_import_empty_jars and not_in_allowlist: - fail("empty java_import.jars is no longer supported " + ctx.label.package) - -def _create_java_info_with_dummy_output_file(ctx, srcjar, all_deps, exports, runtime_deps_list, neverlink, cc_info_list, add_exports, add_opens): - dummy_jar = ctx.actions.declare_file(ctx.label.name + "_dummy.jar") - dummy_src_jar = srcjar - if dummy_src_jar == None: - dummy_src_jar = ctx.actions.declare_file(ctx.label.name + "_src_dummy.java") - ctx.actions.write(dummy_src_jar, "") - return java_common.compile( - ctx, - output = dummy_jar, - java_toolchain = semantics.find_java_toolchain(ctx), - source_files = [dummy_src_jar], - deps = all_deps, - runtime_deps = runtime_deps_list, - neverlink = neverlink, - exports = [export[JavaInfo] for export in exports if JavaInfo in export], # Watchout, maybe you need to add them there manually. - native_libraries = cc_info_list, - add_exports = add_exports, - add_opens = add_opens, - ) - -def bazel_java_import_rule( - ctx, - jars = [], - srcjar = None, - deps = [], - runtime_deps = [], - exports = [], - neverlink = False, - proguard_specs = [], - add_exports = [], - add_opens = []): - """Implements java_import. - - This rule allows the use of precompiled .jar files as libraries in other Java rules. - - Args: - ctx: (RuleContext) Used to register the actions. - jars: (list[Artifact]) List of output jars. - srcjar: (Artifact) The jar containing the sources. - deps: (list[Target]) The list of dependent libraries. - runtime_deps: (list[Target]) Runtime dependencies to attach to the rule. - exports: (list[Target]) The list of exported libraries. - neverlink: (bool) Whether this rule should only be used for compilation and not at runtime. - proguard_specs: (list[File]) Files to be used as Proguard specification. - add_exports: (list[str]) Allow this library to access the given /. - add_opens: (list[str]) Allow this library to reflectively access the given /. - - Returns: - (list[provider]) A list containing DefaultInfo, JavaInfo, - OutputGroupsInfo, ProguardSpecProvider providers. - """ - - _check_empty_jars_error(ctx, jars) - _check_export_error(ctx, exports) - - collected_jars = _collect_jars(ctx, jars) - all_deps = _filter_provider(JavaInfo, deps, exports) - - jdeps_artifact = None - merged_java_info = java_common.merge(all_deps) - not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_deps_checking") and not ctx.attr._allowlist_java_import_deps_checking[PackageSpecificationInfo].contains(ctx.label) - if len(collected_jars) > 0 and not_in_allowlist and "incomplete-deps" not in ctx.attr.tags: - jdeps_artifact = import_deps_check( - ctx, - collected_jars, - merged_java_info.compile_jars, - merged_java_info.transitive_compile_time_jars, - "java_import", - ) - - compilation_to_runtime_jar_map = _process_with_ijars_if_needed(collected_jars, ctx) - runtime_deps_list = [runtime_dep[JavaInfo] for runtime_dep in runtime_deps if JavaInfo in runtime_dep] - cc_info_list = [dep[CcInfo] for dep in deps if CcInfo in dep] - java_info = None - if len(collected_jars) > 0: - java_infos = [] - for jar in collected_jars: - java_infos.append(JavaInfo( - output_jar = jar, - compile_jar = compilation_to_runtime_jar_map[jar], - deps = all_deps, - runtime_deps = runtime_deps_list, - neverlink = neverlink, - source_jar = srcjar, - exports = [export[JavaInfo] for export in exports if JavaInfo in export], # Watchout, maybe you need to add them there manually. - native_libraries = cc_info_list, - add_exports = add_exports, - add_opens = add_opens, - )) - java_info = java_common.merge(java_infos) - else: - # TODO(kotlaja): Remove next line once all java_import targets with empty jars attribute are cleaned from depot (b/246559727). - java_info = _create_java_info_with_dummy_output_file(ctx, srcjar, all_deps, exports, runtime_deps_list, neverlink, cc_info_list, add_exports, add_opens) - - target = {"JavaInfo": java_info} - - target["ProguardSpecProvider"] = validate_proguard_specs( - ctx, - proguard_specs, - [deps, runtime_deps, exports], - ) - - # TODO(kotlaja): Revise if collected_runtimes can be added into construct_defaultinfo directly. - collected_runtimes = [] - for runtime_dep in ctx.attr.runtime_deps: - collected_runtimes.extend(runtime_dep.files.to_list()) - - target["DefaultInfo"] = construct_defaultinfo( - ctx, - collected_jars, - collected_jars + collected_runtimes, - neverlink, - exports, - ) - - output_group_src_jars = depset() if srcjar == None else depset([srcjar]) - target["OutputGroupInfo"] = OutputGroupInfo( - **{ - "_source_jars": output_group_src_jars, - "_direct_source_jars": output_group_src_jars, - "_validation": depset() if jdeps_artifact == None else depset([jdeps_artifact]), - "_hidden_top_level_INTERNAL_": target["ProguardSpecProvider"].specs, - } - ) - return target - -def _proxy(ctx): - return bazel_java_import_rule( - ctx, - ctx.attr.jars, - ctx.file.srcjar, - ctx.attr.deps, - ctx.attr.runtime_deps, - ctx.attr.exports, - ctx.attr.neverlink, - ctx.files.proguard_specs, - ctx.attr.add_exports, - ctx.attr.add_opens, - ).values() - _ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT = [ "java_library", "java_import", @@ -324,33 +125,3 @@ This corresponds to the javac and JVM --add-opens= flags. "licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), "_java_toolchain_type": attr.label(default = semantics.JAVA_TOOLCHAIN_TYPE), } - -java_import = rule( - _proxy, - doc = """ -

- This rule allows the use of precompiled .jar files as - libraries for java_library and - java_binary rules. -

- -

Examples

- -
-
-    java_import(
-        name = "maven_model",
-        jars = [
-            "maven_model/maven-aether-provider-3.2.3.jar",
-            "maven_model/maven-model-3.2.3.jar",
-            "maven_model/maven-model-builder-3.2.3.jar",
-        ],
-    )
-
-
- """, - attrs = JAVA_IMPORT_ATTRS, - provides = [JavaInfo], - fragments = ["java", "cpp"], - toolchains = [semantics.JAVA_TOOLCHAIN], -) diff --git a/java/common/rules/java_library.bzl b/java/common/rules/java_library.bzl index 1ca788d5..8cf012f9 100644 --- a/java/common/rules/java_library.bzl +++ b/java/common/rules/java_library.bzl @@ -20,110 +20,13 @@ load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/common:java_semantics.bzl", "semantics") -load(":android_lint.bzl", "android_lint_subrule") -load(":basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS", "basic_java_library", "construct_defaultinfo") +load(":basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS") load(":rule_util.bzl", "merge_attrs") visibility(["//java/..."]) BootClassPathInfo = java_common.BootClassPathInfo -def bazel_java_library_rule( - ctx, - srcs = [], - deps = [], - runtime_deps = [], - plugins = [], - exports = [], - exported_plugins = [], - resources = [], - javacopts = [], - neverlink = False, - proguard_specs = [], - add_exports = [], - add_opens = [], - bootclasspath = None, - javabuilder_jvm_flags = None): - """Implements java_library. - - Use this call when you need to produce a fully fledged java_library from - another rule's implementation. - - Args: - ctx: (RuleContext) Used to register the actions. - srcs: (list[File]) The list of source files that are processed to create the target. - deps: (list[Target]) The list of other libraries to be linked in to the target. - runtime_deps: (list[Target]) Libraries to make available to the final binary or test at runtime only. - plugins: (list[Target]) Java compiler plugins to run at compile-time. - exports: (list[Target]) Exported libraries. - exported_plugins: (list[Target]) The list of `java_plugin`s (e.g. annotation - processors) to export to libraries that directly depend on this library. - resources: (list[File]) A list of data files to include in a Java jar. - javacopts: (list[str]) Extra compiler options for this library. - neverlink: (bool) Whether this library should only be used for compilation and not at runtime. - proguard_specs: (list[File]) Files to be used as Proguard specification. - add_exports: (list[str]) Allow this library to access the given /. - add_opens: (list[str]) Allow this library to reflectively access the given /. - bootclasspath: (Target) The JDK APIs to compile this library against. - javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. - Returns: - (dict[str, provider]) A list containing DefaultInfo, JavaInfo, - InstrumentedFilesInfo, OutputGroupsInfo, ProguardSpecProvider providers. - """ - if not srcs and deps: - fail("deps not allowed without srcs; move to runtime_deps?") - - target, base_info = basic_java_library( - ctx, - srcs, - deps, - runtime_deps, - plugins, - exports, - exported_plugins, - resources, - [], # resource_jars - [], # class_pathresources - javacopts, - neverlink, - proguard_specs = proguard_specs, - add_exports = add_exports, - add_opens = add_opens, - bootclasspath = bootclasspath, - javabuilder_jvm_flags = javabuilder_jvm_flags, - ) - - target["DefaultInfo"] = construct_defaultinfo( - ctx, - base_info.files_to_build, - base_info.runfiles, - neverlink, - exports, - runtime_deps, - ) - target["OutputGroupInfo"] = OutputGroupInfo(**base_info.output_groups) - - return target - -def _proxy(ctx): - return bazel_java_library_rule( - ctx, - ctx.files.srcs, - ctx.attr.deps, - ctx.attr.runtime_deps, - ctx.attr.plugins, - ctx.attr.exports, - ctx.attr.exported_plugins, - ctx.files.resources, - ctx.attr.javacopts, - ctx.attr.neverlink, - ctx.files.proguard_specs, - ctx.attr.add_exports, - ctx.attr.add_opens, - ctx.attr.bootclasspath, - ctx.attr.javabuilder_jvm_flags, - ).values() - JAVA_LIBRARY_IMPLICIT_ATTRS = BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS JAVA_LIBRARY_ATTRS = merge_attrs( @@ -367,26 +270,3 @@ This corresponds to the javac and JVM --add-opens= flags. "_java_toolchain_type": attr.label(default = semantics.JAVA_TOOLCHAIN_TYPE), }, ) - -java_library = rule( - _proxy, - doc = """ -

This rule compiles and links sources into a .jar file.

- -

Implicit outputs

-
    -
  • libname.jar: A Java archive containing the class files.
  • -
  • libname-src.jar: An archive containing the sources ("source - jar").
  • -
- """, - attrs = JAVA_LIBRARY_ATTRS, - provides = [JavaInfo], - outputs = { - "classjar": "lib%{name}.jar", - "sourcejar": "lib%{name}-src.jar", - }, - fragments = ["java", "cpp"], - toolchains = [semantics.JAVA_TOOLCHAIN], - subrules = [android_lint_subrule], -) diff --git a/java/common/rules/java_package_configuration.bzl b/java/common/rules/java_package_configuration.bzl index 32e3abd1..1f766d07 100644 --- a/java/common/rules/java_package_configuration.bzl +++ b/java/common/rules/java_package_configuration.bzl @@ -15,7 +15,7 @@ """Implementation for the java_package_configuration rule""" load("//java/common:java_common.bzl", "java_common") -load(":java_helper.bzl", "helper") +load("//java/common/rules/impl:java_helper.bzl", "helper") visibility(["//java/..."]) diff --git a/java/common/rules/java_plugin.bzl b/java/common/rules/java_plugin.bzl index 4dbf4e90..571fdff2 100644 --- a/java/common/rules/java_plugin.bzl +++ b/java/common/rules/java_plugin.bzl @@ -16,106 +16,11 @@ Definition of java_plugin rule. """ -load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") -load("//java/common:java_semantics.bzl", "semantics") -load(":android_lint.bzl", "android_lint_subrule") -load(":basic_java_library.bzl", "basic_java_library", "construct_defaultinfo") -load(":java_library.bzl", "JAVA_LIBRARY_ATTRS", "JAVA_LIBRARY_IMPLICIT_ATTRS") +load(":java_library.bzl", "JAVA_LIBRARY_ATTRS") load(":rule_util.bzl", "merge_attrs") visibility(["//java/..."]) -def bazel_java_plugin_rule( - ctx, - srcs = [], - data = [], - generates_api = False, - processor_class = "", - deps = [], - plugins = [], - resources = [], - javacopts = [], - neverlink = False, - proguard_specs = [], - add_exports = [], - add_opens = []): - """Implements java_plugin rule. - - Use this call when you need to produce a fully fledged java_plugin from - another rule's implementation. - - Args: - ctx: (RuleContext) Used to register the actions. - srcs: (list[File]) The list of source files that are processed to create the target. - data: (list[File]) The list of files needed by this plugin at runtime. - generates_api: (bool) This attribute marks annotation processors that generate API code. - processor_class: (str) The processor class is the fully qualified type of - the class that the Java compiler should use as entry point to the annotation processor. - deps: (list[Target]) The list of other libraries to be linked in to the target. - plugins: (list[Target]) Java compiler plugins to run at compile-time. - resources: (list[File]) A list of data files to include in a Java jar. - javacopts: (list[str]) Extra compiler options for this library. - neverlink: (bool) Whether this library should only be used for compilation and not at runtime. - proguard_specs: (list[File]) Files to be used as Proguard specification. - add_exports: (list[str]) Allow this library to access the given /. - add_opens: (list[str]) Allow this library to reflectively access the given /. - Returns: - (list[provider]) A list containing DefaultInfo, JavaInfo, - InstrumentedFilesInfo, OutputGroupsInfo, ProguardSpecProvider providers. - """ - target, base_info = basic_java_library( - ctx, - srcs, - deps, - [], # runtime_deps - plugins, - [], # exports - [], # exported_plugins - resources, - [], # resource_jars - [], # classpath_resources - javacopts, - neverlink, - proguard_specs = proguard_specs, - add_exports = add_exports, - add_opens = add_opens, - ) - java_info = target.pop("JavaInfo") - - # Replace JavaInfo with JavaPluginInfo - target["JavaPluginInfo"] = JavaPluginInfo( - runtime_deps = [java_info], - processor_class = processor_class if processor_class else None, # ignore empty string (default) - data = data, - generates_api = generates_api, - ) - target["DefaultInfo"] = construct_defaultinfo( - ctx, - base_info.files_to_build, - base_info.runfiles, - neverlink, - ) - target["OutputGroupInfo"] = OutputGroupInfo(**base_info.output_groups) - - return target - -def _proxy(ctx): - return bazel_java_plugin_rule( - ctx, - ctx.files.srcs, - ctx.files.data, - ctx.attr.generates_api, - ctx.attr.processor_class, - ctx.attr.deps, - ctx.attr.plugins, - ctx.files.resources, - ctx.attr.javacopts, - ctx.attr.neverlink, - ctx.files.proguard_specs, - ctx.attr.add_exports, - ctx.attr.add_opens, - ).values() - JAVA_PLUGIN_ATTRS = merge_attrs( JAVA_LIBRARY_ATTRS, { @@ -145,41 +50,3 @@ java.util.ServiceLoader.) }, remove_attrs = ["runtime_deps", "exports", "exported_plugins"], ) - -JAVA_PLUGIN_IMPLICIT_ATTRS = JAVA_LIBRARY_IMPLICIT_ATTRS - -java_plugin = rule( - _proxy, - doc = """ -

- java_plugin defines plugins for the Java compiler run by Bazel. The - only supported kind of plugins are annotation processors. A java_library or - java_binary rule can run plugins by depending on them via the plugins - attribute. A java_library can also automatically export plugins to libraries that - directly depend on it using - exported_plugins. -

- -

Implicit output targets

-
    -
  • libname.jar: A Java archive.
  • -
- -

- Arguments are identical to java_library, except - for the addition of the processor_class argument. -

- """, - attrs = merge_attrs( - JAVA_PLUGIN_ATTRS, - JAVA_PLUGIN_IMPLICIT_ATTRS, - ), - provides = [JavaPluginInfo], - outputs = { - "classjar": "lib%{name}.jar", - "sourcejar": "lib%{name}-src.jar", - }, - fragments = ["java", "cpp"], - toolchains = [semantics.JAVA_TOOLCHAIN], - subrules = [android_lint_subrule], -) diff --git a/java/common/rules/java_runtime.bzl b/java/common/rules/java_runtime.bzl index 0876639c..7991d5ed 100644 --- a/java/common/rules/java_runtime.bzl +++ b/java/common/rules/java_runtime.bzl @@ -19,7 +19,7 @@ Definition of java_runtime rule and JavaRuntimeInfo provider. load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_semantics.bzl", "PLATFORMS_ROOT") -load(":java_helper.bzl", "helper") +load("//java/common/rules/impl:java_helper.bzl", "helper") visibility(["//java/..."]) diff --git a/java/common/rules/java_toolchain.bzl b/java/common/rules/java_toolchain.bzl index 8e0f5837..5a9cb87f 100644 --- a/java/common/rules/java_toolchain.bzl +++ b/java/common/rules/java_toolchain.bzl @@ -17,7 +17,7 @@ Definition of java_toolchain rule and JavaToolchainInfo provider. """ load("//java/common:java_semantics.bzl", "semantics") -load(":java_helper.bzl", "helper") +load("//java/common/rules/impl:java_helper.bzl", "helper") load(":java_package_configuration.bzl", "JavaPackageConfigurationInfo") load(":java_runtime.bzl", "JavaRuntimeInfo") From e40342e2f929ca44f3401e54ff298e7b822fd010 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 12 Sep 2024 04:34:23 -0700 Subject: [PATCH 021/465] Add missing `bzl_library` and test filegroups PiperOrigin-RevId: 673788851 Change-Id: Ibe81809a76f0f038f022d50aa42ec359aa734594 --- java/bazel/BUILD.bazel | 6 +++++ java/bazel/common/BUILD.bazel | 6 +++++ java/bazel/common/empty.bzl | 1 + java/common/BUILD | 1 + java/common/rules/BUILD | 48 +++++++++++++++++++++++++++++++++++ 5 files changed, 62 insertions(+) create mode 100644 java/bazel/common/BUILD.bazel create mode 100644 java/bazel/common/empty.bzl diff --git a/java/bazel/BUILD.bazel b/java/bazel/BUILD.bazel index 1db01d36..c3abda26 100644 --- a/java/bazel/BUILD.bazel +++ b/java/bazel/BUILD.bazel @@ -53,3 +53,9 @@ done <<< '{configs}' >> $@ ], visibility = ["//visibility:private"], ) + +filegroup( + name = "for_bazel_tests", + testonly = 1, + visibility = ["//java:__pkg__"], +) diff --git a/java/bazel/common/BUILD.bazel b/java/bazel/common/BUILD.bazel new file mode 100644 index 00000000..c0237707 --- /dev/null +++ b/java/bazel/common/BUILD.bazel @@ -0,0 +1,6 @@ +load("@bazel_skylib//:bzl_library.bzl", "bzl_library") + +bzl_library( + name = "common", + srcs = glob(["*.bzl"]), +) diff --git a/java/bazel/common/empty.bzl b/java/bazel/common/empty.bzl new file mode 100644 index 00000000..c40e750a --- /dev/null +++ b/java/bazel/common/empty.bzl @@ -0,0 +1 @@ +"""Placeholder for glob""" diff --git a/java/common/BUILD b/java/common/BUILD index e8b08c0e..d8f22f7b 100644 --- a/java/common/BUILD +++ b/java/common/BUILD @@ -25,6 +25,7 @@ filegroup( srcs = [ "BUILD", ":common", + "//java/common/rules:for_bazel_tests", ], visibility = ["//java:__pkg__"], ) diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD index 5031de89..5bbc94ed 100644 --- a/java/common/rules/BUILD +++ b/java/common/rules/BUILD @@ -1,3 +1,5 @@ +load("@bazel_skylib//:bzl_library.bzl", "bzl_library") + package(default_visibility = ["//visibility:public"]) filegroup( @@ -7,3 +9,49 @@ filegroup( ], visibility = ["//java/common:__pkg__"], ) + +bzl_library( + name = "android_lint_bzl", + srcs = ["android_lint.bzl"], + visibility = ["//visibility:private"], +) + +bzl_library( + name = "rule_util_bzl", + srcs = ["rule_util.bzl"], + visibility = ["//visibility:private"], +) + +bzl_library( + name = "core_rules", + srcs = [ + "basic_java_library.bzl", + "java_binary.bzl", + "java_binary_wrapper.bzl", + "java_import.bzl", + "java_library.bzl", + "java_plugin.bzl", + "java_toolchain.bzl", + ], + visibility = [ + "//java:__pkg__", + ], + deps = [ + ":android_lint_bzl", + ":rule_util_bzl", + # TODO: re-enable after rules_cc release + # "@rules_cc//cc/common", + "//java/common", + "@bazel_skylib//lib:paths", + ], +) + +filegroup( + name = "for_bazel_tests", + testonly = 1, + srcs = [ + "BUILD", + ":core_rules", + ], + visibility = ["//java/common:__pkg__"], +) From 421c6558595d34111005a2ec913ae3e7fd9c3dd0 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 12 Sep 2024 05:42:00 -0700 Subject: [PATCH 022/465] Fix usage of `paths.get_relative` that was defined in `@_builtins` only PiperOrigin-RevId: 673806805 Change-Id: Iae4cd555837cd483984be296f457e5442df92d75 --- java/common/rules/impl/java_helper.bzl | 8 +++++++- java/common/rules/java_runtime.bzl | 12 ++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/java/common/rules/impl/java_helper.bzl b/java/common/rules/impl/java_helper.bzl index 82897db6..c8190750 100644 --- a/java/common/rules/impl/java_helper.bzl +++ b/java/common/rules/impl/java_helper.bzl @@ -94,7 +94,7 @@ def _primary_class(ctx): for src in ctx.files.srcs: if src.basename == main: return _full_classname(_strip_extension(src)) - return _full_classname(paths.get_relative(ctx.label.package, ctx.label.name)) + return _full_classname(_get_relative(ctx.label.package, ctx.label.name)) def _strip_extension(file): return file.dirname + "/" + ( @@ -445,6 +445,11 @@ def _is_stamping_enabled(ctx, stamp): # stamp == -1 / auto return int(ctx.configuration.stamp_binaries()) +def _get_relative(path_a, path_b): + if paths.is_absolute(path_b): + return path_b + return paths.normalize(paths.join(path_a, path_b)) + helper = struct( collect_all_targets_as_deps = _collect_all_targets_as_deps, filter_launcher_for_target = _filter_launcher_for_target, @@ -471,4 +476,5 @@ helper = struct( detokenize_javacopts = _detokenize_javacopts, derive_output_file = _derive_output_file, is_stamping_enabled = _is_stamping_enabled, + get_relative = _get_relative, ) diff --git a/java/common/rules/java_runtime.bzl b/java/common/rules/java_runtime.bzl index 7991d5ed..43cb7c62 100644 --- a/java/common/rules/java_runtime.bzl +++ b/java/common/rules/java_runtime.bzl @@ -60,7 +60,7 @@ def _default_java_home(label): if _is_main_repo(label): return label.package else: - return paths.get_relative(label.workspace_root, label.package) + return helper.get_relative(label.workspace_root, label.package) def _get_bin_java(ctx): is_windows = helper.is_target_platform_windows(ctx) @@ -68,10 +68,10 @@ def _get_bin_java(ctx): def _get_runfiles_java_executable(ctx, java_home, label): if paths.is_absolute(java_home) or _is_main_repo(label): - return paths.get_relative(java_home, _get_bin_java(ctx)) + return helper.get_relative(java_home, _get_bin_java(ctx)) else: - repo_runfiles_path = "" if _is_main_repo(label) else paths.get_relative("..", label.workspace_name) - return paths.get_relative(repo_runfiles_path, _get_bin_java(ctx)) + repo_runfiles_path = "" if _is_main_repo(label) else helper.get_relative("..", label.workspace_name) + return helper.get_relative(repo_runfiles_path, _get_bin_java(ctx)) def _is_java_binary(path): return path.endswith("bin/java") or path.endswith("bin/java.exe") @@ -94,9 +94,9 @@ def _java_runtime_rule_impl(ctx): java_home_attr = ctx.expand_make_variables("java_home", ctx.attr.java_home, {}) if ctx.files.srcs and paths.is_absolute(java_home_attr): fail("'java_home' with an absolute path requires 'srcs' to be empty.") - java_home = paths.get_relative(java_home, java_home_attr) + java_home = helper.get_relative(java_home, java_home_attr) - java_binary_exec_path = paths.get_relative(java_home, _get_bin_java(ctx)) + java_binary_exec_path = helper.get_relative(java_home, _get_bin_java(ctx)) java_binary_runfiles_path = _get_runfiles_java_executable(ctx, java_home, ctx.label) java = ctx.file.java From 70970af9590a49b310312b2d01e85ac4fb72fff7 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 12 Sep 2024 07:57:23 -0700 Subject: [PATCH 023/465] Switch `rules_java` rule macro redirects from `native.*` to those defined locally Using the rules requires a bazel version that contains all the changes in https://github.com/bazelbuild/bazel/pull/23591 PiperOrigin-RevId: 673847088 Change-Id: Iaaf824fbae4dced297baa6a336b2e7b8b6c3ccb5 --- .bazelci/presubmit.yml | 74 +++++++++++---------- .bazelrc | 6 +- MODULE.bazel | 10 ++- java/BUILD | 5 ++ java/bazel/BUILD.bazel | 6 ++ java/bazel/common/BUILD.bazel | 7 ++ java/common/rules/BUILD | 4 +- java/common/rules/impl/BUILD | 18 +++++ java/common/rules/impl/java_binary_impl.bzl | 2 +- java/java_binary.bzl | 5 +- java/java_import.bzl | 5 +- java/java_library.bzl | 5 +- java/java_plugin.bzl | 5 +- java/java_test.bzl | 5 +- test/repo/.bazelrc | 7 ++ test/repo/BUILD.bazel | 8 ++- test/repo/MODULE.bazel | 39 +++++++++++ test/repo/WORKSPACE.bzlmod | 5 -- 18 files changed, 159 insertions(+), 57 deletions(-) create mode 100644 test/repo/.bazelrc diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 1a493180..179245e5 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -21,11 +21,17 @@ test_targets: &test_targets buildifier: latest tasks: +# TODO: add config for 8.0.0 once released +# Bazel 7.x +# TODO: fix versions after 7.4.0 ubuntu2004: + name: "Bazel 7.x" + bazel: "9e3fa2a2e98db4aa10918a981325cfa9473e4ed8" build_targets: *build_targets test_targets: *test_targets ubuntu2004_integration: - name: "Integration Tests" + name: "Bazel 7.x Integration" + bazel: "9e3fa2a2e98db4aa10918a981325cfa9473e4ed8" platform: ubuntu2004 working_directory: "test/repo" shell_commands: @@ -35,14 +41,30 @@ tasks: - "//:bin_deploy.jar" - "@rules_java//java/..." macos: + name: "Bazel 7.x" + bazel: "9e3fa2a2e98db4aa10918a981325cfa9473e4ed8" build_targets: *build_targets windows: + name: "Bazel 7.x" + bazel: "9e3fa2a2e98db4aa10918a981325cfa9473e4ed8" build_targets: *build_targets +# Bazel@HEAD ubuntu2004_head: name: "Bazel@HEAD" bazel: last_green platform: ubuntu2004 build_targets: *build_targets + ubuntu2004_integration_head: + name: "Bazel@HEAD Integration" + bazel: last_green + platform: ubuntu2004 + working_directory: "test/repo" + shell_commands: + - sh setup.sh + build_targets: + - "//..." + - "//:bin_deploy.jar" + - "@rules_java//java/..." macos_head: name: "Bazel@HEAD" bazel: last_green @@ -53,36 +75,20 @@ tasks: bazel: last_green platform: windows build_targets: *build_targets - ubuntu2004_bzlmod: - name: "bzlmod" - platform: ubuntu2004 - build_flags: - - "--config=bzlmod" - build_targets: *build_targets_bzlmod - macos_bzlmod: - name: "bzlmod" - platform: macos - build_flags: - - "--config=bzlmod" - build_targets: *build_targets_bzlmod - windows_bzlmod: - name: "bzlmod" - platform: windows - build_flags: - - "--config=bzlmod" - build_targets: *build_targets_bzlmod - ubuntu2004_bazel630: - name: "Bazel 6.3.0" - bazel: 6.3.0 - platform: ubuntu2004 - build_targets: *build_targets - macos_bazel630: - name: "Bazel 6.3.0" - bazel: 6.3.0 - platform: macos - build_targets: *build_targets - windows_bazel630: - name: "Bazel 6.3.0" - bazel: 6.3.0 - platform: windows - build_targets: *build_targets +# Bazel 6.x +# TODO: re-enable if possible to redirect to native rule impl +# ubuntu2004_bazel630: +# name: "Bazel 6.3.0" +# bazel: 6.3.0 +# platform: ubuntu2004 +# build_targets: *build_targets +# macos_bazel630: +# name: "Bazel 6.3.0" +# bazel: 6.3.0 +# platform: macos +# build_targets: *build_targets +# windows_bazel630: +# name: "Bazel 6.3.0" +# bazel: 6.3.0 +# platform: windows +# build_targets: *build_targets diff --git a/.bazelrc b/.bazelrc index 5d84eb8f..03c47778 100644 --- a/.bazelrc +++ b/.bazelrc @@ -1,3 +1,5 @@ -build:bzlmod --experimental_enable_bzlmod +common --incompatible_disallow_empty_glob +common --experimental_rule_extension_api -common --incompatible_disallow_empty_glob \ No newline at end of file +# TODO: remove once https://github.com/bazelbuild/bazel/commit/384e381fa841537987691f170ed9408dcfeed2ea is available +common --experimental_google_legacy_api diff --git a/MODULE.bazel b/MODULE.bazel index f66bbd18..42fffc53 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -11,7 +11,7 @@ bazel_dep(name = "bazel_features", version = "1.11.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") # Required by @remote_java_tools, which is loaded via module extension. -bazel_dep(name = "rules_proto", version = "4.0.0") +bazel_dep(name = "rules_proto", version = "6.0.2") bazel_dep(name = "rules_license", version = "0.0.3") bazel_dep(name = "abseil-cpp", version = "20230802.1", repo_name = "com_google_absl") @@ -97,3 +97,11 @@ single_version_override( module_name = "rules_python", version = "0.24.0", ) + +# TODO: drop this & update version from BCR above +archive_override( + module_name = "rules_cc", + integrity = "sha256-ZvxtrlaB2jZk56tUDasvs4b1ThcPMaEa64u+MZSwf1E=", + strip_prefix = "rules_cc-0.0.10-rc2", + urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.10-rc2/rules_cc-0.0.10-rc2.tar.gz"], +) diff --git a/java/BUILD b/java/BUILD index 77848c92..5660699f 100644 --- a/java/BUILD +++ b/java/BUILD @@ -7,6 +7,8 @@ licenses(["notice"]) filegroup( name = "srcs", srcs = glob(["**"]) + [ + "//java/bazel:srcs", + "//java/bazel/common:srcs", "//java/bazel/rules:srcs", "//java/common:srcs", "//java/private:srcs", @@ -39,8 +41,10 @@ bzl_library( ], visibility = ["//visibility:public"], deps = [ + "//java/bazel/common", # copybara-use-repo-external-label "//java/bazel/rules", # copybara-use-repo-external-label "//java/common", + "//java/common/rules:core_rules", "//java/private", ], ) @@ -66,6 +70,7 @@ filegroup( ":core_rules", ":java_single_jar", ":rules", + "//java/bazel:for_bazel_tests", # copybara-use-repo-external-label "//java/bazel/rules:for_bazel_tests", # copybara-use-repo-external-label "//java/common:for_bazel_tests", "//java/private:for_bazel_tests", diff --git a/java/bazel/BUILD.bazel b/java/bazel/BUILD.bazel index c3abda26..21bd34c7 100644 --- a/java/bazel/BUILD.bazel +++ b/java/bazel/BUILD.bazel @@ -59,3 +59,9 @@ filegroup( testonly = 1, visibility = ["//java:__pkg__"], ) + +filegroup( + name = "srcs", + srcs = glob(["**"]), + visibility = ["//java:__pkg__"], +) diff --git a/java/bazel/common/BUILD.bazel b/java/bazel/common/BUILD.bazel index c0237707..dd3bc064 100644 --- a/java/bazel/common/BUILD.bazel +++ b/java/bazel/common/BUILD.bazel @@ -3,4 +3,11 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") bzl_library( name = "common", srcs = glob(["*.bzl"]), + visibility = ["//java:__pkg__"], +) + +filegroup( + name = "srcs", + srcs = glob(["**"]), + visibility = ["//java:__pkg__"], ) diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD index 5bbc94ed..33f6eca9 100644 --- a/java/common/rules/BUILD +++ b/java/common/rules/BUILD @@ -39,10 +39,9 @@ bzl_library( deps = [ ":android_lint_bzl", ":rule_util_bzl", - # TODO: re-enable after rules_cc release - # "@rules_cc//cc/common", "//java/common", "@bazel_skylib//lib:paths", + "@rules_cc//cc/common", ], ) @@ -52,6 +51,7 @@ filegroup( srcs = [ "BUILD", ":core_rules", + "//java/common/rules/impl:for_bazel_tests", ], visibility = ["//java/common:__pkg__"], ) diff --git a/java/common/rules/impl/BUILD b/java/common/rules/impl/BUILD index e755396a..f9c86267 100644 --- a/java/common/rules/impl/BUILD +++ b/java/common/rules/impl/BUILD @@ -1,3 +1,5 @@ +load("@bazel_skylib//:bzl_library.bzl", "bzl_library") + package(default_visibility = ["//visibility:public"]) filegroup( @@ -5,3 +7,19 @@ filegroup( srcs = glob(["**"]), visibility = ["//java/common/rules:__pkg__"], ) + +bzl_library( + name = "impl", + srcs = glob(["*.bzl"]), + visibility = ["//java:__subpackages__"], +) + +filegroup( + name = "for_bazel_tests", + testonly = 1, + srcs = [ + "BUILD", + ":impl", + ], + visibility = ["//java/common/rules:__pkg__"], +) diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl index 03f2cbe2..dd402c78 100644 --- a/java/common/rules/impl/java_binary_impl.bzl +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -16,11 +16,11 @@ load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") +load("@rules_proto//proto:defs.bzl", "ProtoInfo") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") load("//java/common/rules/impl:basic_java_library_impl.bzl", "basic_java_library", "collect_deps") -load("//third_party/protobuf/bazel/common:proto_info.bzl", "ProtoInfo") load(":java_binary_deploy_jar.bzl", "create_deploy_archive") load(":java_helper.bzl", "helper") diff --git a/java/java_binary.bzl b/java/java_binary.bzl index 7184ecbd..18a3fed4 100644 --- a/java/java_binary.bzl +++ b/java/java_binary.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_binary rule""" +load("//java/bazel/rules:bazel_java_binary_wrapper.bzl", _java_binary = "java_binary") + def java_binary(**attrs): """Bazel java_binary rule. @@ -22,5 +24,4 @@ def java_binary(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_binary(**attrs) + _java_binary(**attrs) diff --git a/java/java_import.bzl b/java/java_import.bzl index 926c37a6..89f60309 100644 --- a/java/java_import.bzl +++ b/java/java_import.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_import rule""" +load("//java/bazel/rules:bazel_java_import.bzl", _java_import = "java_import") + def java_import(**attrs): """Bazel java_import rule. @@ -22,5 +24,4 @@ def java_import(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_import(**attrs) + _java_import(**attrs) diff --git a/java/java_library.bzl b/java/java_library.bzl index 9308bbc4..90c72676 100644 --- a/java/java_library.bzl +++ b/java/java_library.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_library rule""" +load("//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") + def java_library(**attrs): """Bazel java_library rule. @@ -22,5 +24,4 @@ def java_library(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_library(**attrs) + _java_library(**attrs) diff --git a/java/java_plugin.bzl b/java/java_plugin.bzl index d12e0e18..130dc625 100644 --- a/java/java_plugin.bzl +++ b/java/java_plugin.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_plugin rule""" +load("//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") + def java_plugin(**attrs): """Bazel java_plugin rule. @@ -22,5 +24,4 @@ def java_plugin(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_plugin(**attrs) + _java_plugin(**attrs) diff --git a/java/java_test.bzl b/java/java_test.bzl index 0aeac91b..48a66551 100644 --- a/java/java_test.bzl +++ b/java/java_test.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_test rule""" +load("//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") + def java_test(**attrs): """Bazel java_test rule. @@ -22,5 +24,4 @@ def java_test(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_test(**attrs) + _java_test(**attrs) diff --git a/test/repo/.bazelrc b/test/repo/.bazelrc new file mode 100644 index 00000000..1146197f --- /dev/null +++ b/test/repo/.bazelrc @@ -0,0 +1,7 @@ +build:bzlmod --experimental_enable_bzlmod + +common --incompatible_disallow_empty_glob +common --experimental_rule_extension_api + +# TODO: remove once https://github.com/bazelbuild/bazel/commit/384e381fa841537987691f170ed9408dcfeed2ea is available +common --experimental_google_legacy_api diff --git a/test/repo/BUILD.bazel b/test/repo/BUILD.bazel index 1e71e527..6b7da400 100644 --- a/test/repo/BUILD.bazel +++ b/test/repo/BUILD.bazel @@ -1,5 +1,5 @@ -load("@rules_java//java:java_binary.bzl", "java_binary") # copybara-use-repo-external-label -load("@rules_java//java:java_library.bzl", "java_library") # copybara-use-repo-external-label +load("@rules_java//java:defs.bzl", "java_binary", "java_library") # copybara-use-repo-external-label +load("@rules_java//toolchains:default_java_toolchain.bzl", "default_java_toolchain") # copybara-use-repo-external-label java_library( name = "lib", @@ -11,3 +11,7 @@ java_binary( main_class = "Main", runtime_deps = [":lib"], ) + +default_java_toolchain( + name = "my_funky_toolchain", +) diff --git a/test/repo/MODULE.bazel b/test/repo/MODULE.bazel index 9289fcd5..c4f81a40 100644 --- a/test/repo/MODULE.bazel +++ b/test/repo/MODULE.bazel @@ -5,3 +5,42 @@ archive_override( module_name = "rules_java", urls = ["file:///tmp/rules_java-HEAD.tar.gz"], ) + +java_toolchains = use_extension("@rules_java//java:extensions.bzl", "toolchains") +use_repo( + java_toolchains, + "local_jdk", + "remote_java_tools", + "remote_java_tools_darwin_arm64", + "remote_java_tools_darwin_x86_64", + "remote_java_tools_linux", + "remote_java_tools_windows", + "remotejdk11_linux", + "remotejdk11_linux_aarch64", + "remotejdk11_linux_ppc64le", + "remotejdk11_linux_s390x", + "remotejdk11_macos", + "remotejdk11_macos_aarch64", + "remotejdk11_win", + "remotejdk11_win_arm64", + "remotejdk17_linux", + "remotejdk17_linux_s390x", + "remotejdk17_macos", + "remotejdk17_macos_aarch64", + "remotejdk17_win", + "remotejdk17_win_arm64", + "remotejdk21_linux", + "remotejdk21_macos", + "remotejdk21_macos_aarch64", + "remotejdk21_win", +) + +# TODO: drop this & update version from BCR above +archive_override( + module_name = "rules_cc", + integrity = "sha256-ZvxtrlaB2jZk56tUDasvs4b1ThcPMaEa64u+MZSwf1E=", + strip_prefix = "rules_cc-0.0.10-rc2", + urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.10-rc2/rules_cc-0.0.10-rc2.tar.gz"], +) + +register_toolchains("//:all") diff --git a/test/repo/WORKSPACE.bzlmod b/test/repo/WORKSPACE.bzlmod index 67a41c3f..e69de29b 100644 --- a/test/repo/WORKSPACE.bzlmod +++ b/test/repo/WORKSPACE.bzlmod @@ -1,5 +0,0 @@ -load("@rules_java//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchains") - -rules_java_dependencies() - -rules_java_toolchains() From 8b21e59767169534bb50f08577807dfff5493286 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 12 Sep 2024 12:02:51 -0700 Subject: [PATCH 024/465] Fix target visibility for `@rules_java//java/common/rules:core_rules` PiperOrigin-RevId: 673945918 Change-Id: I9e52c5a477805bd5aafe0a2d7ff1add65f77d2b3 --- java/common/rules/BUILD | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD index 33f6eca9..ae2cae78 100644 --- a/java/common/rules/BUILD +++ b/java/common/rules/BUILD @@ -34,7 +34,7 @@ bzl_library( "java_toolchain.bzl", ], visibility = [ - "//java:__pkg__", + "//java:__subpackages__", ], deps = [ ":android_lint_bzl", From 0612db715fddf072a194619a81922d54a3152a69 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 17 Sep 2024 07:24:28 -0700 Subject: [PATCH 025/465] Update to released `rules_cc` dependency from BCR in `rules_java` PiperOrigin-RevId: 675557975 Change-Id: I40e6604fcffffaae744f3d7c9f6a5dcb80940d1b --- MODULE.bazel | 10 +--------- java/common/rules/BUILD | 1 + test/repo/MODULE.bazel | 8 -------- 3 files changed, 2 insertions(+), 17 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 42fffc53..66037a6e 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -6,7 +6,7 @@ module( ) bazel_dep(name = "platforms", version = "0.0.4") -bazel_dep(name = "rules_cc", version = "0.0.2") +bazel_dep(name = "rules_cc", version = "0.0.10") bazel_dep(name = "bazel_features", version = "1.11.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") @@ -97,11 +97,3 @@ single_version_override( module_name = "rules_python", version = "0.24.0", ) - -# TODO: drop this & update version from BCR above -archive_override( - module_name = "rules_cc", - integrity = "sha256-ZvxtrlaB2jZk56tUDasvs4b1ThcPMaEa64u+MZSwf1E=", - strip_prefix = "rules_cc-0.0.10-rc2", - urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.10-rc2/rules_cc-0.0.10-rc2.tar.gz"], -) diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD index ae2cae78..b5532dc0 100644 --- a/java/common/rules/BUILD +++ b/java/common/rules/BUILD @@ -52,6 +52,7 @@ filegroup( "BUILD", ":core_rules", "//java/common/rules/impl:for_bazel_tests", + "@rules_cc//cc/private/rules_impl:srcs", ], visibility = ["//java/common:__pkg__"], ) diff --git a/test/repo/MODULE.bazel b/test/repo/MODULE.bazel index c4f81a40..c9729b4d 100644 --- a/test/repo/MODULE.bazel +++ b/test/repo/MODULE.bazel @@ -35,12 +35,4 @@ use_repo( "remotejdk21_win", ) -# TODO: drop this & update version from BCR above -archive_override( - module_name = "rules_cc", - integrity = "sha256-ZvxtrlaB2jZk56tUDasvs4b1ThcPMaEa64u+MZSwf1E=", - strip_prefix = "rules_cc-0.0.10-rc2", - urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.10-rc2/rules_cc-0.0.10-rc2.tar.gz"], -) - register_toolchains("//:all") From de933f3c2455e67f9ad1c97df052b9859730483e Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 18 Sep 2024 03:13:58 -0700 Subject: [PATCH 026/465] Clean up internal references in rules_java and fix test deps PiperOrigin-RevId: 675918045 Change-Id: Ie6a6983240320de62c0a916c5fc51040288dc163 --- java/BUILD | 1 + java/common/rules/android_lint.bzl | 6 +---- java/common/rules/impl/java_binary_impl.bzl | 30 +++++++++------------ 3 files changed, 14 insertions(+), 23 deletions(-) diff --git a/java/BUILD b/java/BUILD index 5660699f..62875608 100644 --- a/java/BUILD +++ b/java/BUILD @@ -75,6 +75,7 @@ filegroup( "//java/common:for_bazel_tests", "//java/private:for_bazel_tests", "//java/toolchains:for_bazel_tests", + "@bazel_skylib//lib:test_deps", ], visibility = ["//visibility:public"], ) diff --git a/java/common/rules/android_lint.bzl b/java/common/rules/android_lint.bzl index 4c96c16e..7fd8d430 100644 --- a/java/common/rules/android_lint.bzl +++ b/java/common/rules/android_lint.bzl @@ -14,11 +14,7 @@ """Creates the android lint action for java rules""" -load( - "//java/common:java_semantics.bzl", - "semantics", - _semantics_tokenize_javacopts = "tokenize_javacopts", -) +load("//java/common:java_semantics.bzl", "semantics", _semantics_tokenize_javacopts = "tokenize_javacopts") visibility(["//java/..."]) diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl index dd402c78..cbf72c19 100644 --- a/java/common/rules/impl/java_binary_impl.bzl +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -53,7 +53,7 @@ def basic_java_binary( launcher_info, executable, strip_as_default, - extension_registry_provider = None, + extra_java_info = None, is_test_rule_class = False): """Creates actions for compiling and linting java sources, coverage support, and sources jar (_deploy-src.jar). @@ -68,7 +68,7 @@ def basic_java_binary( launcher_info: (Struct) Structure with fields (launcher, unstripped_launcher, runfiles, runtime_jars, jvm_flags, classpath_resources) executable: (File) The executable output of the rule strip_as_default: (bool) Whether this target outputs a stripped launcher and deploy jar - extension_registry_provider: (GeneratedExtensionRegistryProvider) internal param, do not use + extra_java_info: (JavaInfo) additional outputs to merge is_test_rule_class: (bool) Whether this rule is a test rule Returns: @@ -131,18 +131,12 @@ def basic_java_binary( ) ], ) - if extension_registry_provider: - runtime_classpath = depset(order = "preorder", direct = [extension_registry_provider.class_jar], transitive = [runtime_classpath]) - java_info = java_common.merge( - [ - java_info, - JavaInfo( - output_jar = extension_registry_provider.class_jar, - compile_jar = None, - source_jar = extension_registry_provider.src_jar, - ), - ], - ) + if extra_java_info: + runtime_classpath = depset(order = "preorder", transitive = [ + extra_java_info.transitive_runtime_jars, + runtime_classpath, + ]) + java_info = java_common.merge([java_info, extra_java_info]) compilation_info = JavaCompilationInfo( compilation_classpath = compilation_info.compilation_classpath, runtime_classpath = runtime_classpath, @@ -192,13 +186,13 @@ def basic_java_binary( _generate_coverage_manifest(ctx, coverage_config.manifest, java_attrs.runtime_classpath) files_to_build.append(coverage_config.manifest) - if extension_registry_provider: - files_to_build.append(extension_registry_provider.class_jar) + if extra_java_info: + files_to_build.extend(extra_java_info.runtime_output_jars) output_groups["_direct_source_jars"] = ( - output_groups["_direct_source_jars"] + [extension_registry_provider.src_jar] + output_groups["_direct_source_jars"] + extra_java_info.source_jars ) output_groups["_source_jars"] = depset( - direct = [extension_registry_provider.src_jar], + direct = extra_java_info.source_jars, transitive = [output_groups["_source_jars"]], ) From 84d712c2d4c737628ee7376579565dc9fdfd18e5 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Wed, 18 Sep 2024 07:09:26 -0700 Subject: [PATCH 027/465] Update JDK 21 binaries Copybara Import from https://github.com/bazelbuild/rules_java/pull/223 BEGIN_PUBLIC Update JDK 21 binaries (#223) Also switch to Zulu for Windows ARM64. Closes #223 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/223 from fmeum:update-21 317efb24b1579d510096cda87c622dbbfe93bdad PiperOrigin-RevId: 675977860 Change-Id: I4c80be97f4e3530725ba26e9374d0352bed08cf9 --- java/bazel/BUILD.bazel | 2 +- java/bazel/repositories_util.bzl | 13 ++----- java/repositories.bzl | 60 ++++++++++++++++---------------- test/check_remote_jdk_configs.sh | 8 ++--- 4 files changed, 38 insertions(+), 45 deletions(-) diff --git a/java/bazel/BUILD.bazel b/java/bazel/BUILD.bazel index 21bd34c7..b5ddea9e 100644 --- a/java/bazel/BUILD.bazel +++ b/java/bazel/BUILD.bazel @@ -13,7 +13,7 @@ # limitations under the License. load(":repositories_util.bzl", "FLAT_CONFIGS") -# run this to generate _REMOTE_JDK_CONFIGS_LIST in repositories.bzl +# build this to generate _REMOTE_JDK_CONFIGS_LIST in repositories.bzl # this downloads all the jdks and computes their sha256 sum, so can take a while # TODO(hvd): make this a sh_binary to update the configs in place genrule( diff --git a/java/bazel/repositories_util.bzl b/java/bazel/repositories_util.bzl index d895fc28..7e9efbd2 100644 --- a/java/bazel/repositories_util.bzl +++ b/java/bazel/repositories_util.bzl @@ -72,31 +72,24 @@ _RELEASE_CONFIGS = { }, "21": { "zulu": { - "release": "21.34.19-ca-jdk21.0.3", + "release": "21.36.17-ca-jdk21.0.4", "platforms": { "linux": ["aarch64", "x86_64"], "macos": ["aarch64", "x86_64"], - "windows": ["x86_64"], + "windows": ["arm64", "x86_64"], }, }, "adoptium": { - "release": "21.0.2+13", + "release": "21.0.4+7", "platforms": { "linux": ["ppc", "s390x"], }, }, - "microsoft": { - "release": "21.0.0", - "platforms": { - "windows": ["arm64"], - }, - }, }, } _STRIP_PREFIX_OVERRIDES = { "remotejdk11_win_arm64": "jdk-11.0.13+8", - "remotejdk21_win_arm64": "jdk-21+35", } def _name_for_remote_jdk(version, os, cpu): diff --git a/java/repositories.bzl b/java/repositories.bzl index c8156bd4..37a0d31d 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -74,7 +74,7 @@ def local_jdk_repo(): ) # DO NOT MANUALLY UPDATE! Update java/bazel/repositories_util.bzl instead and -# run the java/bazel:dump_remote_jdk_configs target to generate this list +# build the java/bazel:dump_remote_jdk_configs target to generate this list _REMOTE_JDK_CONFIGS_LIST = [ struct( name = "remote_jdk8_linux_aarch64", @@ -255,65 +255,65 @@ _REMOTE_JDK_CONFIGS_LIST = [ struct( name = "remotejdk21_linux_aarch64", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"], - sha256 = "c898d4ce365c8926e22859c06be4a81bafb9fd0126088867e15a528fe99b1599", - strip_prefix = "zulu21.34.19-ca-jdk21.0.3-linux_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu21.34.19-ca-jdk21.0.3-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.34.19-ca-jdk21.0.3-linux_aarch64.tar.gz"], + sha256 = "da3c2d7db33670bcf66532441aeb7f33dcf0d227c8dafe7ce35cee67f6829c4c", + strip_prefix = "zulu21.36.17-ca-jdk21.0.4-linux_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-linux_aarch64.tar.gz"], version = "21", ), struct( name = "remotejdk21_linux", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"], - sha256 = "ca763d1308a6bcc768382f160733a08e591d5f595a7dd9e51b60d27d54828dcc", - strip_prefix = "zulu21.34.19-ca-jdk21.0.3-linux_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu21.34.19-ca-jdk21.0.3-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.34.19-ca-jdk21.0.3-linux_x64.tar.gz"], + sha256 = "318d0c2ed3c876fb7ea2c952945cdcf7decfb5264ca51aece159e635ac53d544", + strip_prefix = "zulu21.36.17-ca-jdk21.0.4-linux_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-linux_x64.tar.gz"], version = "21", ), struct( name = "remotejdk21_macos_aarch64", target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"], - sha256 = "4f42a561909d71868a700cf2efa1390e1b9e04863f3fa75ea30c4965e5a702f0", - strip_prefix = "zulu21.34.19-ca-jdk21.0.3-macosx_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu21.34.19-ca-jdk21.0.3-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.34.19-ca-jdk21.0.3-macosx_aarch64.tar.gz"], + sha256 = "bc2750f81a166cc6e9c30ae8aaba54f253a8c8ec9d8cfc04a555fe20712c7bff", + strip_prefix = "zulu21.36.17-ca-jdk21.0.4-macosx_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-macosx_aarch64.tar.gz"], version = "21", ), struct( name = "remotejdk21_macos", target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"], - sha256 = "148006a220a18922d7a9c52ac0bad099c5b4e60334a8d02b11f8c945e9ec9a34", - strip_prefix = "zulu21.34.19-ca-jdk21.0.3-macosx_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu21.34.19-ca-jdk21.0.3-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.34.19-ca-jdk21.0.3-macosx_x64.tar.gz"], + sha256 = "5ce75a6a247c7029b74c4ca7cf6f60fd2b2d68ce1e8956fb448d2984316b5fea", + strip_prefix = "zulu21.36.17-ca-jdk21.0.4-macosx_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-macosx_x64.tar.gz"], + version = "21", + ), + struct( + name = "remotejdk21_win_arm64", + target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"], + sha256 = "9f873eccf030b1d3dc879ec1eb0ff5e11bf76002dc81c5c644c3462bf6c5146b", + strip_prefix = "zulu21.36.17-ca-jdk21.0.4-win_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-win_aarch64.zip"], version = "21", ), struct( name = "remotejdk21_win", target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"], - sha256 = "fb9f0dc6a484b0b169b3b3a3c2425d5f62bebfd15cb06c1597e33f77959c72af", - strip_prefix = "zulu21.34.19-ca-jdk21.0.3-win_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu21.34.19-ca-jdk21.0.3-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.34.19-ca-jdk21.0.3-win_x64.zip"], + sha256 = "d771dad10d3f0b440c3686d1f3d2b68b320802ac97b212d87671af3f2eef8848", + strip_prefix = "zulu21.36.17-ca-jdk21.0.4-win_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-win_x64.zip"], version = "21", ), struct( name = "remotejdk21_linux_ppc64le", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc"], - sha256 = "d08de863499d8851811c893e8915828f2cd8eb67ed9e29432a6b4e222d80a12f", - strip_prefix = "jdk-21.0.2+13", - urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.2+13/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.2_13.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.2+13/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.2_13.tar.gz"], + sha256 = "c208cd0fb90560644a90f928667d2f53bfe408c957a5e36206585ad874427761", + strip_prefix = "jdk-21.0.4+7", + urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.4_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.4_7.tar.gz"], version = "21", ), struct( name = "remotejdk21_linux_s390x", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:s390x"], - sha256 = "0d5676c50821e0d0b951bf3ffd717e7a13be2a89d8848a5c13b4aedc6f982c78", - strip_prefix = "jdk-21.0.2+13", - urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.2+13/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.2_13.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.2+13/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.2_13.tar.gz"], - version = "21", - ), - struct( - name = "remotejdk21_win_arm64", - target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"], - sha256 = "975603e684f2ec5a525b3b5336d6aa0b09b5b7d2d0d9e271bd6a9892ad550181", - strip_prefix = "jdk-21+35", - urls = ["https://aka.ms/download-jdk/microsoft-jdk-21.0.0-windows-aarch64.zip", "https://mirror.bazel.build/aka.ms/download-jdk/microsoft-jdk-21.0.0-windows-aarch64.zip"], + sha256 = "c900c8d64fab1e53274974fa4a4c736a5a3754485a5c56f4947281480773658a", + strip_prefix = "jdk-21.0.4+7", + urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.4_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.4_7.tar.gz"], version = "21", ), ] diff --git a/test/check_remote_jdk_configs.sh b/test/check_remote_jdk_configs.sh index ab42ba11..1b58c96d 100755 --- a/test/check_remote_jdk_configs.sh +++ b/test/check_remote_jdk_configs.sh @@ -21,15 +21,15 @@ for config in "$@"; do IFS=, read -r name url mirror_url hash strip_prefix <<< "${config}" echo "fetching $name from $url to ${TMP_FILE}" curl --silent -o ${TMP_FILE} -L "$url" - actual_hash=`sha256sum ${TMP_FILE} | cut -d' ' -f1` + actual_hash=$(sha256sum ${TMP_FILE} | cut -d' ' -f1) if [ "${hash}" != "${actual_hash}" ]; then echo "ERROR: wrong hash for ${name}! wanted: ${hash}, got: ${actual_hash}" exit 1 fi if [[ -z "${url##*.tar.gz}" ]]; then - root_dir=`tar ztf ${TMP_FILE} --exclude='*/*'` + root_dir=$(tar ztf ${TMP_FILE} --exclude='*/*') elif [[ -z "${url##*.zip}" ]]; then - root_dir=`unzip -Z1 ${TMP_FILE} | head -n1` + root_dir=$(unzip -Z1 ${TMP_FILE} | head -n1) else echo "ERROR: unexpected archive type for ${name}" exit 1 @@ -40,7 +40,7 @@ for config in "$@"; do fi if [[ -n "${mirror_url}" ]]; then echo "checking mirror: ${mirror_url}" - curl --silent --fail -I -L ${mirror_url} > /dev/null || { _MISSING_MIRRORS+="${mirror_url}"; } + curl --silent --fail -I -L ${mirror_url} > /dev/null || { _MISSING_MIRRORS+=("${mirror_url}"); } fi done From 84cd7a393cb48c415219440b4bf79eb90931cb36 Mon Sep 17 00:00:00 2001 From: Googler Date: Sun, 22 Sep 2024 21:51:31 -0700 Subject: [PATCH 028/465] BEGIN_PUBLIC Update one version allowlist flag END_PUBLIC See b/366268295 Startblock: * unknown commit is submitted * unknown commit is submitted PiperOrigin-RevId: 677621922 Change-Id: I04315c0b9730ef1e894f07bbb35a866eba730607 --- java/common/rules/impl/java_binary_impl.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl index cbf72c19..8d7e2ef9 100644 --- a/java/common/rules/impl/java_binary_impl.bzl +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -343,7 +343,7 @@ def _create_one_version_check(ctx, inputs, is_test_rule_class): one_version_inputs = [] args.add("--output", output) if allowlist: - args.add("--whitelist", allowlist) + args.add("--allowlist", allowlist) one_version_inputs.append(allowlist) if one_version_level == "WARNING": args.add("--succeed_on_found_violations") From e4d1f09aeb143d20a21008793cb46d4b91c8005c Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 23 Sep 2024 01:08:26 -0700 Subject: [PATCH 029/465] Partial rollback of commit 70970af9590a49b310312b2d01e85ac4fb72fff7. *** Reason for rollback *** The rules aren't ready to be used with any Bazel version other than HEAD. Unblocks https://github.com/bazelbuild/bazel/pull/23649 *** Original change description *** Switch `rules_java` rule macro redirects from `native.*` to those defined locally Using the rules requires a bazel version that contains all the changes in https://github.com/bazelbuild/bazel/pull/23591 PiperOrigin-RevId: 677675846 Change-Id: Ibfd5d59e1dbfa04b0f0d5117493662d06f40f557 --- java/java_binary.bzl | 5 ++--- java/java_import.bzl | 5 ++--- java/java_library.bzl | 5 ++--- java/java_plugin.bzl | 5 ++--- java/java_test.bzl | 5 ++--- 5 files changed, 10 insertions(+), 15 deletions(-) diff --git a/java/java_binary.bzl b/java/java_binary.bzl index 18a3fed4..7184ecbd 100644 --- a/java/java_binary.bzl +++ b/java/java_binary.bzl @@ -13,8 +13,6 @@ # limitations under the License. """java_binary rule""" -load("//java/bazel/rules:bazel_java_binary_wrapper.bzl", _java_binary = "java_binary") - def java_binary(**attrs): """Bazel java_binary rule. @@ -24,4 +22,5 @@ def java_binary(**attrs): **attrs: Rule attributes """ - _java_binary(**attrs) + # buildifier: disable=native-java + native.java_binary(**attrs) diff --git a/java/java_import.bzl b/java/java_import.bzl index 89f60309..926c37a6 100644 --- a/java/java_import.bzl +++ b/java/java_import.bzl @@ -13,8 +13,6 @@ # limitations under the License. """java_import rule""" -load("//java/bazel/rules:bazel_java_import.bzl", _java_import = "java_import") - def java_import(**attrs): """Bazel java_import rule. @@ -24,4 +22,5 @@ def java_import(**attrs): **attrs: Rule attributes """ - _java_import(**attrs) + # buildifier: disable=native-java + native.java_import(**attrs) diff --git a/java/java_library.bzl b/java/java_library.bzl index 90c72676..9308bbc4 100644 --- a/java/java_library.bzl +++ b/java/java_library.bzl @@ -13,8 +13,6 @@ # limitations under the License. """java_library rule""" -load("//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") - def java_library(**attrs): """Bazel java_library rule. @@ -24,4 +22,5 @@ def java_library(**attrs): **attrs: Rule attributes """ - _java_library(**attrs) + # buildifier: disable=native-java + native.java_library(**attrs) diff --git a/java/java_plugin.bzl b/java/java_plugin.bzl index 130dc625..d12e0e18 100644 --- a/java/java_plugin.bzl +++ b/java/java_plugin.bzl @@ -13,8 +13,6 @@ # limitations under the License. """java_plugin rule""" -load("//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") - def java_plugin(**attrs): """Bazel java_plugin rule. @@ -24,4 +22,5 @@ def java_plugin(**attrs): **attrs: Rule attributes """ - _java_plugin(**attrs) + # buildifier: disable=native-java + native.java_plugin(**attrs) diff --git a/java/java_test.bzl b/java/java_test.bzl index 48a66551..0aeac91b 100644 --- a/java/java_test.bzl +++ b/java/java_test.bzl @@ -13,8 +13,6 @@ # limitations under the License. """java_test rule""" -load("//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") - def java_test(**attrs): """Bazel java_test rule. @@ -24,4 +22,5 @@ def java_test(**attrs): **attrs: Rule attributes """ - _java_test(**attrs) + # buildifier: disable=native-java + native.java_test(**attrs) From 203ec0236cc6d0c260f76b0fb04b09507f7aa443 Mon Sep 17 00:00:00 2001 From: hvadehra Date: Mon, 23 Sep 2024 05:07:02 -0700 Subject: [PATCH 030/465] Add initial rule docs Initial support for generating them and keeping them in sync. A lot of links need to be fixed since the docs currently assume they are part of the build encyclopedia. Will fix all that in a follow up. Copybara Import from https://github.com/bazelbuild/rules_java/pull/224 BEGIN_PUBLIC Add initial rule docs (#224) Closes #224 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/224 from bazelbuild:hvd_docs 0782c46b60b17a0604770a43f3ff9035c32088e6 PiperOrigin-RevId: 677744490 Change-Id: I4bf451cd05fe1838dcec3b3987c62fb134bc0e3f --- MODULE.bazel | 1 + java/bazel/rules/BUILD.bazel | 14 +- java/bazel/rules/bazel_java_binary.bzl | 2 +- java/bazel/rules/bazel_java_import.bzl | 2 +- java/bazel/rules/bazel_java_test.bzl | 2 +- java/common/rules/BUILD | 14 +- java/docs/BUILD.bazel | 39 ++ java/docs/rule.vm | 20 + java/docs/rules.bzl | 22 + java/docs/rules.md | 588 +++++++++++++++++++++++++ test/BUILD.bazel | 14 + 11 files changed, 713 insertions(+), 5 deletions(-) create mode 100644 java/docs/BUILD.bazel create mode 100644 java/docs/rule.vm create mode 100644 java/docs/rules.bzl create mode 100644 java/docs/rules.md diff --git a/MODULE.bazel b/MODULE.bazel index 66037a6e..5c757789 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -9,6 +9,7 @@ bazel_dep(name = "platforms", version = "0.0.4") bazel_dep(name = "rules_cc", version = "0.0.10") bazel_dep(name = "bazel_features", version = "1.11.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") +bazel_dep(name = "stardoc", version = "0.7.1") # Required by @remote_java_tools, which is loaded via module extension. bazel_dep(name = "rules_proto", version = "6.0.2") diff --git a/java/bazel/rules/BUILD.bazel b/java/bazel/rules/BUILD.bazel index 74e1fa5a..ba3ca917 100644 --- a/java/bazel/rules/BUILD.bazel +++ b/java/bazel/rules/BUILD.bazel @@ -22,7 +22,19 @@ filegroup( bzl_library( name = "rules", srcs = glob(["*.bzl"]), - visibility = ["//java:__pkg__"], + visibility = [ + "//java:__pkg__", + "//java/docs:__pkg__", + ], + deps = [ + "//java/common", + "//java/common/rules:core_rules", + "//java/common/rules/impl", + "@bazel_skylib//lib:paths", + "@rules_cc//cc:find_cc_toolchain_bzl", + "@rules_cc//cc/common", + "@rules_proto//proto:defs", + ], ) filegroup( diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl index f3680c12..1cb7c7ad 100644 --- a/java/bazel/rules/bazel_java_binary.bzl +++ b/java/bazel/rules/bazel_java_binary.bzl @@ -27,7 +27,7 @@ load("//java/common/rules/impl:java_binary_deploy_jar.bzl", "create_deploy_archi load("//java/common/rules/impl:java_binary_impl.bzl", "basic_java_binary") load("//java/common/rules/impl:java_helper.bzl", "helper") -visibility("private") +visibility("//java/docs") def _bazel_java_binary_impl(ctx): return bazel_base_binary_impl(ctx, is_test_rule_class = False) + helper.executable_providers(ctx) diff --git a/java/bazel/rules/bazel_java_import.bzl b/java/bazel/rules/bazel_java_import.bzl index 02951d52..98a040b6 100644 --- a/java/bazel/rules/bazel_java_import.bzl +++ b/java/bazel/rules/bazel_java_import.bzl @@ -21,7 +21,7 @@ load("//java/common:java_semantics.bzl", "semantics") load("//java/common/rules:java_import.bzl", "JAVA_IMPORT_ATTRS") load("//java/common/rules/impl:bazel_java_import_impl.bzl", "bazel_java_import_rule") -visibility(["//java"]) +visibility(["//java", "//java/docs"]) def _proxy(ctx): return bazel_java_import_rule( diff --git a/java/bazel/rules/bazel_java_test.bzl b/java/bazel/rules/bazel_java_test.bzl index a019b867..543b0276 100644 --- a/java/bazel/rules/bazel_java_test.bzl +++ b/java/bazel/rules/bazel_java_test.bzl @@ -19,7 +19,7 @@ load("//java/common/rules:rule_util.bzl", "merge_attrs") load("//java/common/rules/impl:java_helper.bzl", "helper") load(":bazel_java_binary.bzl", "BASE_BINARY_ATTRS", "bazel_base_binary_impl", "make_binary_rule") -visibility(["//java"]) +visibility(["//java", "//java/docs"]) def _bazel_java_test_impl(ctx): return bazel_base_binary_impl(ctx, is_test_rule_class = True) + helper.test_providers(ctx) diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD index b5532dc0..4ffe015d 100644 --- a/java/common/rules/BUILD +++ b/java/common/rules/BUILD @@ -31,7 +31,6 @@ bzl_library( "java_import.bzl", "java_library.bzl", "java_plugin.bzl", - "java_toolchain.bzl", ], visibility = [ "//java:__subpackages__", @@ -45,12 +44,25 @@ bzl_library( ], ) +bzl_library( + name = "toolchain_rules", + srcs = [ + "java_package_configuration.bzl", + "java_runtime.bzl", + "java_toolchain.bzl", + ], + visibility = [ + "//java:__subpackages__", + ], +) + filegroup( name = "for_bazel_tests", testonly = 1, srcs = [ "BUILD", ":core_rules", + ":toolchain_rules", "//java/common/rules/impl:for_bazel_tests", "@rules_cc//cc/private/rules_impl:srcs", ], diff --git a/java/docs/BUILD.bazel b/java/docs/BUILD.bazel new file mode 100644 index 00000000..63793251 --- /dev/null +++ b/java/docs/BUILD.bazel @@ -0,0 +1,39 @@ +load("@bazel_skylib//:bzl_library.bzl", "bzl_library") +load("@stardoc//stardoc:stardoc.bzl", "stardoc") + +exports_files( + ["rules.md"], + visibility = ["//test:__pkg__"], +) + +bzl_library( + name = "rules_bzl", + srcs = ["rules.bzl"], + deps = [ + "//java/bazel/rules", + "//java/common/rules:toolchain_rules", + ], +) + +stardoc( + name = "rule_docs", + out = "rules_docs.out", + input = "rules.bzl", + rule_template = ":rule.vm", + symbol_names = [ + # core rules + "java_binary", + "java_import", + "java_library", + "java_plugin", + "java_test", + + # toolchain rules + "java_package_configuration", + "java_runtime", + "java_toolchain", + ], + table_of_contents_template = "@stardoc//stardoc:templates/markdown_tables/table_of_contents.vm", + visibility = ["//test:__pkg__"], + deps = [":rules_bzl"], +) diff --git a/java/docs/rule.vm b/java/docs/rule.vm new file mode 100644 index 00000000..dd89fdf8 --- /dev/null +++ b/java/docs/rule.vm @@ -0,0 +1,20 @@ + + +#[[##]]# ${ruleName} + +
+${util.ruleSummary($ruleName, $ruleInfo)}
+
+ +${ruleInfo.docString} + +**ATTRIBUTES** + +#if (!$ruleInfo.getAttributeList().isEmpty()) + +| Name | Description | Type | Mandatory | Default | +| :------------- | :------------- | :------------- | :------------- | :------------- | +#foreach ($attribute in $ruleInfo.getAttributeList()) +| $attribute.name | #if(!$attribute.docString.isEmpty()) ${util.markdownCellFormat($attribute.docString)} #else - #end | ${util.attributeTypeString($attribute)} | ${util.mandatoryString($attribute)} | #if(!$attribute.defaultValue.isEmpty()) ${util.markdownCodeSpan($attribute.defaultValue)} #end | +#end +#end \ No newline at end of file diff --git a/java/docs/rules.bzl b/java/docs/rules.bzl new file mode 100644 index 00000000..fa6c3dd8 --- /dev/null +++ b/java/docs/rules.bzl @@ -0,0 +1,22 @@ +"""Java rules""" + +load("//java/bazel/rules:bazel_java_binary.bzl", _java_binary = "java_binary") +load("//java/bazel/rules:bazel_java_import.bzl", _java_import = "java_import") +load("//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") +load("//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") +load("//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") +load("//java/common/rules:java_package_configuration.bzl", _java_package_configuration = "java_package_configuration") +load("//java/common/rules:java_runtime.bzl", _java_runtime = "java_runtime") +load("//java/common/rules:java_toolchain.bzl", _java_toolchain = "java_toolchain") + +visibility("private") + +java_binary = _java_binary +java_import = _java_import +java_library = _java_library +java_plugin = _java_plugin +java_test = _java_test + +java_package_configuration = _java_package_configuration +java_runtime = _java_runtime +java_toolchain = _java_toolchain diff --git a/java/docs/rules.md b/java/docs/rules.md new file mode 100644 index 00000000..f241f1b2 --- /dev/null +++ b/java/docs/rules.md @@ -0,0 +1,588 @@ + + +Java rules + + +## Rules + +- [java_binary](#java_binary) +- [java_import](#java_import) +- [java_library](#java_library) +- [java_package_configuration](#java_package_configuration) +- [java_plugin](#java_plugin) +- [java_runtime](#java_runtime) +- [java_test](#java_test) +- [java_toolchain](#java_toolchain) + + + + +## java_binary + +
+java_binary(name, deps, srcs, data, resources, add_exports, add_opens, bootclasspath,
+            classpath_resources, create_executable, deploy_env, deploy_manifest_lines, env, javacopts,
+            jvm_flags, launcher, licenses, main_class, neverlink, plugins, resource_strip_prefix,
+            runtime_deps, stamp, use_launcher, use_testrunner)
+
+ +

+ Builds a Java archive ("jar file"), plus a wrapper shell script with the same name as the rule. + The wrapper shell script uses a classpath that includes, among other things, a jar file for each + library on which the binary depends. When running the wrapper shell script, any nonempty + JAVABIN environment variable will take precedence over the version specified via + Bazel's --java_runtime_version flag. +

+

+ The wrapper script accepts several unique flags. Refer to + //src/main/java/com/google/devtools/build/lib/bazel/rules/java/java_stub_template.txt + for a list of configurable flags and environment variables accepted by the wrapper. +

+ +

Implicit output targets

+
    +
  • name.jar: A Java archive, containing the class files and other + resources corresponding to the binary's direct dependencies.
  • +
  • name-src.jar: An archive containing the sources ("source + jar").
  • +
  • name_deploy.jar: A Java archive suitable for deployment (only + built if explicitly requested). +

    + Building the <name>_deploy.jar target for your rule + creates a self-contained jar file with a manifest that allows it to be run with the + java -jar command or with the wrapper script's --singlejar + option. Using the wrapper script is preferred to java -jar because it + also passes the JVM flags and the options + to load native libraries. +

    +

    + The deploy jar contains all the classes that would be found by a classloader that + searched the classpath from the binary's wrapper script from beginning to end. It also + contains the native libraries needed for dependencies. These are automatically loaded + into the JVM at runtime. +

    +

    If your target specifies a launcher + attribute, then instead of being a normal JAR file, the _deploy.jar will be a + native binary. This will contain the launcher plus any native (C++) dependencies of + your rule, all linked into a static binary. The actual jar file's bytes will be + appended to that native binary, creating a single binary blob containing both the + executable and the Java code. You can execute the resulting jar file directly + like you would execute any native binary.

    +
  • +
  • name_deploy-src.jar: An archive containing the sources + collected from the transitive closure of the target. These will match the classes in the + deploy.jar except where jars have no matching source jar.
  • +
+ +

+It is good practice to use the name of the source file that is the main entry point of the +application (minus the extension). For example, if your entry point is called +Main.java, then your name could be Main. +

+ +

+ A deps attribute is not allowed in a java_binary rule without + srcs; such a rule requires a + main_class provided by + runtime_deps. +

+ +

The following code snippet illustrates a common mistake:

+ +
+
+java_binary(
+    name = "DontDoThis",
+    srcs = [
+        ...,
+        "GeneratedJavaFile.java",  # a generated .java file
+    ],
+    deps = [":generating_rule",],  # rule that generates that file
+)
+
+
+ +

Do this instead:

+ +
+
+java_binary(
+    name = "DoThisInstead",
+    srcs = [
+        ...,
+        ":generating_rule",
+    ],
+)
+
+
+ +**ATTRIBUTES** + + +| Name | Description | Type | Mandatory | Default | +| :------------- | :------------- | :------------- | :------------- | :------------- | +| name | A unique name for this target. | Name | required | | +| deps | The list of other libraries to be linked in to the target. See general comments about deps at Typical attributes defined by most build rules. | List of labels | optional | `[]` | +| srcs | The list of source files that are processed to create the target. This attribute is almost always required; see exceptions below.

Source files of type .java are compiled. In case of generated .java files it is generally advisable to put the generating rule's name here instead of the name of the file itself. This not only improves readability but makes the rule more resilient to future changes: if the generating rule generates different files in the future, you only need to fix one place: the outs of the generating rule. You should not list the generating rule in deps because it is a no-op.

Source files of type .srcjar are unpacked and compiled. (This is useful if you need to generate a set of .java files with a genrule.)

Rules: if the rule (typically genrule or filegroup) generates any of the files listed above, they will be used the same way as described for source files.



This argument is almost always required, except if a main_class attribute specifies a class on the runtime classpath or you specify the runtime_deps argument.

| List of labels | optional | `[]` | +| data | The list of files needed by this library at runtime. See general comments about data at Typical attributes defined by most build rules. | List of labels | optional | `[]` | +| resources | A list of data files to include in a Java jar.

Resources may be source files or generated files.



If resources are specified, they will be bundled in the jar along with the usual .class files produced by compilation. The location of the resources inside of the jar file is determined by the project structure. Bazel first looks for Maven's standard directory layout, (a "src" directory followed by a "resources" directory grandchild). If that is not found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for example, if a resource is at <workspace root>/x/java/y/java/z, the path of the resource will be y/java/z. This heuristic cannot be overridden, however, the resource_strip_prefix attribute can be used to specify a specific alternative directory for resource files. | List of labels | optional | `[]` | +| add_exports | Allow this library to access the given module or package.

This corresponds to the javac and JVM --add-exports= flags. | List of strings | optional | `[]` | +| add_opens | Allow this library to reflectively access the given module or package.

This corresponds to the javac and JVM --add-opens= flags. | List of strings | optional | `[]` | +| bootclasspath | Restricted API, do not use! | Label | optional | `None` | +| classpath_resources | DO NOT USE THIS OPTION UNLESS THERE IS NO OTHER WAY)

A list of resources that must be located at the root of the java tree. This attribute's only purpose is to support third-party libraries that require that their resources be found on the classpath as exactly "myconfig.xml". It is only allowed on binaries and not libraries, due to the danger of namespace conflicts.

| List of labels | optional | `[]` | +| create_executable | Deprecated, use java_single_jar instead. | Boolean | optional | `True` | +| deploy_env | A list of other java_binary targets which represent the deployment environment for this binary. Set this attribute when building a plugin which will be loaded by another java_binary.
Setting this attribute excludes all dependencies from the runtime classpath (and the deploy jar) of this binary that are shared between this binary and the targets specified in deploy_env. | List of labels | optional | `[]` | +| deploy_manifest_lines | A list of lines to add to the META-INF/manifest.mf file generated for the *_deploy.jar target. The contents of this attribute are not subject to "Make variable" substitution. | List of strings | optional | `[]` | +| env | - | Dictionary: String -> String | optional | `{}` | +| javacopts | Extra compiler options for this binary. Subject to "Make variable" substitution and Bourne shell tokenization.

These compiler options are passed to javac after the global compiler options.

| List of strings | optional | `[]` | +| jvm_flags | A list of flags to embed in the wrapper script generated for running this binary. Subject to $(location) and "Make variable" substitution, and Bourne shell tokenization.

The wrapper script for a Java binary includes a CLASSPATH definition (to find all the dependent jars) and invokes the right Java interpreter. The command line generated by the wrapper script includes the name of the main class followed by a "$@" so you can pass along other arguments after the classname. However, arguments intended for parsing by the JVM must be specified before the classname on the command line. The contents of jvm_flags are added to the wrapper script before the classname is listed.



Note that this attribute has no effect on *_deploy.jar outputs.

| List of strings | optional | `[]` | +| launcher | Specify a binary that will be used to run your Java program instead of the normal bin/java program included with the JDK. The target must be a cc_binary. Any cc_binary that implements the Java Invocation API can be specified as a value for this attribute.

By default, Bazel will use the normal JDK launcher (bin/java or java.exe).



The related --java_launcher Bazel flag affects only those java_binary and java_test targets that have not specified a launcher attribute.



Note that your native (C++, SWIG, JNI) dependencies will be built differently depending on whether you are using the JDK launcher or another launcher:



  • If you are using the normal JDK launcher (the default), native dependencies are built as a shared library named {name}_nativedeps.so, where {name} is the name attribute of this java_binary rule. Unused code is not removed by the linker in this configuration.


  • If you are using any other launcher, native (C++) dependencies are statically linked into a binary named {name}_nativedeps, where {name} is the name attribute of this java_binary rule. In this case, the linker will remove any code it thinks is unused from the resulting binary, which means any C++ code accessed only via JNI may not be linked in unless that cc_library target specifies alwayslink = 1.


When using any launcher other than the default JDK launcher, the format of the *_deploy.jar output changes. See the main java_binary docs for details.

| Label | optional | `None` | +| licenses | - | List of strings | optional | `[]` | +| main_class | Name of class with main() method to use as entry point. If a rule uses this option, it does not need a srcs=[...] list. Thus, with this attribute one can make an executable from a Java library that already contains one or more main() methods.

The value of this attribute is a class name, not a source file. The class must be available at runtime: it may be compiled by this rule (from srcs) or provided by direct or transitive dependencies (through runtime_deps or deps). If the class is unavailable, the binary will fail at runtime; there is no build-time check.

| String | optional | `""` | +| neverlink | - | Boolean | optional | `False` | +| plugins | Java compiler plugins to run at compile-time. Every java_plugin specified in this attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use exported_plugins. Resources generated by the plugin will be included in the resulting jar of this rule. | List of labels | optional | `[]` | +| resource_strip_prefix | The path prefix to strip from Java resources.

If specified, this path prefix is stripped from every file in the resources attribute. It is an error for a resource file not to be under this directory. If not specified (the default), the path of resource file is determined according to the same logic as the Java package of source files. For example, a source file at stuff/java/foo/bar/a.txt will be located at foo/bar/a.txt.

| String | optional | `""` | +| runtime_deps | Libraries to make available to the final binary or test at runtime only. Like ordinary deps, these will appear on the runtime classpath, but unlike them, not on the compile-time classpath. Dependencies needed only at runtime should be listed here. Dependency-analysis tools should ignore targets that appear in both runtime_deps and deps. | List of labels | optional | `[]` | +| stamp | Whether to encode build information into the binary. Possible values:
  • stamp = 1: Always stamp the build information into the binary, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the binary and any downstream actions that depend on it.
  • stamp = 0: Always replace build information by constant values. This gives good build result caching.
  • stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.

Stamped binaries are not rebuilt unless their dependencies change.

| Integer | optional | `-1` | +| use_launcher | Whether the binary should use a custom launcher.

If this attribute is set to false, the launcher attribute and the related --java_launcher flag will be ignored for this target. | Boolean | optional | `True` | +| use_testrunner | Use the test runner (by default com.google.testing.junit.runner.BazelTestRunner) class as the main entry point for a Java program, and provide the test class to the test runner as a value of bazel.test_suite system property.


You can use this to override the default behavior, which is to use test runner for java_test rules, and not use it for java_binary rules. It is unlikely you will want to do this. One use is for AllTest rules that are invoked by another rule (to set up a database before running the tests, for example). The AllTest rule must be declared as a java_binary, but should still use the test runner as its main entry point.

The name of a test runner class can be overridden with main_class attribute. | Boolean | optional | `False` | + + + + +## java_import + +

+java_import(name, deps, data, add_exports, add_opens, constraints, exports, jars, licenses,
+            neverlink, proguard_specs, runtime_deps, srcjar)
+
+ +

+ This rule allows the use of precompiled .jar files as + libraries for java_library and + java_binary rules. +

+ +

Examples

+ +
+
+    java_import(
+        name = "maven_model",
+        jars = [
+            "maven_model/maven-aether-provider-3.2.3.jar",
+            "maven_model/maven-model-3.2.3.jar",
+            "maven_model/maven-model-builder-3.2.3.jar",
+        ],
+    )
+
+
+ +**ATTRIBUTES** + + +| Name | Description | Type | Mandatory | Default | +| :------------- | :------------- | :------------- | :------------- | :------------- | +| name | A unique name for this target. | Name | required | | +| deps | The list of other libraries to be linked in to the target. See java_library.deps. | List of labels | optional | `[]` | +| data | The list of files needed by this rule at runtime. | List of labels | optional | `[]` | +| add_exports | Allow this library to access the given module or package.

This corresponds to the javac and JVM --add-exports= flags. | List of strings | optional | `[]` | +| add_opens | Allow this library to reflectively access the given module or package.

This corresponds to the javac and JVM --add-opens= flags. | List of strings | optional | `[]` | +| constraints | Extra constraints imposed on this rule as a Java library. | List of strings | optional | `[]` | +| exports | Targets to make available to users of this rule. See java_library.exports. | List of labels | optional | `[]` | +| jars | The list of JAR files provided to Java targets that depend on this target. | List of labels | required | | +| licenses | - | List of strings | optional | `[]` | +| neverlink | Only use this library for compilation and not at runtime. Useful if the library will be provided by the runtime environment during execution. Examples of libraries like this are IDE APIs for IDE plug-ins or tools.jar for anything running on a standard JDK. | Boolean | optional | `False` | +| proguard_specs | Files to be used as Proguard specification. These will describe the set of specifications to be used by Proguard. If specified, they will be added to any android_binary target depending on this library.

The files included here must only have idempotent rules, namely -dontnote, -dontwarn, assumenosideeffects, and rules that start with -keep. Other options can only appear in android_binary's proguard_specs, to ensure non-tautological merges. | List of labels | optional | `[]` | +| runtime_deps | Libraries to make available to the final binary or test at runtime only. See java_library.runtime_deps. | List of labels | optional | `[]` | +| srcjar | A JAR file that contains source code for the compiled JAR files. | Label | optional | `None` | + + + + +## java_library + +

+java_library(name, deps, srcs, data, resources, add_exports, add_opens, bootclasspath,
+             exported_plugins, exports, javabuilder_jvm_flags, javacopts, licenses, neverlink,
+             plugins, proguard_specs, resource_strip_prefix, runtime_deps)
+
+ +

This rule compiles and links sources into a .jar file.

+ +

Implicit outputs

+
    +
  • libname.jar: A Java archive containing the class files.
  • +
  • libname-src.jar: An archive containing the sources ("source + jar").
  • +
+ +**ATTRIBUTES** + + +| Name | Description | Type | Mandatory | Default | +| :------------- | :------------- | :------------- | :------------- | :------------- | +| name | A unique name for this target. | Name | required | | +| deps | The list of libraries to link into this library. See general comments about deps at Typical attributes defined by most build rules.

The jars built by java_library rules listed in deps will be on the compile-time classpath of this rule. Furthermore the transitive closure of their deps, runtime_deps and exports will be on the runtime classpath.

By contrast, targets in the data attribute are included in the runfiles but on neither the compile-time nor runtime classpath.

| List of labels | optional | `[]` | +| srcs | The list of source files that are processed to create the target. This attribute is almost always required; see exceptions below.

Source files of type .java are compiled. In case of generated .java files it is generally advisable to put the generating rule's name here instead of the name of the file itself. This not only improves readability but makes the rule more resilient to future changes: if the generating rule generates different files in the future, you only need to fix one place: the outs of the generating rule. You should not list the generating rule in deps because it is a no-op.

Source files of type .srcjar are unpacked and compiled. (This is useful if you need to generate a set of .java files with a genrule.)

Rules: if the rule (typically genrule or filegroup) generates any of the files listed above, they will be used the same way as described for source files.

Source files of type .properties are treated as resources.



All other files are ignored, as long as there is at least one file of a file type described above. Otherwise an error is raised.



This argument is almost always required, except if you specify the runtime_deps argument.

| List of labels | optional | `[]` | +| data | The list of files needed by this library at runtime. See general comments about data at Typical attributes defined by most build rules.

When building a java_library, Bazel doesn't put these files anywhere; if the data files are generated files then Bazel generates them. When building a test that depends on this java_library Bazel copies or links the data files into the runfiles area.

| List of labels | optional | `[]` | +| resources | A list of data files to include in a Java jar.

Resources may be source files or generated files.



If resources are specified, they will be bundled in the jar along with the usual .class files produced by compilation. The location of the resources inside of the jar file is determined by the project structure. Bazel first looks for Maven's standard directory layout, (a "src" directory followed by a "resources" directory grandchild). If that is not found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for example, if a resource is at <workspace root>/x/java/y/java/z, the path of the resource will be y/java/z. This heuristic cannot be overridden, however, the resource_strip_prefix attribute can be used to specify a specific alternative directory for resource files. | List of labels | optional | `[]` | +| add_exports | Allow this library to access the given module or package.

This corresponds to the javac and JVM --add-exports= flags. | List of strings | optional | `[]` | +| add_opens | Allow this library to reflectively access the given module or package.

This corresponds to the javac and JVM --add-opens= flags. | List of strings | optional | `[]` | +| bootclasspath | Restricted API, do not use! | Label | optional | `None` | +| exported_plugins | The list of java_plugins (e.g. annotation processors) to export to libraries that directly depend on this library.

The specified list of java_plugins will be applied to any library which directly depends on this library, just as if that library had explicitly declared these labels in plugins.

| List of labels | optional | `[]` | +| exports | Exported libraries.

Listing rules here will make them available to parent rules, as if the parents explicitly depended on these rules. This is not true for regular (non-exported) deps.

Summary: a rule X can access the code in Y if there exists a dependency path between them that begins with a deps edge followed by zero or more exports edges. Let's see some examples to illustrate this.

Assume A depends on B and B depends on C. In this case C is a transitive dependency of A, so changing C's sources and rebuilding A will correctly rebuild everything. However A will not be able to use classes in C. To allow that, either A has to declare C in its deps, or B can make it easier for A (and anything that may depend on A) by declaring C in its (B's) exports attribute.

The closure of exported libraries is available to all direct parent rules. Take a slightly different example: A depends on B, B depends on C and D, and also exports C but not D. Now A has access to C but not to D. Now, if C and D exported some libraries, C' and D' respectively, A could only access C' but not D'.

Important: an exported rule is not a regular dependency. Sticking to the previous example, if B exports C and wants to also use C, it has to also list it in its own deps.

| List of labels | optional | `[]` | +| javabuilder_jvm_flags | Restricted API, do not use! | List of strings | optional | `[]` | +| javacopts | Extra compiler options for this library. Subject to "Make variable" substitution and Bourne shell tokenization.

These compiler options are passed to javac after the global compiler options.

| List of strings | optional | `[]` | +| licenses | - | List of strings | optional | `[]` | +| neverlink | Whether this library should only be used for compilation and not at runtime. Useful if the library will be provided by the runtime environment during execution. Examples of such libraries are the IDE APIs for IDE plug-ins or tools.jar for anything running on a standard JDK.

Note that neverlink = 1 does not prevent the compiler from inlining material from this library into compilation targets that depend on it, as permitted by the Java Language Specification (e.g., static final constants of String or of primitive types). The preferred use case is therefore when the runtime library is identical to the compilation library.

If the runtime library differs from the compilation library then you must ensure that it differs only in places that the JLS forbids compilers to inline (and that must hold for all future versions of the JLS).

| Boolean | optional | `False` | +| plugins | Java compiler plugins to run at compile-time. Every java_plugin specified in this attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use exported_plugins. Resources generated by the plugin will be included in the resulting jar of this rule. | List of labels | optional | `[]` | +| proguard_specs | Files to be used as Proguard specification. These will describe the set of specifications to be used by Proguard. If specified, they will be added to any android_binary target depending on this library.

The files included here must only have idempotent rules, namely -dontnote, -dontwarn, assumenosideeffects, and rules that start with -keep. Other options can only appear in android_binary's proguard_specs, to ensure non-tautological merges. | List of labels | optional | `[]` | +| resource_strip_prefix | The path prefix to strip from Java resources.

If specified, this path prefix is stripped from every file in the resources attribute. It is an error for a resource file not to be under this directory. If not specified (the default), the path of resource file is determined according to the same logic as the Java package of source files. For example, a source file at stuff/java/foo/bar/a.txt will be located at foo/bar/a.txt.

| String | optional | `""` | +| runtime_deps | Libraries to make available to the final binary or test at runtime only. Like ordinary deps, these will appear on the runtime classpath, but unlike them, not on the compile-time classpath. Dependencies needed only at runtime should be listed here. Dependency-analysis tools should ignore targets that appear in both runtime_deps and deps. | List of labels | optional | `[]` | + + + + +## java_package_configuration + +
+java_package_configuration(name, data, javacopts, output_licenses, packages)
+
+ +

+Configuration to apply to a set of packages. +Configurations can be added to +java_toolchain.javacoptss. +

+ +

Example:

+ +
+
+
+java_package_configuration(
+    name = "my_configuration",
+    packages = [":my_packages"],
+    javacopts = ["-Werror"],
+)
+
+package_group(
+    name = "my_packages",
+    packages = [
+        "//com/my/project/...",
+        "-//com/my/project/testing/...",
+    ],
+)
+
+java_toolchain(
+    ...,
+    package_configuration = [
+        ":my_configuration",
+    ]
+)
+
+
+
+ +**ATTRIBUTES** + + +| Name | Description | Type | Mandatory | Default | +| :------------- | :------------- | :------------- | :------------- | :------------- | +| name | A unique name for this target. | Name | required | | +| data | The list of files needed by this configuration at runtime. | List of labels | optional | `[]` | +| javacopts | Java compiler flags. | List of strings | optional | `[]` | +| output_licenses | - | List of strings | optional | `[]` | +| packages | The set of package_groups the configuration should be applied to. | List of labels | optional | `[]` | + + + + +## java_plugin + +
+java_plugin(name, deps, srcs, data, resources, add_exports, add_opens, bootclasspath, generates_api,
+            javabuilder_jvm_flags, javacopts, licenses, neverlink, output_licenses, plugins,
+            processor_class, proguard_specs, resource_strip_prefix)
+
+ +

+ java_plugin defines plugins for the Java compiler run by Bazel. The + only supported kind of plugins are annotation processors. A java_library or + java_binary rule can run plugins by depending on them via the plugins + attribute. A java_library can also automatically export plugins to libraries that + directly depend on it using + exported_plugins. +

+ +

Implicit output targets

+
    +
  • libname.jar: A Java archive.
  • +
+ +

+ Arguments are identical to java_library, except + for the addition of the processor_class argument. +

+ +**ATTRIBUTES** + + +| Name | Description | Type | Mandatory | Default | +| :------------- | :------------- | :------------- | :------------- | :------------- | +| name | A unique name for this target. | Name | required | | +| deps | The list of libraries to link into this library. See general comments about deps at Typical attributes defined by most build rules.

The jars built by java_library rules listed in deps will be on the compile-time classpath of this rule. Furthermore the transitive closure of their deps, runtime_deps and exports will be on the runtime classpath.

By contrast, targets in the data attribute are included in the runfiles but on neither the compile-time nor runtime classpath.

| List of labels | optional | `[]` | +| srcs | The list of source files that are processed to create the target. This attribute is almost always required; see exceptions below.

Source files of type .java are compiled. In case of generated .java files it is generally advisable to put the generating rule's name here instead of the name of the file itself. This not only improves readability but makes the rule more resilient to future changes: if the generating rule generates different files in the future, you only need to fix one place: the outs of the generating rule. You should not list the generating rule in deps because it is a no-op.

Source files of type .srcjar are unpacked and compiled. (This is useful if you need to generate a set of .java files with a genrule.)

Rules: if the rule (typically genrule or filegroup) generates any of the files listed above, they will be used the same way as described for source files.

Source files of type .properties are treated as resources.



All other files are ignored, as long as there is at least one file of a file type described above. Otherwise an error is raised.



This argument is almost always required, except if you specify the runtime_deps argument.

| List of labels | optional | `[]` | +| data | The list of files needed by this library at runtime. See general comments about data at Typical attributes defined by most build rules.

When building a java_library, Bazel doesn't put these files anywhere; if the data files are generated files then Bazel generates them. When building a test that depends on this java_library Bazel copies or links the data files into the runfiles area.

| List of labels | optional | `[]` | +| resources | A list of data files to include in a Java jar.

Resources may be source files or generated files.



If resources are specified, they will be bundled in the jar along with the usual .class files produced by compilation. The location of the resources inside of the jar file is determined by the project structure. Bazel first looks for Maven's standard directory layout, (a "src" directory followed by a "resources" directory grandchild). If that is not found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for example, if a resource is at <workspace root>/x/java/y/java/z, the path of the resource will be y/java/z. This heuristic cannot be overridden, however, the resource_strip_prefix attribute can be used to specify a specific alternative directory for resource files. | List of labels | optional | `[]` | +| add_exports | Allow this library to access the given module or package.

This corresponds to the javac and JVM --add-exports= flags. | List of strings | optional | `[]` | +| add_opens | Allow this library to reflectively access the given module or package.

This corresponds to the javac and JVM --add-opens= flags. | List of strings | optional | `[]` | +| bootclasspath | Restricted API, do not use! | Label | optional | `None` | +| generates_api | This attribute marks annotation processors that generate API code.

If a rule uses an API-generating annotation processor, other rules depending on it can refer to the generated code only if their compilation actions are scheduled after the generating rule. This attribute instructs Bazel to introduce scheduling constraints when --java_header_compilation is enabled.

WARNING: This attribute affects build performance, use it only if necessary.

| Boolean | optional | `False` | +| javabuilder_jvm_flags | Restricted API, do not use! | List of strings | optional | `[]` | +| javacopts | Extra compiler options for this library. Subject to "Make variable" substitution and Bourne shell tokenization.

These compiler options are passed to javac after the global compiler options.

| List of strings | optional | `[]` | +| licenses | - | List of strings | optional | `[]` | +| neverlink | Whether this library should only be used for compilation and not at runtime. Useful if the library will be provided by the runtime environment during execution. Examples of such libraries are the IDE APIs for IDE plug-ins or tools.jar for anything running on a standard JDK.

Note that neverlink = 1 does not prevent the compiler from inlining material from this library into compilation targets that depend on it, as permitted by the Java Language Specification (e.g., static final constants of String or of primitive types). The preferred use case is therefore when the runtime library is identical to the compilation library.

If the runtime library differs from the compilation library then you must ensure that it differs only in places that the JLS forbids compilers to inline (and that must hold for all future versions of the JLS).

| Boolean | optional | `False` | +| output_licenses | - | List of strings | optional | `[]` | +| plugins | Java compiler plugins to run at compile-time. Every java_plugin specified in this attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use exported_plugins. Resources generated by the plugin will be included in the resulting jar of this rule. | List of labels | optional | `[]` | +| processor_class | The processor class is the fully qualified type of the class that the Java compiler should use as entry point to the annotation processor. If not specified, this rule will not contribute an annotation processor to the Java compiler's annotation processing, but its runtime classpath will still be included on the compiler's annotation processor path. (This is primarily intended for use by Error Prone plugins, which are loaded from the annotation processor path using java.util.ServiceLoader.) | String | optional | `""` | +| proguard_specs | Files to be used as Proguard specification. These will describe the set of specifications to be used by Proguard. If specified, they will be added to any android_binary target depending on this library.

The files included here must only have idempotent rules, namely -dontnote, -dontwarn, assumenosideeffects, and rules that start with -keep. Other options can only appear in android_binary's proguard_specs, to ensure non-tautological merges. | List of labels | optional | `[]` | +| resource_strip_prefix | The path prefix to strip from Java resources.

If specified, this path prefix is stripped from every file in the resources attribute. It is an error for a resource file not to be under this directory. If not specified (the default), the path of resource file is determined according to the same logic as the Java package of source files. For example, a source file at stuff/java/foo/bar/a.txt will be located at foo/bar/a.txt.

| String | optional | `""` | + + + + +## java_runtime + +
+java_runtime(name, srcs, default_cds, hermetic_srcs, hermetic_static_libs, java, java_home,
+             lib_ct_sym, lib_modules, output_licenses, version)
+
+ +

+Specifies the configuration for a Java runtime. +

+ +

Example:

+ +
+
+
+java_runtime(
+    name = "jdk-9-ea+153",
+    srcs = glob(["jdk9-ea+153/**"]),
+    java_home = "jdk9-ea+153",
+)
+
+
+
+ +**ATTRIBUTES** + + +| Name | Description | Type | Mandatory | Default | +| :------------- | :------------- | :------------- | :------------- | :------------- | +| name | A unique name for this target. | Name | required | | +| srcs | All files in the runtime. | List of labels | optional | `[]` | +| default_cds | Default CDS archive for hermetic java_runtime. When hermetic is enabled for a java_binary target and if the target does not provide its own CDS archive by specifying the classlist attribute, the java_runtime default CDS is packaged in the hermetic deploy JAR. | Label | optional | `None` | +| hermetic_srcs | Files in the runtime needed for hermetic deployments. | List of labels | optional | `[]` | +| hermetic_static_libs | The libraries that are statically linked with the launcher for hermetic deployments | List of labels | optional | `[]` | +| java | The path to the java executable. | Label | optional | `None` | +| java_home | The path to the root of the runtime. Subject to "Make" variable substitution. If this path is absolute, the rule denotes a non-hermetic Java runtime with a well-known path. In that case, the srcs and java attributes must be empty. | String | optional | `""` | +| lib_ct_sym | The lib/ct.sym file needed for compilation with --release. If not specified and there is exactly one file in srcs whose path ends with /lib/ct.sym, that file is used. | Label | optional | `None` | +| lib_modules | The lib/modules file needed for hermetic deployments. | Label | optional | `None` | +| output_licenses | - | List of strings | optional | `[]` | +| version | The feature version of the Java runtime. I.e., the integer returned by Runtime.version().feature(). | Integer | optional | `0` | + + + + +## java_test + +
+java_test(name, deps, srcs, data, resources, add_exports, add_opens, bootclasspath,
+          classpath_resources, create_executable, deploy_manifest_lines, env, env_inherit, javacopts,
+          jvm_flags, launcher, licenses, main_class, neverlink, plugins, resource_strip_prefix,
+          runtime_deps, stamp, test_class, use_launcher, use_testrunner)
+
+ +

+A java_test() rule compiles a Java test. A test is a binary wrapper around your +test code. The test runner's main method is invoked instead of the main class being compiled. +

+ +

Implicit output targets

+
    +
  • name.jar: A Java archive.
  • +
  • name_deploy.jar: A Java archive suitable + for deployment. (Only built if explicitly requested.) See the description of the + name_deploy.jar output from + java_binary for more details.
  • +
+ +

+See the section on java_binary() arguments. This rule also +supports all attributes common +to all test rules (*_test). +

+ +

Examples

+ +
+
+
+java_library(
+    name = "tests",
+    srcs = glob(["*.java"]),
+    deps = [
+        "//java/com/foo/base:testResources",
+        "//java/com/foo/testing/util",
+    ],
+)
+
+java_test(
+    name = "AllTests",
+    size = "small",
+    runtime_deps = [
+        ":tests",
+        "//util/mysql",
+    ],
+)
+
+
+ +**ATTRIBUTES** + + +| Name | Description | Type | Mandatory | Default | +| :------------- | :------------- | :------------- | :------------- | :------------- | +| name | A unique name for this target. | Name | required | | +| deps | The list of other libraries to be linked in to the target. See general comments about deps at Typical attributes defined by most build rules. | List of labels | optional | `[]` | +| srcs | The list of source files that are processed to create the target. This attribute is almost always required; see exceptions below.

Source files of type .java are compiled. In case of generated .java files it is generally advisable to put the generating rule's name here instead of the name of the file itself. This not only improves readability but makes the rule more resilient to future changes: if the generating rule generates different files in the future, you only need to fix one place: the outs of the generating rule. You should not list the generating rule in deps because it is a no-op.

Source files of type .srcjar are unpacked and compiled. (This is useful if you need to generate a set of .java files with a genrule.)

Rules: if the rule (typically genrule or filegroup) generates any of the files listed above, they will be used the same way as described for source files.



This argument is almost always required, except if a main_class attribute specifies a class on the runtime classpath or you specify the runtime_deps argument.

| List of labels | optional | `[]` | +| data | The list of files needed by this library at runtime. See general comments about data at Typical attributes defined by most build rules. | List of labels | optional | `[]` | +| resources | A list of data files to include in a Java jar.

Resources may be source files or generated files.



If resources are specified, they will be bundled in the jar along with the usual .class files produced by compilation. The location of the resources inside of the jar file is determined by the project structure. Bazel first looks for Maven's standard directory layout, (a "src" directory followed by a "resources" directory grandchild). If that is not found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for example, if a resource is at <workspace root>/x/java/y/java/z, the path of the resource will be y/java/z. This heuristic cannot be overridden, however, the resource_strip_prefix attribute can be used to specify a specific alternative directory for resource files. | List of labels | optional | `[]` | +| add_exports | Allow this library to access the given module or package.

This corresponds to the javac and JVM --add-exports= flags. | List of strings | optional | `[]` | +| add_opens | Allow this library to reflectively access the given module or package.

This corresponds to the javac and JVM --add-opens= flags. | List of strings | optional | `[]` | +| bootclasspath | Restricted API, do not use! | Label | optional | `None` | +| classpath_resources | DO NOT USE THIS OPTION UNLESS THERE IS NO OTHER WAY)

A list of resources that must be located at the root of the java tree. This attribute's only purpose is to support third-party libraries that require that their resources be found on the classpath as exactly "myconfig.xml". It is only allowed on binaries and not libraries, due to the danger of namespace conflicts.

| List of labels | optional | `[]` | +| create_executable | Deprecated, use java_single_jar instead. | Boolean | optional | `True` | +| deploy_manifest_lines | A list of lines to add to the META-INF/manifest.mf file generated for the *_deploy.jar target. The contents of this attribute are not subject to "Make variable" substitution. | List of strings | optional | `[]` | +| env | - | Dictionary: String -> String | optional | `{}` | +| env_inherit | - | List of strings | optional | `[]` | +| javacopts | Extra compiler options for this binary. Subject to "Make variable" substitution and Bourne shell tokenization.

These compiler options are passed to javac after the global compiler options.

| List of strings | optional | `[]` | +| jvm_flags | A list of flags to embed in the wrapper script generated for running this binary. Subject to $(location) and "Make variable" substitution, and Bourne shell tokenization.

The wrapper script for a Java binary includes a CLASSPATH definition (to find all the dependent jars) and invokes the right Java interpreter. The command line generated by the wrapper script includes the name of the main class followed by a "$@" so you can pass along other arguments after the classname. However, arguments intended for parsing by the JVM must be specified before the classname on the command line. The contents of jvm_flags are added to the wrapper script before the classname is listed.



Note that this attribute has no effect on *_deploy.jar outputs.

| List of strings | optional | `[]` | +| launcher | Specify a binary that will be used to run your Java program instead of the normal bin/java program included with the JDK. The target must be a cc_binary. Any cc_binary that implements the Java Invocation API can be specified as a value for this attribute.

By default, Bazel will use the normal JDK launcher (bin/java or java.exe).



The related --java_launcher Bazel flag affects only those java_binary and java_test targets that have not specified a launcher attribute.



Note that your native (C++, SWIG, JNI) dependencies will be built differently depending on whether you are using the JDK launcher or another launcher:



  • If you are using the normal JDK launcher (the default), native dependencies are built as a shared library named {name}_nativedeps.so, where {name} is the name attribute of this java_binary rule. Unused code is not removed by the linker in this configuration.


  • If you are using any other launcher, native (C++) dependencies are statically linked into a binary named {name}_nativedeps, where {name} is the name attribute of this java_binary rule. In this case, the linker will remove any code it thinks is unused from the resulting binary, which means any C++ code accessed only via JNI may not be linked in unless that cc_library target specifies alwayslink = 1.


When using any launcher other than the default JDK launcher, the format of the *_deploy.jar output changes. See the main java_binary docs for details.

| Label | optional | `None` | +| licenses | - | List of strings | optional | `[]` | +| main_class | Name of class with main() method to use as entry point. If a rule uses this option, it does not need a srcs=[...] list. Thus, with this attribute one can make an executable from a Java library that already contains one or more main() methods.

The value of this attribute is a class name, not a source file. The class must be available at runtime: it may be compiled by this rule (from srcs) or provided by direct or transitive dependencies (through runtime_deps or deps). If the class is unavailable, the binary will fail at runtime; there is no build-time check.

| String | optional | `""` | +| neverlink | - | Boolean | optional | `False` | +| plugins | Java compiler plugins to run at compile-time. Every java_plugin specified in this attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use exported_plugins. Resources generated by the plugin will be included in the resulting jar of this rule. | List of labels | optional | `[]` | +| resource_strip_prefix | The path prefix to strip from Java resources.

If specified, this path prefix is stripped from every file in the resources attribute. It is an error for a resource file not to be under this directory. If not specified (the default), the path of resource file is determined according to the same logic as the Java package of source files. For example, a source file at stuff/java/foo/bar/a.txt will be located at foo/bar/a.txt.

| String | optional | `""` | +| runtime_deps | Libraries to make available to the final binary or test at runtime only. Like ordinary deps, these will appear on the runtime classpath, but unlike them, not on the compile-time classpath. Dependencies needed only at runtime should be listed here. Dependency-analysis tools should ignore targets that appear in both runtime_deps and deps. | List of labels | optional | `[]` | +| stamp | Whether to encode build information into the binary. Possible values:
  • stamp = 1: Always stamp the build information into the binary, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the binary and any downstream actions that depend on it.
  • stamp = 0: Always replace build information by constant values. This gives good build result caching.
  • stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.

Stamped binaries are not rebuilt unless their dependencies change.

| Integer | optional | `0` | +| test_class | The Java class to be loaded by the test runner.

By default, if this argument is not defined then the legacy mode is used and the test arguments are used instead. Set the --nolegacy_bazel_java_test flag to not fallback on the first argument.

This attribute specifies the name of a Java class to be run by this test. It is rare to need to set this. If this argument is omitted, it will be inferred using the target's name and its source-root-relative path. If the test is located outside a known source root, Bazel will report an error if test_class is unset.

For JUnit3, the test class needs to either be a subclass of junit.framework.TestCase or it needs to have a public static suite() method that returns a junit.framework.Test (or a subclass of Test). For JUnit4, the class needs to be annotated with org.junit.runner.RunWith.

This attribute allows several java_test rules to share the same Test (TestCase, TestSuite, ...). Typically additional information is passed to it (e.g. via jvm_flags=['-Dkey=value']) so that its behavior differs in each case, such as running a different subset of the tests. This attribute also enables the use of Java tests outside the javatests tree.

| String | optional | `""` | +| use_launcher | Whether the binary should use a custom launcher.

If this attribute is set to false, the launcher attribute and the related --java_launcher flag will be ignored for this target. | Boolean | optional | `True` | +| use_testrunner | Use the test runner (by default com.google.testing.junit.runner.BazelTestRunner) class as the main entry point for a Java program, and provide the test class to the test runner as a value of bazel.test_suite system property.


You can use this to override the default behavior, which is to use test runner for java_test rules, and not use it for java_binary rules. It is unlikely you will want to do this. One use is for AllTest rules that are invoked by another rule (to set up a database before running the tests, for example). The AllTest rule must be declared as a java_binary, but should still use the test runner as its main entry point.

The name of a test runner class can be overridden with main_class attribute. | Boolean | optional | `True` | + + + + +## java_toolchain + +

+java_toolchain(name, android_lint_data, android_lint_jvm_opts, android_lint_opts,
+               android_lint_package_configuration, android_lint_runner, bootclasspath,
+               compatible_javacopts, deps_checker, forcibly_disable_header_compilation, genclass,
+               header_compiler, header_compiler_builtin_processors, header_compiler_direct, ijar,
+               jacocorunner, java_runtime, javabuilder, javabuilder_data, javabuilder_jvm_opts,
+               javac_supports_multiplex_workers, javac_supports_worker_cancellation,
+               javac_supports_worker_multiplex_sandboxing, javac_supports_workers, javacopts,
+               jspecify_implicit_deps, jspecify_javacopts, jspecify_packages, jspecify_processor,
+               jspecify_processor_class, jspecify_stubs, jvm_opts, licenses, misc, oneversion,
+               oneversion_allowlist_for_tests, oneversion_whitelist, package_configuration,
+               proguard_allowlister, reduced_classpath_incompatible_processors, singlejar,
+               source_version, target_version, timezone_data, tools, turbine_data, turbine_jvm_opts,
+               xlint)
+
+ +

+Specifies the configuration for the Java compiler. Which toolchain to be used can be changed through +the --java_toolchain argument. Normally you should not write those kind of rules unless you want to +tune your Java compiler. +

+ +

Examples

+ +

A simple example would be: +

+ +
+
+
+java_toolchain(
+    name = "toolchain",
+    source_version = "7",
+    target_version = "7",
+    bootclasspath = ["//tools/jdk:bootclasspath"],
+    xlint = [ "classfile", "divzero", "empty", "options", "path" ],
+    javacopts = [ "-g" ],
+    javabuilder = ":JavaBuilder_deploy.jar",
+)
+
+
+ +**ATTRIBUTES** + + +| Name | Description | Type | Mandatory | Default | +| :------------- | :------------- | :------------- | :------------- | :------------- | +| name | A unique name for this target. | Name | required | | +| android_lint_data | Labels of tools available for label-expansion in android_lint_jvm_opts. | List of labels | optional | `[]` | +| android_lint_jvm_opts | The list of arguments for the JVM when invoking Android Lint. | List of strings | optional | `[]` | +| android_lint_opts | The list of Android Lint arguments. | List of strings | optional | `[]` | +| android_lint_package_configuration | Android Lint Configuration that should be applied to the specified package groups. | List of labels | optional | `[]` | +| android_lint_runner | Label of the Android Lint runner, if any. | Label | optional | `None` | +| bootclasspath | The Java target bootclasspath entries. Corresponds to javac's -bootclasspath flag. | List of labels | optional | `[]` | +| compatible_javacopts | Internal API, do not use! | Dictionary: String -> List of strings | optional | `{}` | +| deps_checker | Label of the ImportDepsChecker deploy jar. | Label | optional | `None` | +| forcibly_disable_header_compilation | Overrides --java_header_compilation to disable header compilation on platforms that do not support it, e.g. JDK 7 Bazel. | Boolean | optional | `False` | +| genclass | Label of the GenClass deploy jar. | Label | optional | `None` | +| header_compiler | Label of the header compiler. Required if --java_header_compilation is enabled. | Label | optional | `None` | +| header_compiler_builtin_processors | Internal API, do not use! | List of strings | optional | `[]` | +| header_compiler_direct | Optional label of the header compiler to use for direct classpath actions that do not include any API-generating annotation processors.

This tool does not support annotation processing. | Label | optional | `None` | +| ijar | Label of the ijar executable. | Label | optional | `None` | +| jacocorunner | Label of the JacocoCoverageRunner deploy jar. | Label | optional | `None` | +| java_runtime | The java_runtime to use with this toolchain. It defaults to java_runtime in execution configuration. | Label | optional | `None` | +| javabuilder | Label of the JavaBuilder deploy jar. | Label | optional | `None` | +| javabuilder_data | Labels of data available for label-expansion in javabuilder_jvm_opts. | List of labels | optional | `[]` | +| javabuilder_jvm_opts | The list of arguments for the JVM when invoking JavaBuilder. | List of strings | optional | `[]` | +| javac_supports_multiplex_workers | True if JavaBuilder supports running as a multiplex persistent worker, false if it doesn't. | Boolean | optional | `True` | +| javac_supports_worker_cancellation | True if JavaBuilder supports cancellation of persistent workers, false if it doesn't. | Boolean | optional | `True` | +| javac_supports_worker_multiplex_sandboxing | True if JavaBuilder supports running as a multiplex persistent worker with sandboxing, false if it doesn't. | Boolean | optional | `False` | +| javac_supports_workers | True if JavaBuilder supports running as a persistent worker, false if it doesn't. | Boolean | optional | `True` | +| javacopts | The list of extra arguments for the Java compiler. Please refer to the Java compiler documentation for the extensive list of possible Java compiler flags. | List of strings | optional | `[]` | +| jspecify_implicit_deps | Experimental, do not use! | Label | optional | `None` | +| jspecify_javacopts | Experimental, do not use! | List of strings | optional | `[]` | +| jspecify_packages | Experimental, do not use! | List of labels | optional | `[]` | +| jspecify_processor | Experimental, do not use! | Label | optional | `None` | +| jspecify_processor_class | Experimental, do not use! | String | optional | `""` | +| jspecify_stubs | Experimental, do not use! | List of labels | optional | `[]` | +| jvm_opts | The list of arguments for the JVM when invoking the Java compiler. Please refer to the Java virtual machine documentation for the extensive list of possible flags for this option. | List of strings | optional | `[]` | +| licenses | - | List of strings | optional | `[]` | +| misc | Deprecated: use javacopts instead | List of strings | optional | `[]` | +| oneversion | Label of the one-version enforcement binary. | Label | optional | `None` | +| oneversion_allowlist_for_tests | Label of the one-version allowlist for tests. | Label | optional | `None` | +| oneversion_whitelist | Label of the one-version allowlist. | Label | optional | `None` | +| package_configuration | Configuration that should be applied to the specified package groups. | List of labels | optional | `[]` | +| proguard_allowlister | Label of the Proguard allowlister. | Label | optional | `"@bazel_tools//tools/jdk:proguard_whitelister"` | +| reduced_classpath_incompatible_processors | Internal API, do not use! | List of strings | optional | `[]` | +| singlejar | Label of the SingleJar deploy jar. | Label | optional | `None` | +| source_version | The Java source version (e.g., '6' or '7'). It specifies which set of code structures are allowed in the Java source code. | String | optional | `""` | +| target_version | The Java target version (e.g., '6' or '7'). It specifies for which Java runtime the class should be build. | String | optional | `""` | +| timezone_data | Label of a resource jar containing timezone data. If set, the timezone data is added as an implicitly runtime dependency of all java_binary rules. | Label | optional | `None` | +| tools | Labels of tools available for label-expansion in jvm_opts. | List of labels | optional | `[]` | +| turbine_data | Labels of data available for label-expansion in turbine_jvm_opts. | List of labels | optional | `[]` | +| turbine_jvm_opts | The list of arguments for the JVM when invoking turbine. | List of strings | optional | `[]` | +| xlint | The list of warning to add or removes from default list. Precedes it with a dash to removes it. Please see the Javac documentation on the -Xlint options for more information. | List of strings | optional | `[]` | + + diff --git a/test/BUILD.bazel b/test/BUILD.bazel index 10919e52..c823457b 100644 --- a/test/BUILD.bazel +++ b/test/BUILD.bazel @@ -1,3 +1,5 @@ +load("@bazel_skylib//rules:diff_test.bzl", "diff_test") + # Copyright 2024 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -44,4 +46,16 @@ sh_test( ], ) +diff_test( + name = "docs_up_to_date_test", + failure_message = """ + Docs are no longer up to date. Regenerate them by running: + + bazel build //java/docs:rule_docs && \ + cp bazel-bin/java/docs/rules_docs.out java/docs/rules.md + """, + file1 = "//java/docs:rules.md", + file2 = "//java/docs:rule_docs", +) + validate_configs() From b6cf2ebf546c917f194594b2a78a15a5a732ef3f Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 23 Sep 2024 10:05:07 -0700 Subject: [PATCH 031/465] Rename java_toolchain.oneversion_whitelist to oneversion_allowlist PiperOrigin-RevId: 677839283 Change-Id: I45d2a914d1a10599fad9c2426564361bd5a29c03 --- java/common/rules/java_toolchain.bzl | 9 ++++++++- java/docs/rules.md | 11 ++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/java/common/rules/java_toolchain.bzl b/java/common/rules/java_toolchain.bzl index 5a9cb87f..1875e33e 100644 --- a/java/common/rules/java_toolchain.bzl +++ b/java/common/rules/java_toolchain.bzl @@ -91,6 +91,9 @@ def _java_toolchain_impl(ctx): else: header_compiler_direct_data = [] header_compiler_direct_jvm_opts = [] + if ctx.attr.oneversion_allowlist and ctx.attr.oneversion_whitelist: + fail("oneversion_allowlist and oneversion_whitelist are mutually exclusive") + oneversion_allowlist = ctx.file.oneversion_allowlist if ctx.file.oneversion_allowlist else ctx.file.oneversion_whitelist java_toolchain_info = _new_javatoolchaininfo( bootclasspath = bootclasspath_info.bootclasspath, ijar = ctx.attr.ijar.files_to_run if ctx.attr.ijar else None, @@ -129,7 +132,7 @@ def _java_toolchain_impl(ctx): _jspecify_info = _get_jspecify_info(ctx), _local_java_optimization_config = ctx.files._local_java_optimization_configuration, _one_version_tool = ctx.attr.oneversion.files_to_run if ctx.attr.oneversion else None, - _one_version_allowlist = ctx.file.oneversion_whitelist, + _one_version_allowlist = oneversion_allowlist, _one_version_allowlist_for_tests = ctx.file.oneversion_allowlist_for_tests, _package_configuration = [dep[JavaPackageConfigurationInfo] for dep in ctx.attr.package_configuration], _reduced_classpath_incompatible_processors = depset(ctx.attr.reduced_classpath_incompatible_processors, order = "preorder"), @@ -503,6 +506,10 @@ Label of the one-version enforcement binary. """, ), "oneversion_whitelist": attr.label( + allow_single_file = True, + doc = """Deprecated: use oneversion_allowlist instead""", + ), + "oneversion_allowlist": attr.label( allow_single_file = True, doc = """ Label of the one-version allowlist. diff --git a/java/docs/rules.md b/java/docs/rules.md index f241f1b2..6585ee39 100644 --- a/java/docs/rules.md +++ b/java/docs/rules.md @@ -499,10 +499,10 @@ java_toolchain(name, javac_supports_worker_multiplex_sandboxing, javac_supports_workers, javacopts, jspecify_implicit_deps, jspecify_javacopts, jspecify_packages, jspecify_processor, jspecify_processor_class, jspecify_stubs, jvm_opts, licenses, misc, oneversion, - oneversion_allowlist_for_tests, oneversion_whitelist, package_configuration, - proguard_allowlister, reduced_classpath_incompatible_processors, singlejar, - source_version, target_version, timezone_data, tools, turbine_data, turbine_jvm_opts, - xlint) + oneversion_allowlist, oneversion_allowlist_for_tests, oneversion_whitelist, + package_configuration, proguard_allowlister, reduced_classpath_incompatible_processors, + singlejar, source_version, target_version, timezone_data, tools, turbine_data, + turbine_jvm_opts, xlint)

@@ -571,8 +571,9 @@ java_toolchain( | licenses | - | List of strings | optional | `[]` | | misc | Deprecated: use javacopts instead | List of strings | optional | `[]` | | oneversion | Label of the one-version enforcement binary. | Label | optional | `None` | +| oneversion_allowlist | Label of the one-version allowlist. | Label | optional | `None` | | oneversion_allowlist_for_tests | Label of the one-version allowlist for tests. | Label | optional | `None` | -| oneversion_whitelist | Label of the one-version allowlist. | Label | optional | `None` | +| oneversion_whitelist | Deprecated: use oneversion_allowlist instead | Label | optional | `None` | | package_configuration | Configuration that should be applied to the specified package groups. | List of labels | optional | `[]` | | proguard_allowlister | Label of the Proguard allowlister. | Label | optional | `"@bazel_tools//tools/jdk:proguard_whitelister"` | | reduced_classpath_incompatible_processors | Internal API, do not use! | List of strings | optional | `[]` | From 46b472deb3c8bc4ca70028d6290ad11525b66ee8 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 25 Sep 2024 00:03:58 -0700 Subject: [PATCH 032/465] Minor documentation fixes PiperOrigin-RevId: 678562013 Change-Id: I4a52cc458f4b72478c0286a7300cb1214d410d0d --- java/bazel/rules/bazel_java_binary.bzl | 8 ++++---- java/bazel/rules/bazel_java_binary_nonexec.bzl | 5 +---- java/bazel/rules/bazel_java_import.bzl | 2 +- java/bazel/rules/bazel_java_plugin.bzl | 4 ++-- java/bazel/rules/bazel_java_test.bzl | 6 +++--- java/docs/BUILD.bazel | 2 +- java/docs/rules.md | 18 +++++++++--------- test/BUILD.bazel | 2 +- 8 files changed, 22 insertions(+), 25 deletions(-) diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl index 1cb7c7ad..5de7c859 100644 --- a/java/bazel/rules/bazel_java_binary.bzl +++ b/java/bazel/rules/bazel_java_binary.bzl @@ -381,7 +381,7 @@ def make_java_binary(executable): creates a self-contained jar file with a manifest that allows it to be run with the java -jar command or with the wrapper script's --singlejar option. Using the wrapper script is preferred to java -jar because it - also passes the JVM flags and the options + also passes the JVM flags and the options to load native libraries.

@@ -411,9 +411,9 @@ application (minus the extension). For example, if your entry point is called

A deps attribute is not allowed in a java_binary rule without - srcs; such a rule requires a - main_class provided by - runtime_deps. + srcs; such a rule requires a + main_class provided by + runtime_deps.

The following code snippet illustrates a common mistake:

diff --git a/java/bazel/rules/bazel_java_binary_nonexec.bzl b/java/bazel/rules/bazel_java_binary_nonexec.bzl index 82a76430..a59030ea 100644 --- a/java/bazel/rules/bazel_java_binary_nonexec.bzl +++ b/java/bazel/rules/bazel_java_binary_nonexec.bzl @@ -14,11 +14,8 @@ """Defines a java_binary rule class that is non-executable. -There are three physical rule classes for java_binary and we want all of them +There are two physical rule classes for java_binary and we want both of them to have a name string of "java_binary" because various tooling expects that. -But we also need the rule classes to be defined in separate files. That way the -hash of their bzl environments will be different. See http://b/226379109, -specifically #20, for details. """ load(":bazel_java_binary.bzl", "make_java_binary") diff --git a/java/bazel/rules/bazel_java_import.bzl b/java/bazel/rules/bazel_java_import.bzl index 98a040b6..a99b9a62 100644 --- a/java/bazel/rules/bazel_java_import.bzl +++ b/java/bazel/rules/bazel_java_import.bzl @@ -42,7 +42,7 @@ java_import = rule( doc = """

This rule allows the use of precompiled .jar files as - libraries for java_library and + libraries for java_library and java_binary rules.

diff --git a/java/bazel/rules/bazel_java_plugin.bzl b/java/bazel/rules/bazel_java_plugin.bzl index 462df8c3..943edd32 100644 --- a/java/bazel/rules/bazel_java_plugin.bzl +++ b/java/bazel/rules/bazel_java_plugin.bzl @@ -128,7 +128,7 @@ java_plugin = rule( java_binary rule can run plugins by depending on them via the plugins attribute. A java_library can also automatically export plugins to libraries that directly depend on it using - exported_plugins. + exported_plugins.

Implicit output targets

@@ -137,7 +137,7 @@ java_plugin = rule(

- Arguments are identical to java_library, except + Arguments are identical to java_library, except for the addition of the processor_class argument.

""", diff --git a/java/bazel/rules/bazel_java_test.bzl b/java/bazel/rules/bazel_java_test.bzl index 543b0276..8976e2e1 100644 --- a/java/bazel/rules/bazel_java_test.bzl +++ b/java/bazel/rules/bazel_java_test.bzl @@ -54,7 +54,7 @@ test code. The test runner's main method is invoked instead of the main class be

See the section on java_binary() arguments. This rule also -supports all attributes common +supports all attributes common to all test rules (*_test).

@@ -126,7 +126,7 @@ Whether to encode build information into the binary. Possible values:
  • stamp = 1: Always stamp the build information into the binary, even in - --nostamp builds. This + --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the binary and any downstream actions that depend on it.
  • @@ -136,7 +136,7 @@ Whether to encode build information into the binary. Possible values:
  • stamp = -1: Embedding of build information is controlled by the - --[no]stamp flag. + --[no]stamp flag.

Stamped binaries are not rebuilt unless their dependencies change.

diff --git a/java/docs/BUILD.bazel b/java/docs/BUILD.bazel index 63793251..599e4e0c 100644 --- a/java/docs/BUILD.bazel +++ b/java/docs/BUILD.bazel @@ -16,7 +16,7 @@ bzl_library( ) stardoc( - name = "rule_docs", + name = "rules_docs", out = "rules_docs.out", input = "rules.bzl", rule_template = ":rule.vm", diff --git a/java/docs/rules.md b/java/docs/rules.md index 6585ee39..974b93ff 100644 --- a/java/docs/rules.md +++ b/java/docs/rules.md @@ -52,7 +52,7 @@ java_binary(name, de creates a self-contained jar file with a manifest that allows it to be run with the java -jar command or with the wrapper script's --singlejar option. Using the wrapper script is preferred to java -jar because it - also passes the JVM flags and the options + also passes the JVM flags and the options to load native libraries.

@@ -82,9 +82,9 @@ application (minus the extension). For example, if your entry point is called

A deps attribute is not allowed in a java_binary rule without - srcs; such a rule requires a - main_class provided by - runtime_deps. + srcs; such a rule requires a + main_class provided by + runtime_deps.

The following code snippet illustrates a common mistake:

@@ -159,7 +159,7 @@ java_import(name, de

This rule allows the use of precompiled .jar files as - libraries for java_library and + libraries for java_library and java_binary rules.

@@ -313,7 +313,7 @@ java_plugin(name, de java_binary rule can run plugins by depending on them via the plugins attribute. A java_library can also automatically export plugins to libraries that directly depend on it using - exported_plugins. + exported_plugins.

Implicit output targets

@@ -322,7 +322,7 @@ java_plugin(name, de

- Arguments are identical to java_library, except + Arguments are identical to java_library, except for the addition of the processor_class argument.

@@ -423,7 +423,7 @@ test code. The test runner's main method is invoked instead of the main class be

See the section on java_binary() arguments. This rule also -supports all attributes common +supports all attributes common to all test rules (*_test).

@@ -479,7 +479,7 @@ java_test( | plugins | Java compiler plugins to run at compile-time. Every java_plugin specified in this attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use exported_plugins. Resources generated by the plugin will be included in the resulting jar of this rule. | List of labels | optional | `[]` | | resource_strip_prefix | The path prefix to strip from Java resources.

If specified, this path prefix is stripped from every file in the resources attribute. It is an error for a resource file not to be under this directory. If not specified (the default), the path of resource file is determined according to the same logic as the Java package of source files. For example, a source file at stuff/java/foo/bar/a.txt will be located at foo/bar/a.txt.

| String | optional | `""` | | runtime_deps | Libraries to make available to the final binary or test at runtime only. Like ordinary deps, these will appear on the runtime classpath, but unlike them, not on the compile-time classpath. Dependencies needed only at runtime should be listed here. Dependency-analysis tools should ignore targets that appear in both runtime_deps and deps. | List of labels | optional | `[]` | -| stamp | Whether to encode build information into the binary. Possible values:
  • stamp = 1: Always stamp the build information into the binary, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the binary and any downstream actions that depend on it.
  • stamp = 0: Always replace build information by constant values. This gives good build result caching.
  • stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.

Stamped binaries are not rebuilt unless their dependencies change.

| Integer | optional | `0` | +| stamp | Whether to encode build information into the binary. Possible values:
  • stamp = 1: Always stamp the build information into the binary, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the binary and any downstream actions that depend on it.
  • stamp = 0: Always replace build information by constant values. This gives good build result caching.
  • stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.

Stamped binaries are not rebuilt unless their dependencies change.

| Integer | optional | `0` | | test_class | The Java class to be loaded by the test runner.

By default, if this argument is not defined then the legacy mode is used and the test arguments are used instead. Set the --nolegacy_bazel_java_test flag to not fallback on the first argument.

This attribute specifies the name of a Java class to be run by this test. It is rare to need to set this. If this argument is omitted, it will be inferred using the target's name and its source-root-relative path. If the test is located outside a known source root, Bazel will report an error if test_class is unset.

For JUnit3, the test class needs to either be a subclass of junit.framework.TestCase or it needs to have a public static suite() method that returns a junit.framework.Test (or a subclass of Test). For JUnit4, the class needs to be annotated with org.junit.runner.RunWith.

This attribute allows several java_test rules to share the same Test (TestCase, TestSuite, ...). Typically additional information is passed to it (e.g. via jvm_flags=['-Dkey=value']) so that its behavior differs in each case, such as running a different subset of the tests. This attribute also enables the use of Java tests outside the javatests tree.

| String | optional | `""` | | use_launcher | Whether the binary should use a custom launcher.

If this attribute is set to false, the launcher attribute and the related --java_launcher flag will be ignored for this target. | Boolean | optional | `True` | | use_testrunner | Use the test runner (by default com.google.testing.junit.runner.BazelTestRunner) class as the main entry point for a Java program, and provide the test class to the test runner as a value of bazel.test_suite system property.


You can use this to override the default behavior, which is to use test runner for java_test rules, and not use it for java_binary rules. It is unlikely you will want to do this. One use is for AllTest rules that are invoked by another rule (to set up a database before running the tests, for example). The AllTest rule must be declared as a java_binary, but should still use the test runner as its main entry point.

The name of a test runner class can be overridden with main_class attribute. | Boolean | optional | `True` | diff --git a/test/BUILD.bazel b/test/BUILD.bazel index c823457b..a1d5be72 100644 --- a/test/BUILD.bazel +++ b/test/BUILD.bazel @@ -55,7 +55,7 @@ diff_test( cp bazel-bin/java/docs/rules_docs.out java/docs/rules.md """, file1 = "//java/docs:rules.md", - file2 = "//java/docs:rule_docs", + file2 = "//java/docs:rules_docs", ) validate_configs() From c1ce06ec058012d84fd3ef58b408850ee8f7e6d4 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 25 Sep 2024 20:00:51 -0700 Subject: [PATCH 033/465] Use `--one_version_allowlist` flag added in unknown commit PiperOrigin-RevId: 678949708 Change-Id: I6b5641a88aaecda9570fbd4c4f6e58239b0186cc --- java/common/rules/impl/java_binary_deploy_jar.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/common/rules/impl/java_binary_deploy_jar.bzl b/java/common/rules/impl/java_binary_deploy_jar.bzl index 183be458..dd24456b 100644 --- a/java/common/rules/impl/java_binary_deploy_jar.bzl +++ b/java/common/rules/impl/java_binary_deploy_jar.bzl @@ -204,7 +204,7 @@ def create_deploy_archive( if one_version_level != "OFF" and one_version_allowlist: input_files.append(one_version_allowlist) args.add("--enforce_one_version") - args.add("--one_version_whitelist", one_version_allowlist) + args.add("--one_version_allowlist", one_version_allowlist) if one_version_level == "WARNING": args.add("--succeed_on_found_violations") From d12c75c4c0d8080acb6ada208d29919ce0942a0f Mon Sep 17 00:00:00 2001 From: "Ian (Hee) Cha" Date: Thu, 26 Sep 2024 23:09:08 -0700 Subject: [PATCH 034/465] Update rules_java to 7.12.0 and java_tools to 13.9 Copybara Import from https://github.com/bazelbuild/rules_java/pull/226 BEGIN_PUBLIC Update rules_java to 7.12.0 and java_tools to 13.9 (#226) Closes #226 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/226 from bazelbuild:java_v13.9 fb6d56758a4606b0122bdd0d0159a336a2f901b6 PiperOrigin-RevId: 679448843 Change-Id: Iee8f019900583f4427339c0d195be5b70025518f --- MODULE.bazel | 2 +- java/repositories.bzl | 32 ++++++++++++++++---------------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 5c757789..0902c3a1 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "7.11.1", + version = "7.12.0", bazel_compatibility = [">=6.2.0"], compatibility_level = 1, ) diff --git a/java/repositories.bzl b/java/repositories.bzl index 37a0d31d..27f4f85d 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.8", + "version": "v13.9", "release": "false", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.8/java_tools_linux-v13.8.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.8/java_tools_linux-v13.8.zip", - "sha": "e480906978b34d1f15fa958699112872c7b5883a3d48b630b6bed574d86523ca", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.9/java_tools_linux-v13.9.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.9/java_tools_linux-v13.9.zip", + "sha": "7a3d7b1cd080efdf49ab2a3818177799416734acf2bd23040aa9037141287548", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.8/java_tools_windows-v13.8.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.8/java_tools_windows-v13.8.zip", - "sha": "bae74a8f1c7d3d5f73f944a31446b2d87d4e94966ef9cc0bc6b07de6fed6e382", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.9/java_tools_windows-v13.9.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.9/java_tools_windows-v13.9.zip", + "sha": "6a17ac1921d60af5dca780f4200fd0f9963441bd7afff53b9efad6e7156c699d", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.8/java_tools_darwin_x86_64-v13.8.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.8/java_tools_darwin_x86_64-v13.8.zip", - "sha": "78a750e24d0bf0f125f3bb4218f58c4e60343f3d28c834e88bd09c7924c83d8d", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.9/java_tools_darwin_x86_64-v13.9.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.9/java_tools_darwin_x86_64-v13.9.zip", + "sha": "802bfb5085cec0ac5745a637ae2e7a7152c54230ba542d093a10bd48ba29ba6f", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.8/java_tools_darwin_arm64-v13.8.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.8/java_tools_darwin_arm64-v13.8.zip", - "sha": "7a4bf783c67db892e3e670d61c194a0595df8f151c0684146ec7bcf2057a6500", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.9/java_tools_darwin_arm64-v13.9.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.9/java_tools_darwin_arm64-v13.9.zip", + "sha": "9fa400a43153b048ae5a785e3ee533d675ed6a994ab3c763f50bd15a28544c10", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.8/java_tools-v13.8.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.8/java_tools-v13.8.zip", - "sha": "224287ef2b581795392cbd8b1b9f4306d11abb95bba41ea72810cc9c7872a5f8", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.9/java_tools-v13.9.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.9/java_tools-v13.9.zip", + "sha": "3b92e0c1884ac0e9683e87c3c49e1098cff91faeacdb76cc90d92efb0df861cf", }, }, } From 38ba04b12add1995f91f4b400e3ab3ac24f868ba Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 30 Sep 2024 03:27:20 -0700 Subject: [PATCH 035/465] Make `stardoc` a dev dependency of `rules_java` Context: https://github.com/bazelbuild/bazel/pull/23738#issuecomment-2382700919 PiperOrigin-RevId: 680499660 Change-Id: If2f44149382e7205c47a684eb1cb1abadff5a918 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 0902c3a1..b101761a 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -9,7 +9,6 @@ bazel_dep(name = "platforms", version = "0.0.4") bazel_dep(name = "rules_cc", version = "0.0.10") bazel_dep(name = "bazel_features", version = "1.11.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") -bazel_dep(name = "stardoc", version = "0.7.1") # Required by @remote_java_tools, which is loaded via module extension. bazel_dep(name = "rules_proto", version = "6.0.2") @@ -92,6 +91,7 @@ REMOTE_JDK_REPOS = [(("remote_jdk" if version == "8" else "remotejdk") + version # Dev dependencies bazel_dep(name = "rules_pkg", version = "0.9.1", dev_dependency = True) +bazel_dep(name = "stardoc", version = "0.7.1", dev_dependency = True) # Override rules_python version to deal with #161 and https://github.com/bazelbuild/bazel/issues/20458 single_version_override( From f9a46081f0902fe55d202f730330629fbcad053d Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 30 Sep 2024 04:51:00 -0700 Subject: [PATCH 036/465] Release `rules_java` `v7.12.1` PiperOrigin-RevId: 680522727 Change-Id: Id24518757e575039b3ddbce02f8043989423fd09 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index b101761a..fa5b11d8 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "7.12.0", + version = "7.12.1", bazel_compatibility = [">=6.2.0"], compatibility_level = 1, ) From 3cdce961d8f15b554d0072b6534c1a65d8400ba5 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 2 Oct 2024 01:18:46 -0700 Subject: [PATCH 037/465] Automated rollback of commit e4d1f09aeb143d20a21008793cb46d4b91c8005c. *** Reason for rollback *** Rollforward of https://github.com/rules_java/bazel/commit/70970af9590a49b310312b2d01e85ac4fb72fff7, Bazel 7.3.2 is released and the rules are usable *** Original change description *** Partial rollback of commit 70970af9590a49b310312b2d01e85ac4fb72fff7. *** Reason for rollback *** The rules aren't ready to be used with any Bazel version other than HEAD. Unblocks https://github.com/bazelbuild/bazel/pull/23649 *** Original change description *** Switch `rules_java` rule macro redirects from `native.*` to those defined locally Using the rules requires a bazel version that contains all the changes in https://github.com/bazelbuild/bazel/pull/23591 PiperOrigin-RevId: 681344593 Change-Id: Idea53aea2a0569ff6e345edd6a1d1b44722117bf --- .bazelci/presubmit.yml | 9 ++++----- java/java_binary.bzl | 5 +++-- java/java_import.bzl | 5 +++-- java/java_library.bzl | 5 +++-- java/java_plugin.bzl | 5 +++-- java/java_test.bzl | 5 +++-- 6 files changed, 19 insertions(+), 15 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 179245e5..43383114 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -23,15 +23,14 @@ buildifier: latest tasks: # TODO: add config for 8.0.0 once released # Bazel 7.x -# TODO: fix versions after 7.4.0 ubuntu2004: name: "Bazel 7.x" - bazel: "9e3fa2a2e98db4aa10918a981325cfa9473e4ed8" + bazel: "7.3.2" build_targets: *build_targets test_targets: *test_targets ubuntu2004_integration: name: "Bazel 7.x Integration" - bazel: "9e3fa2a2e98db4aa10918a981325cfa9473e4ed8" + bazel: "7.3.2" platform: ubuntu2004 working_directory: "test/repo" shell_commands: @@ -42,11 +41,11 @@ tasks: - "@rules_java//java/..." macos: name: "Bazel 7.x" - bazel: "9e3fa2a2e98db4aa10918a981325cfa9473e4ed8" + bazel: "7.3.2" build_targets: *build_targets windows: name: "Bazel 7.x" - bazel: "9e3fa2a2e98db4aa10918a981325cfa9473e4ed8" + bazel: "7.3.2" build_targets: *build_targets # Bazel@HEAD ubuntu2004_head: diff --git a/java/java_binary.bzl b/java/java_binary.bzl index 7184ecbd..18a3fed4 100644 --- a/java/java_binary.bzl +++ b/java/java_binary.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_binary rule""" +load("//java/bazel/rules:bazel_java_binary_wrapper.bzl", _java_binary = "java_binary") + def java_binary(**attrs): """Bazel java_binary rule. @@ -22,5 +24,4 @@ def java_binary(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_binary(**attrs) + _java_binary(**attrs) diff --git a/java/java_import.bzl b/java/java_import.bzl index 926c37a6..89f60309 100644 --- a/java/java_import.bzl +++ b/java/java_import.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_import rule""" +load("//java/bazel/rules:bazel_java_import.bzl", _java_import = "java_import") + def java_import(**attrs): """Bazel java_import rule. @@ -22,5 +24,4 @@ def java_import(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_import(**attrs) + _java_import(**attrs) diff --git a/java/java_library.bzl b/java/java_library.bzl index 9308bbc4..90c72676 100644 --- a/java/java_library.bzl +++ b/java/java_library.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_library rule""" +load("//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") + def java_library(**attrs): """Bazel java_library rule. @@ -22,5 +24,4 @@ def java_library(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_library(**attrs) + _java_library(**attrs) diff --git a/java/java_plugin.bzl b/java/java_plugin.bzl index d12e0e18..130dc625 100644 --- a/java/java_plugin.bzl +++ b/java/java_plugin.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_plugin rule""" +load("//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") + def java_plugin(**attrs): """Bazel java_plugin rule. @@ -22,5 +24,4 @@ def java_plugin(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_plugin(**attrs) + _java_plugin(**attrs) diff --git a/java/java_test.bzl b/java/java_test.bzl index 0aeac91b..48a66551 100644 --- a/java/java_test.bzl +++ b/java/java_test.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_test rule""" +load("//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") + def java_test(**attrs): """Bazel java_test rule. @@ -22,5 +24,4 @@ def java_test(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_test(**attrs) + _java_test(**attrs) From 2c8f7f4af7002b11ef80360b19393c8c363d1c0c Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 4 Oct 2024 02:08:23 -0700 Subject: [PATCH 038/465] Strip bzl visibility in `rules_java` on export PiperOrigin-RevId: 682229230 Change-Id: I8d71c8880b91ecf84f5e628d4108ccfa005e96e3 --- java/bazel/rules/BUILD.bazel | 5 +---- java/bazel/rules/bazel_java_binary.bzl | 2 -- java/bazel/rules/bazel_java_import.bzl | 2 -- java/bazel/rules/bazel_java_library.bzl | 2 -- java/bazel/rules/bazel_java_plugin.bzl | 2 -- java/bazel/rules/bazel_java_test.bzl | 2 -- java/common/java_semantics.bzl | 2 +- java/common/rules/android_lint.bzl | 2 +- java/common/rules/impl/bazel_java_import_impl.bzl | 2 +- java/common/rules/impl/bazel_java_library_impl.bzl | 2 +- java/common/rules/impl/java_binary_deploy_jar.bzl | 2 +- java/common/rules/impl/java_binary_impl.bzl | 2 +- java/common/rules/impl/java_helper.bzl | 2 +- java/common/rules/java_binary.bzl | 2 +- java/common/rules/java_binary_wrapper.bzl | 2 +- java/common/rules/java_import.bzl | 2 +- java/common/rules/java_library.bzl | 2 +- java/common/rules/java_package_configuration.bzl | 2 +- java/common/rules/java_plugin.bzl | 2 +- java/common/rules/java_runtime.bzl | 2 +- java/common/rules/java_toolchain.bzl | 2 +- java/common/rules/rule_util.bzl | 2 +- 22 files changed, 17 insertions(+), 30 deletions(-) diff --git a/java/bazel/rules/BUILD.bazel b/java/bazel/rules/BUILD.bazel index ba3ca917..b82b16c9 100644 --- a/java/bazel/rules/BUILD.bazel +++ b/java/bazel/rules/BUILD.bazel @@ -22,10 +22,7 @@ filegroup( bzl_library( name = "rules", srcs = glob(["*.bzl"]), - visibility = [ - "//java:__pkg__", - "//java/docs:__pkg__", - ], + visibility = ["//visibility:public"], # for Bazel docgen deps = [ "//java/common", "//java/common/rules:core_rules", diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl index 5de7c859..7d0e75b7 100644 --- a/java/bazel/rules/bazel_java_binary.bzl +++ b/java/bazel/rules/bazel_java_binary.bzl @@ -27,8 +27,6 @@ load("//java/common/rules/impl:java_binary_deploy_jar.bzl", "create_deploy_archi load("//java/common/rules/impl:java_binary_impl.bzl", "basic_java_binary") load("//java/common/rules/impl:java_helper.bzl", "helper") -visibility("//java/docs") - def _bazel_java_binary_impl(ctx): return bazel_base_binary_impl(ctx, is_test_rule_class = False) + helper.executable_providers(ctx) diff --git a/java/bazel/rules/bazel_java_import.bzl b/java/bazel/rules/bazel_java_import.bzl index a99b9a62..702dcf94 100644 --- a/java/bazel/rules/bazel_java_import.bzl +++ b/java/bazel/rules/bazel_java_import.bzl @@ -21,8 +21,6 @@ load("//java/common:java_semantics.bzl", "semantics") load("//java/common/rules:java_import.bzl", "JAVA_IMPORT_ATTRS") load("//java/common/rules/impl:bazel_java_import_impl.bzl", "bazel_java_import_rule") -visibility(["//java", "//java/docs"]) - def _proxy(ctx): return bazel_java_import_rule( ctx, diff --git a/java/bazel/rules/bazel_java_library.bzl b/java/bazel/rules/bazel_java_library.bzl index e70d54fd..425a91a3 100644 --- a/java/bazel/rules/bazel_java_library.bzl +++ b/java/bazel/rules/bazel_java_library.bzl @@ -22,8 +22,6 @@ load("//java/common/rules:android_lint.bzl", "android_lint_subrule") load("//java/common/rules:java_library.bzl", "JAVA_LIBRARY_ATTRS") load("//java/common/rules/impl:bazel_java_library_impl.bzl", "bazel_java_library_rule") -visibility(["//java/..."]) - def _proxy(ctx): return bazel_java_library_rule( ctx, diff --git a/java/bazel/rules/bazel_java_plugin.bzl b/java/bazel/rules/bazel_java_plugin.bzl index 943edd32..b1bfacbf 100644 --- a/java/bazel/rules/bazel_java_plugin.bzl +++ b/java/bazel/rules/bazel_java_plugin.bzl @@ -24,8 +24,6 @@ load("//java/common/rules:java_plugin.bzl", "JAVA_PLUGIN_ATTRS") load("//java/common/rules:rule_util.bzl", "merge_attrs") load("//java/common/rules/impl:basic_java_library_impl.bzl", "basic_java_library", "construct_defaultinfo") -visibility(["//java/..."]) - def bazel_java_plugin_rule( ctx, srcs = [], diff --git a/java/bazel/rules/bazel_java_test.bzl b/java/bazel/rules/bazel_java_test.bzl index 8976e2e1..7dec8496 100644 --- a/java/bazel/rules/bazel_java_test.bzl +++ b/java/bazel/rules/bazel_java_test.bzl @@ -19,8 +19,6 @@ load("//java/common/rules:rule_util.bzl", "merge_attrs") load("//java/common/rules/impl:java_helper.bzl", "helper") load(":bazel_java_binary.bzl", "BASE_BINARY_ATTRS", "bazel_base_binary_impl", "make_binary_rule") -visibility(["//java", "//java/docs"]) - def _bazel_java_test_impl(ctx): return bazel_base_binary_impl(ctx, is_test_rule_class = True) + helper.test_providers(ctx) diff --git a/java/common/java_semantics.bzl b/java/common/java_semantics.bzl index d8bf824b..c5cb2830 100644 --- a/java/common/java_semantics.bzl +++ b/java/common/java_semantics.bzl @@ -15,7 +15,7 @@ load("@rules_cc//cc/common:cc_helper.bzl", "cc_helper") -visibility(["//java/..."]) +# copybara: default visibility def _find_java_toolchain(ctx): return ctx.toolchains["@bazel_tools//tools/jdk:toolchain_type"].java diff --git a/java/common/rules/android_lint.bzl b/java/common/rules/android_lint.bzl index 7fd8d430..d7fec44b 100644 --- a/java/common/rules/android_lint.bzl +++ b/java/common/rules/android_lint.bzl @@ -16,7 +16,7 @@ load("//java/common:java_semantics.bzl", "semantics", _semantics_tokenize_javacopts = "tokenize_javacopts") -visibility(["//java/..."]) +# copybara: default visibility def _tokenize_opts(opts_depset): opts = reversed(opts_depset.to_list()) diff --git a/java/common/rules/impl/bazel_java_import_impl.bzl b/java/common/rules/impl/bazel_java_import_impl.bzl index 1c84fb79..6d636dc3 100644 --- a/java/common/rules/impl/bazel_java_import_impl.bzl +++ b/java/common/rules/impl/bazel_java_import_impl.bzl @@ -24,7 +24,7 @@ load("//java/common/rules/impl:basic_java_library_impl.bzl", "construct_defaulti load("//java/common/rules/impl:import_deps_check.bzl", "import_deps_check") load(":proguard_validation.bzl", "validate_proguard_specs") -visibility(["//java/..."]) +# copybara: default visibility _java_common_internal = java_common.internal_DO_NOT_USE() _run_ijar_private_for_builtins = _java_common_internal.run_ijar_private_for_builtins diff --git a/java/common/rules/impl/bazel_java_library_impl.bzl b/java/common/rules/impl/bazel_java_library_impl.bzl index f0a22748..04a020e4 100644 --- a/java/common/rules/impl/bazel_java_library_impl.bzl +++ b/java/common/rules/impl/bazel_java_library_impl.bzl @@ -18,7 +18,7 @@ Definition of java_library rule. load("//java/common/rules/impl:basic_java_library_impl.bzl", "basic_java_library", "construct_defaultinfo") -visibility(["//java/..."]) +# copybara: default visibility def bazel_java_library_rule( ctx, diff --git a/java/common/rules/impl/java_binary_deploy_jar.bzl b/java/common/rules/impl/java_binary_deploy_jar.bzl index dd24456b..6df08cbf 100644 --- a/java/common/rules/impl/java_binary_deploy_jar.bzl +++ b/java/common/rules/impl/java_binary_deploy_jar.bzl @@ -17,7 +17,7 @@ load("//java/common:java_semantics.bzl", "semantics") load(":java_helper.bzl", "helper") -visibility(["//java/..."]) +# copybara: default visibility def _get_build_info(ctx, stamp): if helper.is_stamping_enabled(ctx, stamp): diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl index 8d7e2ef9..98b388be 100644 --- a/java/common/rules/impl/java_binary_impl.bzl +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -24,7 +24,7 @@ load("//java/common/rules/impl:basic_java_library_impl.bzl", "basic_java_library load(":java_binary_deploy_jar.bzl", "create_deploy_archive") load(":java_helper.bzl", "helper") -visibility(["//java/..."]) +# copybara: default visibility _java_common_internal = java_common.internal_DO_NOT_USE() JavaCompilationInfo = _java_common_internal.JavaCompilationInfo diff --git a/java/common/rules/impl/java_helper.bzl b/java/common/rules/impl/java_helper.bzl index c8190750..87465f0a 100644 --- a/java/common/rules/impl/java_helper.bzl +++ b/java/common/rules/impl/java_helper.bzl @@ -20,7 +20,7 @@ load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_helper.bzl", "cc_helper") load("//java/common:java_semantics.bzl", "semantics") -visibility(["//java/..."]) +# copybara: default visibility def _collect_all_targets_as_deps(ctx, classpath_type = "all"): deps = [] diff --git a/java/common/rules/java_binary.bzl b/java/common/rules/java_binary.bzl index 5bdcd480..5b8b1072 100644 --- a/java/common/rules/java_binary.bzl +++ b/java/common/rules/java_binary.bzl @@ -23,7 +23,7 @@ load("//java/common:java_semantics.bzl", "PLATFORMS_ROOT", "semantics") load(":basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS") load(":rule_util.bzl", "merge_attrs") -visibility(["//java/..."]) +# copybara: default visibility BootClassPathInfo = java_common.BootClassPathInfo diff --git a/java/common/rules/java_binary_wrapper.bzl b/java/common/rules/java_binary_wrapper.bzl index 3d94dcd7..89b423b4 100644 --- a/java/common/rules/java_binary_wrapper.bzl +++ b/java/common/rules/java_binary_wrapper.bzl @@ -20,7 +20,7 @@ the supplied value of the `create_executable` attribute. load("//java/common:java_semantics.bzl", "semantics") -visibility(["//java/..."]) +# copybara: default visibility def register_legacy_java_binary_rules( rule_exec, diff --git a/java/common/rules/java_import.bzl b/java/common/rules/java_import.bzl index eb8f09ea..029f0ab6 100644 --- a/java/common/rules/java_import.bzl +++ b/java/common/rules/java_import.bzl @@ -19,7 +19,7 @@ Definition of java_import rule. load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") -visibility(["//java/..."]) +# copybara: default visibility _ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT = [ "java_library", diff --git a/java/common/rules/java_library.bzl b/java/common/rules/java_library.bzl index 8cf012f9..9c04fe7c 100644 --- a/java/common/rules/java_library.bzl +++ b/java/common/rules/java_library.bzl @@ -23,7 +23,7 @@ load("//java/common:java_semantics.bzl", "semantics") load(":basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS") load(":rule_util.bzl", "merge_attrs") -visibility(["//java/..."]) +# copybara: default visibility BootClassPathInfo = java_common.BootClassPathInfo diff --git a/java/common/rules/java_package_configuration.bzl b/java/common/rules/java_package_configuration.bzl index 1f766d07..7783e0d6 100644 --- a/java/common/rules/java_package_configuration.bzl +++ b/java/common/rules/java_package_configuration.bzl @@ -17,7 +17,7 @@ load("//java/common:java_common.bzl", "java_common") load("//java/common/rules/impl:java_helper.bzl", "helper") -visibility(["//java/..."]) +# copybara: default visibility _java_common_internal = java_common.internal_DO_NOT_USE() diff --git a/java/common/rules/java_plugin.bzl b/java/common/rules/java_plugin.bzl index 571fdff2..5b2cc936 100644 --- a/java/common/rules/java_plugin.bzl +++ b/java/common/rules/java_plugin.bzl @@ -19,7 +19,7 @@ Definition of java_plugin rule. load(":java_library.bzl", "JAVA_LIBRARY_ATTRS") load(":rule_util.bzl", "merge_attrs") -visibility(["//java/..."]) +# copybara: default visibility JAVA_PLUGIN_ATTRS = merge_attrs( JAVA_LIBRARY_ATTRS, diff --git a/java/common/rules/java_runtime.bzl b/java/common/rules/java_runtime.bzl index 43cb7c62..602819b2 100644 --- a/java/common/rules/java_runtime.bzl +++ b/java/common/rules/java_runtime.bzl @@ -21,7 +21,7 @@ load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_semantics.bzl", "PLATFORMS_ROOT") load("//java/common/rules/impl:java_helper.bzl", "helper") -visibility(["//java/..."]) +# copybara: default visibility ToolchainInfo = platform_common.ToolchainInfo diff --git a/java/common/rules/java_toolchain.bzl b/java/common/rules/java_toolchain.bzl index 1875e33e..d59fd621 100644 --- a/java/common/rules/java_toolchain.bzl +++ b/java/common/rules/java_toolchain.bzl @@ -21,7 +21,7 @@ load("//java/common/rules/impl:java_helper.bzl", "helper") load(":java_package_configuration.bzl", "JavaPackageConfigurationInfo") load(":java_runtime.bzl", "JavaRuntimeInfo") -visibility(["//java/..."]) +# copybara: default visibility _java_common_internal = java_common.internal_DO_NOT_USE() ToolchainInfo = platform_common.ToolchainInfo diff --git a/java/common/rules/rule_util.bzl b/java/common/rules/rule_util.bzl index 2b1423af..dc62252c 100644 --- a/java/common/rules/rule_util.bzl +++ b/java/common/rules/rule_util.bzl @@ -13,7 +13,7 @@ # limitations under the License. """Defines rule utilities.""" -visibility(["//java/..."]) +# copybara: default visibility def merge_attrs(*attribute_dicts, override_attrs = {}, remove_attrs = []): """Merges attributes together. From b11d9f0b6a531b0b88c156a2c882da8cffc6c9cc Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 4 Oct 2024 03:13:31 -0700 Subject: [PATCH 039/465] Use `@protobuf` instead of `@rules_proto` in `rules_java` `rules_proto` is still kept as a dependency for `@remote_java_tools` PiperOrigin-RevId: 682247564 Change-Id: I50535d2d23aa84cf62a2c7f9dec9fe1b360fcf2c --- BUILD | 1 + MODULE.bazel | 13 ++++---- java/bazel/rules/BUILD.bazel | 1 - java/common/rules/impl/BUILD | 3 ++ java/common/rules/impl/java_binary_impl.bzl | 2 +- protobuf_29.0-rc1.patch | 33 +++++++++++++++++++++ 6 files changed, 45 insertions(+), 8 deletions(-) create mode 100644 protobuf_29.0-rc1.patch diff --git a/BUILD b/BUILD index c138b7fa..51b19f77 100644 --- a/BUILD +++ b/BUILD @@ -3,6 +3,7 @@ licenses(["notice"]) exports_files([ "LICENSE", "WORKSPACE", + "protobuf_29.0-rc1.patch", ]) filegroup( diff --git a/MODULE.bazel b/MODULE.bazel index fa5b11d8..8615179d 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -9,6 +9,13 @@ bazel_dep(name = "platforms", version = "0.0.4") bazel_dep(name = "rules_cc", version = "0.0.10") bazel_dep(name = "bazel_features", version = "1.11.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") +bazel_dep(name = "protobuf", version = "29.0-rc1") +single_version_override( + module_name = "protobuf", + patch_strip = 1, + patches = ["//:protobuf_29.0-rc1.patch"], + version = "29.0-rc1", +) # Required by @remote_java_tools, which is loaded via module extension. bazel_dep(name = "rules_proto", version = "6.0.2") @@ -92,9 +99,3 @@ REMOTE_JDK_REPOS = [(("remote_jdk" if version == "8" else "remotejdk") + version # Dev dependencies bazel_dep(name = "rules_pkg", version = "0.9.1", dev_dependency = True) bazel_dep(name = "stardoc", version = "0.7.1", dev_dependency = True) - -# Override rules_python version to deal with #161 and https://github.com/bazelbuild/bazel/issues/20458 -single_version_override( - module_name = "rules_python", - version = "0.24.0", -) diff --git a/java/bazel/rules/BUILD.bazel b/java/bazel/rules/BUILD.bazel index b82b16c9..1ffd8efc 100644 --- a/java/bazel/rules/BUILD.bazel +++ b/java/bazel/rules/BUILD.bazel @@ -30,7 +30,6 @@ bzl_library( "@bazel_skylib//lib:paths", "@rules_cc//cc:find_cc_toolchain_bzl", "@rules_cc//cc/common", - "@rules_proto//proto:defs", ], ) diff --git a/java/common/rules/impl/BUILD b/java/common/rules/impl/BUILD index f9c86267..89bfaf59 100644 --- a/java/common/rules/impl/BUILD +++ b/java/common/rules/impl/BUILD @@ -12,6 +12,9 @@ bzl_library( name = "impl", srcs = glob(["*.bzl"]), visibility = ["//java:__subpackages__"], + deps = [ + "@protobuf//bazel/common:proto_info_bzl", + ], ) filegroup( diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl index 98b388be..918aff06 100644 --- a/java/common/rules/impl/java_binary_impl.bzl +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -14,9 +14,9 @@ """ Implementation of java_binary for bazel """ +load("@protobuf//bazel/common:proto_info.bzl", "ProtoInfo") load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") -load("@rules_proto//proto:defs.bzl", "ProtoInfo") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") diff --git a/protobuf_29.0-rc1.patch b/protobuf_29.0-rc1.patch new file mode 100644 index 00000000..c0332951 --- /dev/null +++ b/protobuf_29.0-rc1.patch @@ -0,0 +1,33 @@ +diff --git a/bazel/common/BUILD b/bazel/common/BUILD +index c79d22280..9ab40ff05 100644 +--- a/bazel/common/BUILD ++++ b/bazel/common/BUILD +@@ -22,7 +22,8 @@ bzl_library( + ], + visibility = ["//visibility:public"], + deps = [ +- "//bazel/private:native_bzl", ++ "//bazel/private:proto_info_bzl", ++ "@proto_bazel_features//:features", + ], + ) + +diff --git a/bazel/private/BUILD b/bazel/private/BUILD +index 9b04c1f86..8e5207f3a 100644 +--- a/bazel/private/BUILD ++++ b/bazel/private/BUILD +@@ -108,6 +108,14 @@ bzl_library( + ], + ) + ++bzl_library( ++ name = "proto_info_bzl", ++ srcs = [ ++ "proto_info.bzl", ++ ], ++ visibility = ["//bazel:__subpackages__"], ++) ++ + native_bool_flag( + name = "experimental_proto_descriptor_sets_include_source_info", + flag = "experimental_proto_descriptor_sets_include_source_info", From 9b0e4b57423dedd9a37c4bf818c20eb4e749c1c4 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 4 Oct 2024 04:05:37 -0700 Subject: [PATCH 040/465] Release `rules_java` `8.0.0-rc1` PiperOrigin-RevId: 682260942 Change-Id: Iafa36ae84640ebad6b08441bb06acf61768ba2a3 --- MODULE.bazel | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 8615179d..4f8ef2a8 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,7 +1,7 @@ module( name = "rules_java", - version = "7.12.1", - bazel_compatibility = [">=6.2.0"], + version = "8.0.0-rc1", + bazel_compatibility = [">=7.3.2"], compatibility_level = 1, ) From 692f1d359cf8128ced6097ec40cadd5bdad0268c Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 4 Oct 2024 09:01:41 -0700 Subject: [PATCH 041/465] Release `rules_java` `v8.0.0-rc2` (w/ `java_tools` `v13.10`) Downgrades protobuf to v27.0 (earliest version with `ProtoInfo` redirect), needed to play nice with `@bazel_tools` PiperOrigin-RevId: 682339966 Change-Id: I55195faba79783fdd437bfa1628c6ed7b7657a98 --- BUILD | 1 - MODULE.bazel | 10 ++-------- java/repositories.bzl | 34 +++++++++++++++++----------------- protobuf_29.0-rc1.patch | 33 --------------------------------- 4 files changed, 19 insertions(+), 59 deletions(-) delete mode 100644 protobuf_29.0-rc1.patch diff --git a/BUILD b/BUILD index 51b19f77..c138b7fa 100644 --- a/BUILD +++ b/BUILD @@ -3,7 +3,6 @@ licenses(["notice"]) exports_files([ "LICENSE", "WORKSPACE", - "protobuf_29.0-rc1.patch", ]) filegroup( diff --git a/MODULE.bazel b/MODULE.bazel index 4f8ef2a8..5c564e35 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.0.0-rc1", + version = "8.0.0-rc2", bazel_compatibility = [">=7.3.2"], compatibility_level = 1, ) @@ -9,13 +9,7 @@ bazel_dep(name = "platforms", version = "0.0.4") bazel_dep(name = "rules_cc", version = "0.0.10") bazel_dep(name = "bazel_features", version = "1.11.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") -bazel_dep(name = "protobuf", version = "29.0-rc1") -single_version_override( - module_name = "protobuf", - patch_strip = 1, - patches = ["//:protobuf_29.0-rc1.patch"], - version = "29.0-rc1", -) +bazel_dep(name = "protobuf", version = "27.0") # Required by @remote_java_tools, which is loaded via module extension. bazel_dep(name = "rules_proto", version = "6.0.2") diff --git a/java/repositories.bzl b/java/repositories.bzl index 27f4f85d..d41551e0 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.9", - "release": "false", + "version": "v13.10", + "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.9/java_tools_linux-v13.9.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.9/java_tools_linux-v13.9.zip", - "sha": "7a3d7b1cd080efdf49ab2a3818177799416734acf2bd23040aa9037141287548", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.10/java_tools_linux-v13.10.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.10/java_tools_linux-v13.10.zip", + "sha": "8d74d836be57fc92b76788c4fa605a941069cce69678ebe87e6ee02c8ad6c36b", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.9/java_tools_windows-v13.9.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.9/java_tools_windows-v13.9.zip", - "sha": "6a17ac1921d60af5dca780f4200fd0f9963441bd7afff53b9efad6e7156c699d", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.10/java_tools_windows-v13.10.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.10/java_tools_windows-v13.10.zip", + "sha": "5e63bc6382cf02c5adde702be04bb60b352811318d41aeceda4912a3ba9d4dc4", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.9/java_tools_darwin_x86_64-v13.9.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.9/java_tools_darwin_x86_64-v13.9.zip", - "sha": "802bfb5085cec0ac5745a637ae2e7a7152c54230ba542d093a10bd48ba29ba6f", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.10/java_tools_darwin_x86_64-v13.10.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.10/java_tools_darwin_x86_64-v13.10.zip", + "sha": "b6b56884d8749890ac1095b74fd2e941001673c5b3e5b9aee96fa63981a254a3", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.9/java_tools_darwin_arm64-v13.9.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.9/java_tools_darwin_arm64-v13.9.zip", - "sha": "9fa400a43153b048ae5a785e3ee533d675ed6a994ab3c763f50bd15a28544c10", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.10/java_tools_darwin_arm64-v13.10.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.10/java_tools_darwin_arm64-v13.10.zip", + "sha": "743a3e6a4021e88f16adff04b7783da3e9cbbbd63250dbb0f36aee1ed070d83c", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.9/java_tools-v13.9.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.9/java_tools-v13.9.zip", - "sha": "3b92e0c1884ac0e9683e87c3c49e1098cff91faeacdb76cc90d92efb0df861cf", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.10/java_tools-v13.10.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.10/java_tools-v13.10.zip", + "sha": "4ae903c8d51641c5cb8bf3f1dde4f1eef9d2f460d99d76e0c2116b17c55b19a6", }, }, } diff --git a/protobuf_29.0-rc1.patch b/protobuf_29.0-rc1.patch deleted file mode 100644 index c0332951..00000000 --- a/protobuf_29.0-rc1.patch +++ /dev/null @@ -1,33 +0,0 @@ -diff --git a/bazel/common/BUILD b/bazel/common/BUILD -index c79d22280..9ab40ff05 100644 ---- a/bazel/common/BUILD -+++ b/bazel/common/BUILD -@@ -22,7 +22,8 @@ bzl_library( - ], - visibility = ["//visibility:public"], - deps = [ -- "//bazel/private:native_bzl", -+ "//bazel/private:proto_info_bzl", -+ "@proto_bazel_features//:features", - ], - ) - -diff --git a/bazel/private/BUILD b/bazel/private/BUILD -index 9b04c1f86..8e5207f3a 100644 ---- a/bazel/private/BUILD -+++ b/bazel/private/BUILD -@@ -108,6 +108,14 @@ bzl_library( - ], - ) - -+bzl_library( -+ name = "proto_info_bzl", -+ srcs = [ -+ "proto_info.bzl", -+ ], -+ visibility = ["//bazel:__subpackages__"], -+) -+ - native_bool_flag( - name = "experimental_proto_descriptor_sets_include_source_info", - flag = "experimental_proto_descriptor_sets_include_source_info", From 110064d84a415b69acbfc2f02ebee7707947e37a Mon Sep 17 00:00:00 2001 From: Googler Date: Sat, 5 Oct 2024 08:40:59 -0700 Subject: [PATCH 042/465] Release `rules_java` `v8.0.0` PiperOrigin-RevId: 682670425 Change-Id: I166dbd7596da6cc5079ede7097530bf75eaafd04 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 5c564e35..08efa832 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.0.0-rc2", + version = "8.0.0", bazel_compatibility = [">=7.3.2"], compatibility_level = 1, ) From f552441945fd45e9cb258ebf73c493c90db5f72d Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 7 Oct 2024 02:50:07 -0700 Subject: [PATCH 043/465] Implement ProguardSpecInfo in Starlark MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This addresses the problem of needing --experimental_google_legacy_api for ProguardSpecProvider used by java_lite_proto_library. Although the latest Bazel 7 minor release exposes the provider without the need for a flag, the provider is impossible to obtain in prior versions without setting the flag. Replace the provider with a Starlark version, irregardless of Bazel version. This never fails and if there's a Bazel user that needs it, they are probably already advanced enough to set it up together with everything else. The risk of always using a starlark version is that some combinations don’t work - like native Android rules with Starlark proto rules. Or Starlark proto rules with native Android rules. PiperOrigin-RevId: 683101513 Change-Id: I7523438e74a2bd1913e8e05fad2f3af18db7eebd --- java/common/proguard_spec_info.bzl | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/java/common/proguard_spec_info.bzl b/java/common/proguard_spec_info.bzl index a57a0ed7..b2a591a2 100644 --- a/java/common/proguard_spec_info.bzl +++ b/java/common/proguard_spec_info.bzl @@ -13,4 +13,14 @@ # limitations under the License. """ProguardSpecInfo provider""" -ProguardSpecInfo = ProguardSpecProvider +def _proguard_spec_info_init(specs): + # The constructor supports positional parameter, i.e ProguardSpecInfo([file]) + return {"specs": specs} + +ProguardSpecInfo, _ = provider( + doc = "Information about proguard specs for Android binaries.", + fields = { + "specs": "A list of proguard specs files", + }, + init = _proguard_spec_info_init, +) From ba7fcc5a0a463eee655da93bb6cd09de80711c82 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 7 Oct 2024 04:10:24 -0700 Subject: [PATCH 044/465] Release `rules_java` `v8.0.1` (w/ `java_tools` `v13.11`) PiperOrigin-RevId: 683121139 Change-Id: I0a67cb8e34e28933c4ae33eba5982faf4901622b --- MODULE.bazel | 2 +- java/repositories.bzl | 32 ++++++++++++++++---------------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 08efa832..308c4934 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.0.0", + version = "8.0.1", bazel_compatibility = [">=7.3.2"], compatibility_level = 1, ) diff --git a/java/repositories.bzl b/java/repositories.bzl index d41551e0..0ef98f12 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.10", + "version": "v13.11", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.10/java_tools_linux-v13.10.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.10/java_tools_linux-v13.10.zip", - "sha": "8d74d836be57fc92b76788c4fa605a941069cce69678ebe87e6ee02c8ad6c36b", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.11/java_tools_linux-v13.11.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.11/java_tools_linux-v13.11.zip", + "sha": "f9b681214026eaa725e6b407e25c2cd052d10566ba4ea7baddb2f5bdb465fab7", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.10/java_tools_windows-v13.10.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.10/java_tools_windows-v13.10.zip", - "sha": "5e63bc6382cf02c5adde702be04bb60b352811318d41aeceda4912a3ba9d4dc4", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.11/java_tools_windows-v13.11.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.11/java_tools_windows-v13.11.zip", + "sha": "20068b019dd665dcab83aeda3f76af3451e84aa8f64be5a777bcf095447c4be5", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.10/java_tools_darwin_x86_64-v13.10.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.10/java_tools_darwin_x86_64-v13.10.zip", - "sha": "b6b56884d8749890ac1095b74fd2e941001673c5b3e5b9aee96fa63981a254a3", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.11/java_tools_darwin_x86_64-v13.11.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.11/java_tools_darwin_x86_64-v13.11.zip", + "sha": "6f75919c53f6d345e97668afbdcd5a9ea6648e7ed6cd743d4dfcd9f5ff22907b", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.10/java_tools_darwin_arm64-v13.10.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.10/java_tools_darwin_arm64-v13.10.zip", - "sha": "743a3e6a4021e88f16adff04b7783da3e9cbbbd63250dbb0f36aee1ed070d83c", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.11/java_tools_darwin_arm64-v13.11.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.11/java_tools_darwin_arm64-v13.11.zip", + "sha": "f18f5a307c571518d252a151393f0076b4a371651f99edcf922bb791842149ec", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.10/java_tools-v13.10.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.10/java_tools-v13.10.zip", - "sha": "4ae903c8d51641c5cb8bf3f1dde4f1eef9d2f460d99d76e0c2116b17c55b19a6", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.11/java_tools-v13.11.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.11/java_tools-v13.11.zip", + "sha": "43a8075de2ec06aea77a0c7b57abc08031645e0361850900280f8f7f4cdb72e2", }, }, } From c5a331067dfb2ba21220fe191ad664221e11fd38 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 7 Oct 2024 05:43:24 -0700 Subject: [PATCH 045/465] Add `rule_util.bzl` tests PiperOrigin-RevId: 683145308 Change-Id: I2ae3a98c02bbc5d55f91e18f03594ca00dd6ac6e --- .bazelci/presubmit.yml | 1 + java/test/BUILD | 3 +++ java/test/merge_attrs_tests.bzl | 38 +++++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 java/test/BUILD create mode 100644 java/test/merge_attrs_tests.bzl diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 43383114..66b78ae3 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -17,6 +17,7 @@ build_targets_bzlmod: &build_targets_bzlmod test_targets: &test_targets - "//test/..." + - "//java/test/..." buildifier: latest diff --git a/java/test/BUILD b/java/test/BUILD new file mode 100644 index 00000000..8a52e410 --- /dev/null +++ b/java/test/BUILD @@ -0,0 +1,3 @@ +load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") + +merge_attrs_test_suite(name = "merge_attrs_tests") diff --git a/java/test/merge_attrs_tests.bzl b/java/test/merge_attrs_tests.bzl new file mode 100644 index 00000000..84b340e3 --- /dev/null +++ b/java/test/merge_attrs_tests.bzl @@ -0,0 +1,38 @@ +"""Tests for merge_attrsfunction""" + +load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") +load( + "//java/common/rules:rule_util.bzl", + "merge_attrs", +) + +_attr_string = attr.string() +_attr_string_different_ref = attr.string() +_attr_string_different = attr.string(default = "Some default") + +def _merge_attrs_merges_impl(ctx): + env = unittest.begin(ctx) + + attrs = merge_attrs( + {"A": _attr_string}, + {"B": _attr_string_different_ref, "C": _attr_string_different}, + override_attrs = {"B": _attr_string_different}, + remove_attrs = ["C"], + ) + + asserts.equals(env, attrs, {"A": _attr_string, "B": _attr_string_different}) + + return unittest.end(env) + +merge_attrs_merges_test = unittest.make(_merge_attrs_merges_impl) + +def merge_attrs_test_suite(name): + """Sets up util test suite + + Args: + name: the name of the test suite target + """ + unittest.suite( + name, + merge_attrs_merges_test, + ) From 886c1132571f646c9b68eb36da35267ab63ac45d Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 8 Oct 2024 01:43:34 -0700 Subject: [PATCH 046/465] Remove rules_proto dependency PiperOrigin-RevId: 683519641 Change-Id: I0f74eeb7cfb8b8b4eff498f5e0b9abb8dc808f7a --- MODULE.bazel | 1 - java/BUILD | 2 ++ java/defs.bzl | 6 ++++-- java/defs.bzl.oss | 51 +++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 java/defs.bzl.oss diff --git a/MODULE.bazel b/MODULE.bazel index 308c4934..efdad893 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -12,7 +12,6 @@ bazel_dep(name = "bazel_skylib", version = "1.6.1") bazel_dep(name = "protobuf", version = "27.0") # Required by @remote_java_tools, which is loaded via module extension. -bazel_dep(name = "rules_proto", version = "6.0.2") bazel_dep(name = "rules_license", version = "0.0.3") bazel_dep(name = "abseil-cpp", version = "20230802.1", repo_name = "com_google_absl") diff --git a/java/BUILD b/java/BUILD index 62875608..66bfb075 100644 --- a/java/BUILD +++ b/java/BUILD @@ -26,6 +26,8 @@ bzl_library( ":core_rules", "//java/common", "//java/toolchains:toolchain_rules", + "@protobuf//bazel:java_lite_proto_library_bzl", + "@protobuf//bazel:java_proto_library_bzl", ], ) diff --git a/java/defs.bzl b/java/defs.bzl index 64de71a4..e73d633f 100644 --- a/java/defs.bzl +++ b/java/defs.bzl @@ -13,6 +13,8 @@ # limitations under the License. """Starlark rules for building Java projects.""" +load("@protobuf//bazel:java_lite_proto_library.bzl", _java_lite_proto_library = "java_lite_proto_library") +load("@protobuf//bazel:java_proto_library.bzl", _java_proto_library = "java_proto_library") load("//java:java_binary.bzl", _java_binary = "java_binary") load("//java:java_import.bzl", _java_import = "java_import") load("//java:java_library.bzl", _java_library = "java_library") @@ -41,8 +43,8 @@ java_package_configuration = _java_package_configuration # Proto rules # Deprecated: don't use java proto libraries from here -java_proto_library = native.java_proto_library -java_lite_proto_library = native.java_lite_proto_library +java_proto_library = _java_proto_library +java_lite_proto_library = _java_lite_proto_library # Modules and providers diff --git a/java/defs.bzl.oss b/java/defs.bzl.oss new file mode 100644 index 00000000..28f61cae --- /dev/null +++ b/java/defs.bzl.oss @@ -0,0 +1,51 @@ +# Copyright 2019 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. +"""Starlark rules for building Java projects.""" + +load("//third_party/bazel_rules/rules_java/java:java_binary.bzl", _java_binary = "java_binary") +load("//third_party/bazel_rules/rules_java/java:java_import.bzl", _java_import = "java_import") +load("//third_party/bazel_rules/rules_java/java:java_library.bzl", _java_library = "java_library") +load("//third_party/bazel_rules/rules_java/java:java_plugin.bzl", _java_plugin = "java_plugin") +load("//third_party/bazel_rules/rules_java/java:java_test.bzl", _java_test = "java_test") +load("//third_party/bazel_rules/rules_java/java/common:java_common.bzl", _java_common = "java_common") +load("//third_party/bazel_rules/rules_java/java/common:java_info.bzl", _JavaInfo = "JavaInfo") +load("//third_party/bazel_rules/rules_java/java/common:java_plugin_info.bzl", _JavaPluginInfo = "JavaPluginInfo") +load("//third_party/bazel_rules/rules_java/java/toolchains:java_package_configuration.bzl", _java_package_configuration = "java_package_configuration") +load("//third_party/bazel_rules/rules_java/java/toolchains:java_runtime.bzl", _java_runtime = "java_runtime") +load("//third_party/bazel_rules/rules_java/java/toolchains:java_toolchain.bzl", _java_toolchain = "java_toolchain") + +# Language rules + +java_binary = _java_binary +java_test = _java_test +java_library = _java_library +java_plugin = _java_plugin +java_import = _java_import + +# Toolchain rules + +java_runtime = _java_runtime +java_toolchain = _java_toolchain +java_package_configuration = _java_package_configuration + +# Proto rules +# Deprecated: don't use java proto libraries from here +java_proto_library = native.java_proto_library +java_lite_proto_library = native.java_lite_proto_library + +# Modules and providers + +JavaInfo = _JavaInfo +JavaPluginInfo = _JavaPluginInfo +java_common = _java_common From a66a4d0dabbb1837fa3ac75c63acce2d28adca96 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 8 Oct 2024 01:43:39 -0700 Subject: [PATCH 047/465] Redirect java proto libraries to protobuf PiperOrigin-RevId: 683519662 Change-Id: I092615f52d9317e1937c730d66cfc19211feb163 --- java/defs.bzl.oss | 51 ----------------------------------------------- 1 file changed, 51 deletions(-) delete mode 100644 java/defs.bzl.oss diff --git a/java/defs.bzl.oss b/java/defs.bzl.oss deleted file mode 100644 index 28f61cae..00000000 --- a/java/defs.bzl.oss +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright 2019 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. -"""Starlark rules for building Java projects.""" - -load("//third_party/bazel_rules/rules_java/java:java_binary.bzl", _java_binary = "java_binary") -load("//third_party/bazel_rules/rules_java/java:java_import.bzl", _java_import = "java_import") -load("//third_party/bazel_rules/rules_java/java:java_library.bzl", _java_library = "java_library") -load("//third_party/bazel_rules/rules_java/java:java_plugin.bzl", _java_plugin = "java_plugin") -load("//third_party/bazel_rules/rules_java/java:java_test.bzl", _java_test = "java_test") -load("//third_party/bazel_rules/rules_java/java/common:java_common.bzl", _java_common = "java_common") -load("//third_party/bazel_rules/rules_java/java/common:java_info.bzl", _JavaInfo = "JavaInfo") -load("//third_party/bazel_rules/rules_java/java/common:java_plugin_info.bzl", _JavaPluginInfo = "JavaPluginInfo") -load("//third_party/bazel_rules/rules_java/java/toolchains:java_package_configuration.bzl", _java_package_configuration = "java_package_configuration") -load("//third_party/bazel_rules/rules_java/java/toolchains:java_runtime.bzl", _java_runtime = "java_runtime") -load("//third_party/bazel_rules/rules_java/java/toolchains:java_toolchain.bzl", _java_toolchain = "java_toolchain") - -# Language rules - -java_binary = _java_binary -java_test = _java_test -java_library = _java_library -java_plugin = _java_plugin -java_import = _java_import - -# Toolchain rules - -java_runtime = _java_runtime -java_toolchain = _java_toolchain -java_package_configuration = _java_package_configuration - -# Proto rules -# Deprecated: don't use java proto libraries from here -java_proto_library = native.java_proto_library -java_lite_proto_library = native.java_lite_proto_library - -# Modules and providers - -JavaInfo = _JavaInfo -JavaPluginInfo = _JavaPluginInfo -java_common = _java_common From 708d0ccb19525f1100dc7f38fe8f42efcfe9cff2 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 8 Oct 2024 02:53:48 -0700 Subject: [PATCH 048/465] Add proto_support to for_bazel_tests PiperOrigin-RevId: 683540374 Change-Id: I55a9fcf0ad0b191d95225abc6b2cab7f7dc02e6e --- java/private/BUILD | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/java/private/BUILD b/java/private/BUILD index 69481997..36c4fe65 100644 --- a/java/private/BUILD +++ b/java/private/BUILD @@ -10,6 +10,13 @@ bzl_library( visibility = ["//java:__subpackages__"], ) +bzl_library( + name = "proto_support", + srcs = ["proto_support.bzl"], + visibility = ["@protobuf//bazel:__subpackages__"], + deps = [":private"], +) + filegroup( name = "srcs", srcs = glob(["**"]), @@ -22,6 +29,7 @@ filegroup( srcs = [ "BUILD", ":private", + ":proto_support", ], visibility = ["//java:__pkg__"], ) From 87e5aac3503a2c17d048ce8d3a84569a0d54d934 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 8 Oct 2024 03:01:00 -0700 Subject: [PATCH 049/465] Change the default java `source_version` / `target_version` to `11` Using a language version of 8 and running with jdk21 (or later) results in: ``` warning: [options] source value 8 is obsolete and will be removed in a future release warning: [options] target value 8 is obsolete and will be removed in a future release warning: [options] To suppress warnings about obsolete options, use -Xlint:-options. ``` PiperOrigin-RevId: 683542164 Change-Id: Icc9600af2543720ff98a9d695cdd526f59612b9c --- toolchains/default_java_toolchain.bzl | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl index a92a1f93..8cbb17a8 100644 --- a/toolchains/default_java_toolchain.bzl +++ b/toolchains/default_java_toolchain.bzl @@ -68,6 +68,10 @@ DEFAULT_JAVACOPTS = [ "-Xep:UseCorrectAssertInTests:OFF", ] +# If this is changed, the docs for "{,tool_}java_language_version" also +# need to be updated in the Bazel user manual +_DEFAULT_JAVA_LANGUAGE_VERSION = "11" + # Default java_toolchain parameters _BASE_TOOLCHAIN_CONFIGURATION = dict( forcibly_disable_header_compilation = False, @@ -88,8 +92,8 @@ _BASE_TOOLCHAIN_CONFIGURATION = dict( # Code to enumerate target JVM boot classpath uses host JVM. Because # java_runtime-s are involved, its implementation is in @bazel_tools. bootclasspath = [Label("//toolchains:platformclasspath")], - source_version = "8", - target_version = "8", + source_version = _DEFAULT_JAVA_LANGUAGE_VERSION, + target_version = _DEFAULT_JAVA_LANGUAGE_VERSION, reduced_classpath_incompatible_processors = [ "dagger.hilt.processor.internal.root.RootProcessor", # see b/21307381 ], @@ -137,10 +141,6 @@ NONPREBUILT_TOOLCHAIN_CONFIGURATION = dict( oneversion = Label("@remote_java_tools//:one_version_cc_bin"), ) -# If this is changed, the docs for "{,tool_}java_language_version" also -# need to be updated in the Bazel user manual -_DEFAULT_SOURCE_VERSION = "8" - def default_java_toolchain(name, configuration = DEFAULT_TOOLCHAIN_CONFIGURATION, toolchain_definition = True, exec_compatible_with = [], target_compatible_with = [], **kwargs): """Defines a remote java_toolchain with appropriate defaults for Bazel. @@ -164,7 +164,7 @@ def default_java_toolchain(name, configuration = DEFAULT_TOOLCHAIN_CONFIGURATION ) if toolchain_definition: source_version = toolchain_args["source_version"] - if source_version == _DEFAULT_SOURCE_VERSION: + if source_version == _DEFAULT_JAVA_LANGUAGE_VERSION: native.config_setting( name = name + "_default_version_setting", values = {"java_language_version": ""}, From 071069d0f20b1e39e11de5779947af366ac828c1 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 8 Oct 2024 05:03:25 -0700 Subject: [PATCH 050/465] Fix `auto_create_deploy_jars` in `java_binary` for IntelliJ PiperOrigin-RevId: 683574444 Change-Id: I4d1fe8e90392c37cc873ad97f079c9f3d9b401d5 --- java/common/rules/impl/java_binary_impl.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl index 918aff06..80adbb5e 100644 --- a/java/common/rules/impl/java_binary_impl.bzl +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -447,7 +447,7 @@ def _auto_create_deploy_jar(ctx, info, launcher_info, main_class, coverage_main_ resources = java_attrs.resources, classpath_resources = java_attrs.classpath_resources, runtime_classpath = runtime_classpath, - manifest_lines = info.manifest_lines, + manifest_lines = [], build_info_files = [], build_target = str(ctx.label), output = output, From a405ce01716673102ac35e82fc0cb9b06ce03d87 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 8 Oct 2024 06:11:28 -0700 Subject: [PATCH 051/465] Release `rules_java` `v8.1.0` PiperOrigin-RevId: 683593444 Change-Id: I33cc7336626224671ca9e5201bf75e067cb246f4 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index efdad893..09611e87 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.0.1", + version = "8.1.0", bazel_compatibility = [">=7.3.2"], compatibility_level = 1, ) From c98aab70aa4b806174f012ecf686ef695a986389 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 8 Oct 2024 09:09:08 -0700 Subject: [PATCH 052/465] Remove proto testing deps from rules_java rules_java don't need to depend on proto code. There are tests in Apple that needs is though. BEGIN_PUBLIC Internal change END_PUBLIC PiperOrigin-RevId: 683646824 Change-Id: I3eb9c4ddf4c11cce800e715a2cb03c3fcf49e39f --- java/private/BUILD | 1 - 1 file changed, 1 deletion(-) diff --git a/java/private/BUILD b/java/private/BUILD index 36c4fe65..7d682cdb 100644 --- a/java/private/BUILD +++ b/java/private/BUILD @@ -13,7 +13,6 @@ bzl_library( bzl_library( name = "proto_support", srcs = ["proto_support.bzl"], - visibility = ["@protobuf//bazel:__subpackages__"], deps = [":private"], ) From e6009ef8f8c3c26e3088324ed1f48811fcf20fe4 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 10 Oct 2024 02:53:30 -0700 Subject: [PATCH 053/465] Fix proto_support visibility I can't generate proto documentation without making bzl_library visible. PiperOrigin-RevId: 684368893 Change-Id: I45fdb813146fe9fbeda16a4900af8d1ffcc84562 --- java/private/BUILD | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/java/private/BUILD b/java/private/BUILD index 7d682cdb..75e6e187 100644 --- a/java/private/BUILD +++ b/java/private/BUILD @@ -4,9 +4,7 @@ licenses(["notice"]) bzl_library( name = "private", - srcs = [ - "native.bzl", - ], + srcs = ["native.bzl"], visibility = ["//java:__subpackages__"], ) From 011672368264355ee0ad25c44396cf9023b60de4 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 10 Oct 2024 09:47:41 -0700 Subject: [PATCH 054/465] Add support for configuring `--system` using `java_package_configuration` Also use `cfg = "target"` for `java_toolchain.package_configuration` to ensure `java_package_configuration.system` is built in the target config, and do the exec transition later for `java_package_configuration.data` (which we do want in the exec config). The system needs to match the target Java language configuration, the data is an exec dependency used at built-time. PiperOrigin-RevId: 684478368 Change-Id: Iaa2020525b204cf9eabc0cd1830cb3bdc40da683 --- java/common/rules/java_package_configuration.bzl | 12 ++++++++++++ java/common/rules/java_toolchain.bzl | 2 +- java/docs/rules.md | 3 ++- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/java/common/rules/java_package_configuration.bzl b/java/common/rules/java_package_configuration.bzl index 7783e0d6..49b24053 100644 --- a/java/common/rules/java_package_configuration.bzl +++ b/java/common/rules/java_package_configuration.bzl @@ -21,6 +21,8 @@ load("//java/common/rules/impl:java_helper.bzl", "helper") _java_common_internal = java_common.internal_DO_NOT_USE() +BootClassPathInfo = java_common.BootClassPathInfo + JavaPackageConfigurationInfo = provider( "A provider for Java per-package configuration", fields = [ @@ -28,6 +30,7 @@ JavaPackageConfigurationInfo = provider( "javac_opts", "matches", "package_specs", + "system", ], ) @@ -41,6 +44,7 @@ def _rule_impl(ctx): javacopts = _java_common_internal.expand_java_opts(ctx, "javacopts", tokenize = True) javacopts_depset = helper.detokenize_javacopts(javacopts) package_specs = [package[PackageSpecificationInfo] for package in ctx.attr.packages] + system = ctx.attr.system[BootClassPathInfo] if ctx.attr.system else None return [ DefaultInfo(), JavaPackageConfigurationInfo( @@ -48,6 +52,7 @@ def _rule_impl(ctx): javac_opts = javacopts_depset, matches = lambda label: _matches(package_specs, label), package_specs = package_specs, + system = system, ), ] @@ -104,11 +109,18 @@ Java compiler flags. """, ), "data": attr.label_list( + cfg = "exec", allow_files = True, doc = """ The list of files needed by this configuration at runtime. """, ), + "system": attr.label( + providers = [BootClassPathInfo], + doc = """ +Corresponds to javac's --system flag. +""", + ), # buildifier: disable=attr-licenses "output_licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), }, diff --git a/java/common/rules/java_toolchain.bzl b/java/common/rules/java_toolchain.bzl index d59fd621..174733dc 100644 --- a/java/common/rules/java_toolchain.bzl +++ b/java/common/rules/java_toolchain.bzl @@ -522,7 +522,7 @@ Label of the one-version allowlist for tests. """, ), "package_configuration": attr.label_list( - cfg = "exec", + cfg = "target", providers = [JavaPackageConfigurationInfo], doc = """ Configuration that should be applied to the specified package groups. diff --git a/java/docs/rules.md b/java/docs/rules.md index 974b93ff..e64e05ca 100644 --- a/java/docs/rules.md +++ b/java/docs/rules.md @@ -247,7 +247,7 @@ java_library(name, -java_package_configuration(name, data, javacopts, output_licenses, packages) +java_package_configuration(name, data, javacopts, output_licenses, packages, system)

@@ -295,6 +295,7 @@ java_toolchain( | javacopts | Java compiler flags. | List of strings | optional | `[]` | | output_licenses | - | List of strings | optional | `[]` | | packages | The set of package_groups the configuration should be applied to. | List of labels | optional | `[]` | +| system | Corresponds to javac's --system flag. | Label | optional | `None` | From 79c6e69f76e7d061853cafbaca0eff6b1f284370 Mon Sep 17 00:00:00 2001 From: Ivo List Date: Fri, 11 Oct 2024 02:22:16 -0700 Subject: [PATCH 055/465] Remove @rules_cc//cc:defs.bzl references Copybara Import from https://github.com/bazelbuild/rules_java/pull/228 BEGIN_PUBLIC Remove @rules_cc//cc:defs.bzl references (#228) Referring to @rules_cc//cc:defs.bzl, refers to @protobuf//bazel:java_proto_library.bzl, which fetches protobuf repository. Referring directly to what's needed limits the fetches just to rules_cc. Closes #228 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/228 from comius:remove-cc-defs e1f3016584ecd873b0a6464f34c5c5ad0b778159 PiperOrigin-RevId: 684759221 Change-Id: I53856709635e6f6d35f3ae67dc57f2857af1db6f --- MODULE.bazel | 2 +- toolchains/BUILD | 2 +- toolchains/default_java_toolchain.bzl | 2 +- toolchains/jdk_build_file.bzl | 2 +- toolchains/local_java_repository.bzl | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 09611e87..ef6c420c 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -6,7 +6,7 @@ module( ) bazel_dep(name = "platforms", version = "0.0.4") -bazel_dep(name = "rules_cc", version = "0.0.10") +bazel_dep(name = "rules_cc", version = "0.0.13") bazel_dep(name = "bazel_features", version = "1.11.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") bazel_dep(name = "protobuf", version = "27.0") diff --git a/toolchains/BUILD b/toolchains/BUILD index f78c3b9e..191c3115 100644 --- a/toolchains/BUILD +++ b/toolchains/BUILD @@ -1,5 +1,5 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") -load("@rules_cc//cc:defs.bzl", "cc_library") +load("@rules_cc//cc:cc_library.bzl", "cc_library") load( ":default_java_toolchain.bzl", "DEFAULT_TOOLCHAIN_CONFIGURATION", diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl index 8cbb17a8..0c81bdb2 100644 --- a/toolchains/default_java_toolchain.bzl +++ b/toolchains/default_java_toolchain.bzl @@ -14,8 +14,8 @@ """Rules for defining default_java_toolchain""" -load("//java:defs.bzl", "java_toolchain") load("//java/common:java_common.bzl", "java_common") +load("//java/toolchains:java_toolchain.bzl", "java_toolchain") # JVM options, without patching java.compiler and jdk.compiler modules. BASE_JDK9_JVM_OPTS = [ diff --git a/toolchains/jdk_build_file.bzl b/toolchains/jdk_build_file.bzl index 1e08f376..c0ed1608 100644 --- a/toolchains/jdk_build_file.bzl +++ b/toolchains/jdk_build_file.bzl @@ -14,7 +14,7 @@ """A templated BUILD file for Java repositories.""" -JDK_BUILD_TEMPLATE = """load("@rules_java//java:defs.bzl", "java_runtime") +JDK_BUILD_TEMPLATE = """load("@rules_java//java/toolchains:java_runtime.bzl", "java_runtime") package(default_visibility = ["//visibility:public"]) diff --git a/toolchains/local_java_repository.bzl b/toolchains/local_java_repository.bzl index e0123673..17b1a0e7 100644 --- a/toolchains/local_java_repository.bzl +++ b/toolchains/local_java_repository.bzl @@ -14,7 +14,7 @@ """Rules for importing a local JDK.""" -load("//java:defs.bzl", "java_runtime") +load("//java/toolchains:java_runtime.bzl", "java_runtime") load(":default_java_toolchain.bzl", "default_java_toolchain") def _detect_java_version(repository_ctx, java_bin): From 94d5617cf3d97ddda10c81ba05a865e8e3a0408e Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 11 Oct 2024 02:59:51 -0700 Subject: [PATCH 056/465] Make proto_support bzl_library visible PiperOrigin-RevId: 684767814 Change-Id: I37ff05039ad64ac7ee20c88910e4832c3090404c --- java/private/BUILD | 2 ++ 1 file changed, 2 insertions(+) diff --git a/java/private/BUILD b/java/private/BUILD index 75e6e187..5afe66c3 100644 --- a/java/private/BUILD +++ b/java/private/BUILD @@ -8,9 +8,11 @@ bzl_library( visibility = ["//java:__subpackages__"], ) +# Exposed for use by the protobuf. bzl_library( name = "proto_support", srcs = ["proto_support.bzl"], + visibility = ["//visibility:public"], deps = [":private"], ) From 9226c76e4f2f5e802f65423c86fde8d9244844a6 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 14 Oct 2024 05:47:04 -0700 Subject: [PATCH 057/465] Remove dependency on builtins-internal symbol `CcNativeLibraryInfo` from `java_info.bzl` PiperOrigin-RevId: 685676319 Change-Id: I16377a2d2070a77d7c76054eb9dadf445d76e1a3 --- java/common/java_semantics.bzl | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/java/common/java_semantics.bzl b/java/common/java_semantics.bzl index c5cb2830..ec17c92d 100644 --- a/java/common/java_semantics.bzl +++ b/java/common/java_semantics.bzl @@ -38,6 +38,9 @@ def _compatible_javac_options(*_args): def _check_java_info_opens_exports(): pass +def _minimize_cc_info(cc_info): + return cc_info + _DOCS = struct( ATTRS = { "resources": """ @@ -104,4 +107,5 @@ semantics = struct( DOCS = struct( for_attribute = lambda name: _DOCS.ATTRS.get(name, ""), ), + minimize_cc_info = _minimize_cc_info, ) From 5fe8347f73056e7649af2116c2f40a93bb088c83 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 15 Oct 2024 07:39:41 -0700 Subject: [PATCH 058/465] Add `-XDshould-stop.ifError=FLOW` to the default javacopts. See https://github.com/google/error-prone/issues/4595 for motivation. This fixes a bug with the interaction between javac and Error Prone, but also improves diagnostic quality in general by showing more errors if there are multiple problems and multiple files being compiled. PiperOrigin-RevId: 686100365 Change-Id: I2e5e6dffdbbe1ca6480369a51a7ea3445db78a8a --- toolchains/default_java_toolchain.bzl | 1 + 1 file changed, 1 insertion(+) diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl index 0c81bdb2..9efc2f32 100644 --- a/toolchains/default_java_toolchain.bzl +++ b/toolchains/default_java_toolchain.bzl @@ -56,6 +56,7 @@ JDK9_JVM_OPTS = BASE_JDK9_JVM_OPTS DEFAULT_JAVACOPTS = [ "-XDskipDuplicateBridges=true", "-XDcompilePolicy=simple", + "-XDshould-stop.ifError=FLOW", # See b/27049950, https://github.com/google/error-prone/issues/4595 "-g", "-parameters", # https://github.com/bazelbuild/bazel/issues/15219 From 21bdf1e2391ed07bff9124fc40d36432bfc0cfcd Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 16 Oct 2024 04:43:29 -0700 Subject: [PATCH 059/465] Fix `rules_java` presubmits - Update to `java_tools` `v13.12` (was missing a load for java_binary) - Disable building `rules_java` docs with Bazel@HEAD. Protobuf (needed by stardoc) is currently broken with Bazel@HEAD because of deleting the python & java rules. Unless we want to patch protobuf locally (as in Bazel), we need to wait for a final protobuf release. PiperOrigin-RevId: 686461122 Change-Id: Id15e93e6784134684a0226b6bfedca2f17a50bd2 --- .bazelci/presubmit.yml | 9 ++++++++- java/repositories.bzl | 32 ++++++++++++++++---------------- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 66b78ae3..15c774d5 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -53,7 +53,14 @@ tasks: name: "Bazel@HEAD" bazel: last_green platform: ubuntu2004 - build_targets: *build_targets + build_targets: + # TODO: use *build_targets after protobuf is fixed + - "//..." + - "@remote_java_tools//java_tools/..." + - "-//toolchains/..." + - "-//test/repo/..." + - "-//java/docs/..." + - "-//test:docs_up_to_date_test" ubuntu2004_integration_head: name: "Bazel@HEAD Integration" bazel: last_green diff --git a/java/repositories.bzl b/java/repositories.bzl index 0ef98f12..50e7b760 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.11", + "version": "v13.12", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.11/java_tools_linux-v13.11.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.11/java_tools_linux-v13.11.zip", - "sha": "f9b681214026eaa725e6b407e25c2cd052d10566ba4ea7baddb2f5bdb465fab7", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.12/java_tools_linux-v13.12.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.12/java_tools_linux-v13.12.zip", + "sha": "ecdf36b1d93d1e6c270f6acf6e9cfd95b6ce52ce5e798f8a57aae6041d881cb9", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.11/java_tools_windows-v13.11.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.11/java_tools_windows-v13.11.zip", - "sha": "20068b019dd665dcab83aeda3f76af3451e84aa8f64be5a777bcf095447c4be5", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.12/java_tools_windows-v13.12.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.12/java_tools_windows-v13.12.zip", + "sha": "da590aa0bbc4f2967edcb7cc05cd0260412b6b057f9256bdd518a262a5f483c7", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.11/java_tools_darwin_x86_64-v13.11.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.11/java_tools_darwin_x86_64-v13.11.zip", - "sha": "6f75919c53f6d345e97668afbdcd5a9ea6648e7ed6cd743d4dfcd9f5ff22907b", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.12/java_tools_darwin_x86_64-v13.12.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.12/java_tools_darwin_x86_64-v13.12.zip", + "sha": "2a5c700567cae1f3dcfe42e702ee2fc5b1e4b66dfc13e8a2b5ccdddf12910e55", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.11/java_tools_darwin_arm64-v13.11.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.11/java_tools_darwin_arm64-v13.11.zip", - "sha": "f18f5a307c571518d252a151393f0076b4a371651f99edcf922bb791842149ec", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.12/java_tools_darwin_arm64-v13.12.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.12/java_tools_darwin_arm64-v13.12.zip", + "sha": "97159db5a1f54301bc067ef1773c1eb7f7bc2f875bcb97a9e15baf4b08b129f2", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.11/java_tools-v13.11.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.11/java_tools-v13.11.zip", - "sha": "43a8075de2ec06aea77a0c7b57abc08031645e0361850900280f8f7f4cdb72e2", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.12/java_tools-v13.12.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.12/java_tools-v13.12.zip", + "sha": "5f065d70984f607d1560f023348158bbbf6babdf4c4bbdd528ee867628b7fa1e", }, }, } From 9a8d8f32acb98e6a77ab2c455d24683623b14960 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 16 Oct 2024 08:02:26 -0700 Subject: [PATCH 060/465] Update `--should-stop=ifError=FLOW` flags This is equivalent to `-XDshould-stop.ifError=FLOW`, but the `-XD` flag is a internal javac debug flag interface that writes directly to the options table. The `--should-stop` flags are slightly more standard. PiperOrigin-RevId: 686508919 Change-Id: If71a8508b14b5c4628cdcabb255f638df32ac230 --- toolchains/default_java_toolchain.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl index 9efc2f32..a6d200b7 100644 --- a/toolchains/default_java_toolchain.bzl +++ b/toolchains/default_java_toolchain.bzl @@ -56,7 +56,7 @@ JDK9_JVM_OPTS = BASE_JDK9_JVM_OPTS DEFAULT_JAVACOPTS = [ "-XDskipDuplicateBridges=true", "-XDcompilePolicy=simple", - "-XDshould-stop.ifError=FLOW", # See b/27049950, https://github.com/google/error-prone/issues/4595 + "--should-stop=ifError=FLOW", # See b/27049950, https://github.com/google/error-prone/issues/4595 "-g", "-parameters", # https://github.com/bazelbuild/bazel/issues/15219 From 2f45e203576084b7aa6b9019057eefd8c3070d5b Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 21 Oct 2024 23:58:03 -0700 Subject: [PATCH 061/465] Copy the remaining java rule code out of `@_builtins` These aren't usable just yet, will need to wait for a Bazel release PiperOrigin-RevId: 688422592 Change-Id: I46884b630a5dd3b44c316c06b55f246368ce6c1e --- java/BUILD | 2 +- java/common/BUILD | 2 +- java/common/rules/impl/BUILD | 12 +- java/private/BUILD | 29 +- java/private/boot_class_path_info.bzl | 65 ++ java/private/java_common.bzl | 320 +++++++++ java/private/java_info.bzl | 974 ++++++++++++++++++++++++++ java/private/message_bundle_info.bzl | 26 + java/toolchains/BUILD | 2 +- 9 files changed, 1424 insertions(+), 8 deletions(-) create mode 100644 java/private/boot_class_path_info.bzl create mode 100644 java/private/java_common.bzl create mode 100644 java/private/java_info.bzl create mode 100644 java/private/message_bundle_info.bzl diff --git a/java/BUILD b/java/BUILD index 66bfb075..3e6823ff 100644 --- a/java/BUILD +++ b/java/BUILD @@ -47,7 +47,7 @@ bzl_library( "//java/bazel/rules", # copybara-use-repo-external-label "//java/common", "//java/common/rules:core_rules", - "//java/private", + "//java/private:native_bzl", ], ) diff --git a/java/common/BUILD b/java/common/BUILD index d8f22f7b..01fab794 100644 --- a/java/common/BUILD +++ b/java/common/BUILD @@ -16,7 +16,7 @@ bzl_library( name = "common", srcs = glob(["*.bzl"]), visibility = ["//visibility:public"], - deps = ["//java/private"], + deps = ["//java/private:native_bzl"], ) filegroup( diff --git a/java/common/rules/impl/BUILD b/java/common/rules/impl/BUILD index 89bfaf59..a1c0f91b 100644 --- a/java/common/rules/impl/BUILD +++ b/java/common/rules/impl/BUILD @@ -10,13 +10,23 @@ filegroup( bzl_library( name = "impl", - srcs = glob(["*.bzl"]), + srcs = glob( + ["*.bzl"], + exclude = ["java_helper.bzl"], + ), visibility = ["//java:__subpackages__"], deps = [ + ":java_helper_bzl", "@protobuf//bazel/common:proto_info_bzl", ], ) +bzl_library( + name = "java_helper_bzl", + srcs = ["java_helper.bzl"], + visibility = ["//java:__subpackages__"], +) + filegroup( name = "for_bazel_tests", testonly = 1, diff --git a/java/private/BUILD b/java/private/BUILD index 5afe66c3..8197421d 100644 --- a/java/private/BUILD +++ b/java/private/BUILD @@ -3,17 +3,38 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") licenses(["notice"]) bzl_library( - name = "private", - srcs = ["native.bzl"], + name = "native_bzl", + srcs = [ + "native.bzl", + ], visibility = ["//java:__subpackages__"], ) +bzl_library( + name = "internals", + srcs = [ + "boot_class_path_info.bzl", + "java_common.bzl", + "java_info.bzl", + "message_bundle_info.bzl", + ], + visibility = ["//java:__subpackages__"], + deps = [ + ":native_bzl", + "//java/common", + "//java/common/rules:toolchain_rules", + "//java/common/rules/impl:java_helper_bzl", + "@bazel_skylib//lib:paths", + "@rules_cc//cc/common", + ], +) + # Exposed for use by the protobuf. bzl_library( name = "proto_support", srcs = ["proto_support.bzl"], visibility = ["//visibility:public"], - deps = [":private"], + deps = [":native_bzl"], ) filegroup( @@ -27,7 +48,7 @@ filegroup( testonly = 1, srcs = [ "BUILD", - ":private", + ":native_bzl", ":proto_support", ], visibility = ["//java:__pkg__"], diff --git a/java/private/boot_class_path_info.bzl b/java/private/boot_class_path_info.bzl new file mode 100644 index 00000000..7280da31 --- /dev/null +++ b/java/private/boot_class_path_info.bzl @@ -0,0 +1,65 @@ +# Copyright 2023 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. + +""" +Definition of the BootClassPathInfo provider. +""" + +load("@bazel_skylib//lib:paths.bzl", "paths") + +visibility("private") + +def _init(bootclasspath = [], auxiliary = [], system = None): + """The BootClassPathInfo constructor. + + Args: + bootclasspath: ([File]) + auxiliary: ([File]) + system: ([File]|File|None) + """ + if not system: # None or [] + system_inputs = depset() + system_path = None + elif type(system) == "File": + system_inputs = depset([system]) + if not system.is_directory: + fail("for system,", system, "is not a directory") + system_path = system.path + elif type(system) == type([]): + system_inputs = depset(system) + system_paths = [input.path for input in system if input.basename == "release"] + if not system_paths: + fail("for system, expected inputs to contain 'release'") + system_path = paths.dirname(system_paths[0]) + else: + fail("for system, got", type(system), ", want File, sequence, or None") + + return { + "bootclasspath": depset(bootclasspath), + "_auxiliary": depset(auxiliary), + "_system_inputs": system_inputs, + "_system_path": system_path, + } + +BootClassPathInfo, _new_bootclasspathinfo = provider( + doc = "Information about the system APIs for a Java compilation.", + fields = [ + "bootclasspath", + # private + "_auxiliary", + "_system_inputs", + "_system_path", + ], + init = _init, +) diff --git a/java/private/java_common.bzl b/java/private/java_common.bzl new file mode 100644 index 00000000..5175ac55 --- /dev/null +++ b/java/private/java_common.bzl @@ -0,0 +1,320 @@ +# Copyright 2023 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. + +""" Utilities for Java compilation support in Starlark. """ + +load("@bazel_skylib//lib:paths.bzl", "paths") +load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_runtime.bzl", "JavaRuntimeInfo") +load("//java/common/rules:java_toolchain.bzl", "JavaToolchainInfo") +load("//java/common/rules/impl:java_helper.bzl", "helper") +load(":boot_class_path_info.bzl", "BootClassPathInfo") +load( + ":java_info.bzl", + "JavaInfo", + "JavaPluginInfo", + _java_info_add_constraints = "add_constraints", + _java_info_make_non_strict = "make_non_strict", + _java_info_merge = "merge", + _java_info_set_annotation_processing = "set_annotation_processing", +) +load(":message_bundle_info.bzl", "MessageBundleInfo") +load(":native.bzl", _native_java_common = "native_java_common") + +visibility("private") + +_java_common_internal = _native_java_common.internal_DO_NOT_USE() + +JavaRuntimeClasspathInfo = provider( + "Provider for the runtime classpath contributions of a Java binary.", + fields = ["runtime_classpath"], +) + +def _compile( + ctx, + output, + java_toolchain, + source_jars = [], + source_files = [], + output_source_jar = None, + javac_opts = [], + deps = [], + runtime_deps = [], + exports = [], + plugins = [], + exported_plugins = [], + native_libraries = [], + annotation_processor_additional_inputs = [], + annotation_processor_additional_outputs = [], + strict_deps = "ERROR", + bootclasspath = None, + sourcepath = [], + resources = [], + neverlink = False, + enable_annotation_processing = True, + add_exports = [], + add_opens = []): + return _java_common_internal.compile( + ctx, + output, + java_toolchain, + source_jars = source_jars, + source_files = source_files, + output_source_jar = output_source_jar, + javac_opts = javac_opts, + deps = deps, + runtime_deps = runtime_deps, + exports = exports, + plugins = plugins, + exported_plugins = exported_plugins, + native_libraries = native_libraries, + annotation_processor_additional_inputs = annotation_processor_additional_inputs, + annotation_processor_additional_outputs = annotation_processor_additional_outputs, + strict_deps = strict_deps, + bootclasspath = bootclasspath, + sourcepath = sourcepath, + resources = resources, + neverlink = neverlink, + enable_annotation_processing = enable_annotation_processing, + add_exports = add_exports, + add_opens = add_opens, + ) + +def _run_ijar(actions, jar, java_toolchain, target_label = None): + _java_common_internal.check_java_toolchain_is_declared_on_rule(actions) + return _java_common_internal.run_ijar_private_for_builtins( + actions = actions, + jar = jar, + java_toolchain = java_toolchain, + target_label = target_label, + ) + +def _stamp_jar(actions, jar, java_toolchain, target_label): + """Stamps a jar with a target label for add_dep support. + + The return value is typically passed to `JavaInfo.compile_jar`. Prefer to use `run_ijar` when + possible. + + Args: + actions: (actions) ctx.actions + jar: (File) The jar to run stamp_jar on. + java_toolchain: (JavaToolchainInfo) The toolchain to used to find the stamp_jar tool. + target_label: (Label) A target label to stamp the jar with. Used for `add_dep` support. + Typically, you would pass `ctx.label` to stamp the jar with the current rule's label. + + Returns: + (File) The output artifact + + """ + _java_common_internal.check_java_toolchain_is_declared_on_rule(actions) + output = actions.declare_file(paths.replace_extension(jar.basename, "-stamped.jar"), sibling = jar) + args = actions.args() + args.add(jar) + args.add(output) + args.add("--nostrip_jar") + args.add("--target_label", target_label) + actions.run( + mnemonic = "JavaIjar", + inputs = [jar], + outputs = [output], + executable = java_toolchain.ijar, # ijar doubles as a stamping tool + arguments = [args], + progress_message = "Stamping target label into jar %{input}", + toolchain = semantics.JAVA_TOOLCHAIN_TYPE, + use_default_shell_env = True, + ) + return output + +def _pack_sources( + actions, + java_toolchain, + output_source_jar, + sources = [], + source_jars = []): + """Packs sources and source jars into a single source jar file. + + The return value is typically passed to `JavaInfo.source_jar`. + + Args: + actions: (actions) ctx.actions + java_toolchain: (JavaToolchainInfo) The toolchain used to find the ijar tool. + output_source_jar: (File) The output source jar. + sources: ([File]) A list of Java source files to be packed into the source jar. + source_jars: ([File]) A list of source jars to be packed into the source jar. + + Returns: + (File) The output artifact + """ + _java_common_internal.check_java_toolchain_is_declared_on_rule(actions) + return helper.create_single_jar( + actions, + toolchain = java_toolchain, + output = output_source_jar, + sources = depset(source_jars), + resources = depset(sources), + progress_message = "Building source jar %{output}", + mnemonic = "JavaSourceJar", + ) + +# TODO: b/78512644 - migrate callers to passing explicit javacopts or using custom toolchains, and delete +def _default_javac_opts(java_toolchain): + """Experimental! Get default javacopts from a java toolchain + + Args: + java_toolchain: (JavaToolchainInfo) the toolchain from which to get the javac options. + + Returns: + ([str]) A list of javac options + """ + return java_toolchain._javacopts_list + +# temporary for migration +def _default_javac_opts_depset(java_toolchain): + """Experimental! Get default javacopts from a java toolchain + + Args: + java_toolchain: (JavaToolchainInfo) the toolchain from which to get the javac options. + + Returns: + (depset[str]) A depset of javac options that should be tokenized before passing to javac + """ + return java_toolchain._javacopts + +def _merge(providers): + """Merges the given providers into a single JavaInfo. + + Args: + providers: ([JavaInfo]) The list of providers to merge. + + Returns: + (JavaInfo) The merged JavaInfo + """ + return _java_info_merge(providers) + +def _make_non_strict(java_info): + """Returns a new JavaInfo instance whose direct-jars part is the union of both the direct and indirect jars of the given Java provider. + + Args: + java_info: (JavaInfo) The java info to make non-strict. + + Returns: + (JavaInfo) + """ + return _java_info_make_non_strict(java_info) + +def _get_message_bundle_info(): + return None if semantics.IS_BAZEL else MessageBundleInfo + +def _add_constraints(java_info, constraints = []): + """Returns a copy of the given JavaInfo with the given constraints added. + + Args: + java_info: (JavaInfo) The JavaInfo to enhance + constraints: ([str]) Constraints to add + + Returns: + (JavaInfo) + """ + if semantics.IS_BAZEL: + return java_info + + return _java_info_add_constraints(java_info, constraints = constraints) + +def _get_constraints(java_info): + """Returns a set of constraints added. + + Args: + java_info: (JavaInfo) The JavaInfo to get constraints from. + + Returns: + ([str]) The constraints set on the supplied JavaInfo + """ + return [] if semantics.IS_BAZEL else java_info._constraints + +def _set_annotation_processing( + java_info, + enabled = False, + processor_classnames = [], + processor_classpath = None, + class_jar = None, + source_jar = None): + """Returns a copy of the given JavaInfo with the given annotation_processing info. + + Args: + java_info: (JavaInfo) The JavaInfo to enhance. + enabled: (bool) Whether the rule uses annotation processing. + processor_classnames: ([str]) Class names of annotation processors applied. + processor_classpath: (depset[File]) Class names of annotation processors applied. + class_jar: (File) Optional. Jar that is the result of annotation processing. + source_jar: (File) Optional. Source archive resulting from annotation processing. + + Returns: + (JavaInfo) + """ + if semantics.IS_BAZEL: + return None + + return _java_info_set_annotation_processing( + java_info, + enabled = enabled, + processor_classnames = processor_classnames, + processor_classpath = processor_classpath, + class_jar = class_jar, + source_jar = source_jar, + ) + +def _java_toolchain_label(java_toolchain): + """Returns the toolchain's label. + + Args: + java_toolchain: (JavaToolchainInfo) The toolchain. + Returns: + (Label) + """ + if semantics.IS_BAZEL: + # No implementation in Bazel. This method is not callable in Starlark except through + # (discouraged) use of --experimental_google_legacy_api. + return None + + _java_common_internal.check_provider_instances([java_toolchain], "java_toolchain", JavaToolchainInfo) + return java_toolchain.label + +def _make_java_common(): + methods = { + "provider": JavaInfo, + "compile": _compile, + "run_ijar": _run_ijar, + "stamp_jar": _stamp_jar, + "pack_sources": _pack_sources, + "default_javac_opts": _default_javac_opts, + "default_javac_opts_depset": _default_javac_opts_depset, + "merge": _merge, + "make_non_strict": _make_non_strict, + "JavaPluginInfo": JavaPluginInfo, + "JavaToolchainInfo": JavaToolchainInfo, + "JavaRuntimeInfo": JavaRuntimeInfo, + "BootClassPathInfo": BootClassPathInfo, + "JavaRuntimeClasspathInfo": JavaRuntimeClasspathInfo, + } + if _java_common_internal.google_legacy_api_enabled(): + methods.update( + MessageBundleInfo = _get_message_bundle_info(), # struct field that is None in bazel + add_constraints = _add_constraints, + get_constraints = _get_constraints, + set_annotation_processing = _set_annotation_processing, + java_toolchain_label = _java_toolchain_label, + ) + return struct(**methods) + +java_common = _make_java_common() diff --git a/java/private/java_info.bzl b/java/private/java_info.bzl new file mode 100644 index 00000000..f55020fd --- /dev/null +++ b/java/private/java_info.bzl @@ -0,0 +1,974 @@ +# Copyright 2023 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. + +""" +Definition of JavaInfo and JavaPluginInfo provider. +""" + +load("@rules_cc//cc/common:cc_common.bzl", "cc_common") +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") +load("//java/common:java_semantics.bzl", "semantics") +load(":native.bzl", _native_java_common = "native_java_common") + +visibility("private") + +# TODO(hvd): remove this when: +# - we have a general provider-type checking API +# - no longer need to check for --experimental_google_legacy_api +_java_common_internal = _native_java_common.internal_DO_NOT_USE() + +_JavaOutputInfo = provider( + doc = "The outputs of Java compilation.", + fields = { + "class_jar": "(File) A classes jar file.", + "compile_jar": "(File) An interface jar file.", + "ijar": "Deprecated: Please use compile_jar.", + "compile_jdeps": "(File) Compile time dependencies information (deps.proto file).", + "generated_class_jar": "(File) A jar containing classes generated via annotation processing.", + "generated_source_jar": "(File) The source jar created as a result of annotation processing.", + "native_headers_jar": "(File) A jar of CC header files supporting native method implementation.", + "manifest_proto": "(File) The manifest protobuf file of the manifest generated from JavaBuilder.", + "jdeps": "(File) The jdeps protobuf file of the manifest generated from JavaBuilder.", + "source_jars": "(depset[File]) A depset of sources archive files.", + "source_jar": "Deprecated: Please use source_jars instead.", + }, +) +_ModuleFlagsInfo = provider( + doc = "Provider for the runtime classpath contributions of a Java binary.", + fields = { + "add_exports": "(depset[str]) Add-Exports configuration.", + "add_opens": "(depset[str]) Add-Opens configuration.", + }, +) +_EMPTY_MODULE_FLAGS_INFO = _ModuleFlagsInfo(add_exports = depset(), add_opens = depset()) + +def _create_module_flags_info(*, add_exports, add_opens): + if add_exports or add_opens: + return _ModuleFlagsInfo(add_exports = add_exports, add_opens = add_opens) + return _EMPTY_MODULE_FLAGS_INFO + +_JavaRuleOutputJarsInfo = provider( + doc = "Deprecated: use java_info.java_outputs. Information about outputs of a Java rule.", + fields = { + "jdeps": "Deprecated: Use java_info.java_outputs.", + "native_headers": "Deprecated: Use java_info.java_outputs[i].jdeps.", + "jars": "Deprecated: Use java_info.java_outputs[i].native_headers_jar.", + }, +) +_JavaGenJarsInfo = provider( + doc = "Deprecated: Information about jars that are a result of annotation processing for a Java rule.", + fields = { + "enabled": "Deprecated. Returns true if annotation processing was applied on this target.", + "class_jar": "Deprecated: Please use JavaInfo.java_outputs.generated_class_jar instead.", + "source_jar": "Deprecated: Please use JavaInfo.java_outputs.generated_source_jar instead.", + "transitive_class_jars": "Deprecated. A transitive set of class file jars from annotation " + + "processing of this rule and its dependencies.", + "transitive_source_jars": "Deprecated. A transitive set of source archives from annotation " + + "processing of this rule and its dependencies.", + "processor_classpath": "Deprecated: Please use JavaInfo.plugins instead.", + "processor_classnames": "Deprecated: Please use JavaInfo.plugins instead.", + }, +) + +JavaCompilationInfo = provider( + doc = "Compilation information in Java rules, for perusal of aspects and tools.", + fields = { + "boot_classpath": "Boot classpath for this Java target.", + "javac_options": """Depset of options to the java compiler. To get the + exact list of options passed to javac in the correct order, use the + tokenize_javacopts utility in rules_java""", + "compilation_classpath": "Compilation classpath for this Java target.", + "runtime_classpath": "Run-time classpath for this Java target.", + }, +) + +def merge( + providers, + # private to @_builtins: + merge_java_outputs = True, + merge_source_jars = True): + """Merges the given providers into a single JavaInfo. + + Args: + providers: ([JavaInfo]) The list of providers to merge. + merge_java_outputs: (bool) + merge_source_jars: (bool) + + Returns: + (JavaInfo) The merged JavaInfo + """ + _validate_provider_list(providers, "providers", JavaInfo) + + plugin_info = merge_plugin_info_without_outputs(providers) + + source_jars = [] # [File] + transitive_source_jars = [] # [depset[File]] + java_outputs = [] # [_JavaOutputInfo] + runtime_output_jars = [] # [File] + transitive_runtime_jars = [] # [depset[File]] + transitive_compile_time_jars = [] # [depset[File]] + compile_jars = [] # [depset[File]] + full_compile_jars = [] # [depset[File]] + _transitive_full_compile_time_jars = [] # [depset[File]] + _compile_time_java_dependencies = [] # [depset[File]] + add_exports = [] # [depset[str]] + add_opens = [] # [depset[str]] + _neverlink = False + _constraints = [] # [str] + for p in providers: + if merge_source_jars: + source_jars.extend(p.source_jars) + transitive_source_jars.append(p.transitive_source_jars) + if merge_java_outputs: + java_outputs.extend(p.java_outputs) + runtime_output_jars.extend(p.runtime_output_jars) + transitive_runtime_jars.append(p.transitive_runtime_jars) + transitive_compile_time_jars.append(p.transitive_compile_time_jars) + compile_jars.append(p.compile_jars) + full_compile_jars.append(p.full_compile_jars) + _transitive_full_compile_time_jars.append(p._transitive_full_compile_time_jars) + _compile_time_java_dependencies.append(p._compile_time_java_dependencies) + add_exports.append(p.module_flags_info.add_exports) + add_opens.append(p.module_flags_info.add_opens) + _neverlink = _neverlink or p._neverlink + _constraints.extend(p._constraints) + + transitive_runtime_jars = depset(order = "preorder", transitive = transitive_runtime_jars) + transitive_compile_time_jars = depset(order = "preorder", transitive = transitive_compile_time_jars) + + # java_outputs is a list so we uniquify to avoid https://github.com/bazelbuild/bazel/issues/17170 + java_outputs = depset(java_outputs).to_list() + result = { + "transitive_runtime_jars": transitive_runtime_jars, + "transitive_compile_time_jars": transitive_compile_time_jars, + "compile_jars": depset(order = "preorder", transitive = compile_jars), + "full_compile_jars": depset(order = "preorder", transitive = full_compile_jars), + "_transitive_full_compile_time_jars": depset(order = "preorder", transitive = _transitive_full_compile_time_jars), + "_compile_time_java_dependencies": depset(order = "preorder", transitive = _compile_time_java_dependencies), + # runtime_output_jars is a list so we uniquify to avoid https://github.com/bazelbuild/bazel/issues/17170 + "runtime_output_jars": depset(runtime_output_jars).to_list(), + # source_jars is a list so we uniquify to avoid https://github.com/bazelbuild/bazel/issues/17170 + "source_jars": depset(source_jars).to_list(), + "transitive_source_jars": depset(transitive = transitive_source_jars), + "java_outputs": java_outputs, + "outputs": _JavaRuleOutputJarsInfo(jars = java_outputs, jdeps = None, native_headers = None), + "module_flags_info": _create_module_flags_info( + add_exports = depset(transitive = add_exports), + add_opens = depset(transitive = add_opens), + ), + "plugins": plugin_info.plugins, + "api_generating_plugins": plugin_info.api_generating_plugins, + "_neverlink": bool(_neverlink), + "_constraints": depset(_constraints).to_list(), + "annotation_processing": None, + "compilation_info": None, + } + + if _java_common_internal.google_legacy_api_enabled(): + cc_info = semantics.minimize_cc_info(cc_common.merge_cc_infos(cc_infos = [p.cc_link_params_info for p in providers])) + result.update( + cc_link_params_info = cc_info, + transitive_native_libraries = cc_info.transitive_native_libraries(), + ) + else: + result.update( + transitive_native_libraries = depset( + order = "topological", + transitive = [p.transitive_native_libraries for p in providers], + ), + ) + return _java_common_internal.wrap_java_info(_new_javainfo(**result)) + +def to_java_binary_info(java_info, compilation_info): + """Get a copy of the given JavaInfo with minimal info returned by a java_binary + + Args: + java_info: (JavaInfo) A JavaInfo provider instance + compilation_info: (JavaCompilationInfo) + Returns: + (JavaInfo) A JavaInfo instance representing a java_binary target + """ + result = { + "transitive_runtime_jars": depset(), + "transitive_compile_time_jars": depset(), + "compile_jars": depset(), + "full_compile_jars": depset(), + "_transitive_full_compile_time_jars": depset(), + "_compile_time_java_dependencies": depset(), + "runtime_output_jars": [], + "plugins": _EMPTY_PLUGIN_DATA, + "api_generating_plugins": _EMPTY_PLUGIN_DATA, + "module_flags_info": _EMPTY_MODULE_FLAGS_INFO, + "_neverlink": False, + "_constraints": [], + "annotation_processing": java_info.annotation_processing, + "transitive_native_libraries": java_info.transitive_native_libraries, + "source_jars": java_info.source_jars, + "transitive_source_jars": java_info.transitive_source_jars, + } + if hasattr(java_info, "cc_link_params_info"): + result.update(cc_link_params_info = java_info.cc_link_params_info) + + result["compilation_info"] = compilation_info + + java_outputs = [ + _JavaOutputInfo( + compile_jar = None, + ijar = None, # deprecated + compile_jdeps = None, + class_jar = output.class_jar, + generated_class_jar = output.generated_class_jar, + generated_source_jar = output.generated_source_jar, + native_headers_jar = output.native_headers_jar, + manifest_proto = output.manifest_proto, + jdeps = output.jdeps, + source_jars = output.source_jars, + source_jar = output.source_jar, # deprecated + ) + for output in java_info.java_outputs + ] + all_jdeps = [output.jdeps for output in java_info.java_outputs if output.jdeps] + all_native_headers = [output.native_headers_jar for output in java_info.java_outputs if output.native_headers_jar] + result.update( + java_outputs = java_outputs, + outputs = _JavaRuleOutputJarsInfo( + jars = java_outputs, + jdeps = all_jdeps[0] if len(all_jdeps) == 1 else None, + native_headers = all_native_headers[0] if len(all_native_headers) == 1 else None, + ), + ) + + # so that translation into native JavaInfo does not add JavaCompilationArgsProvider + result.update(_is_binary = True) + return _new_javainfo(**result) + +def _to_mutable_dict(java_info): + return { + key: getattr(java_info, key) + for key in dir(java_info) + if key not in ["to_json", "to_proto"] + } + +def add_constraints(java_info, constraints = []): + """Returns a copy of the given JavaInfo with the given constraints added. + + Args: + java_info: (JavaInfo) The JavaInfo to enhance + constraints: ([str]) Constraints to add + + Returns: + (JavaInfo) + """ + result = _to_mutable_dict(java_info) + old_constraints = java_info._constraints if java_info._constraints else [] + result.update( + _constraints = depset(constraints + old_constraints).to_list(), + ) + return _new_javainfo(**result) + +def make_non_strict(java_info): + """Returns a new JavaInfo instance whose direct-jars part is the union of both the direct and indirect jars of the given Java provider. + + Args: + java_info: (JavaInfo) The java info to make non-strict. + + Returns: + (JavaInfo) + """ + result = _to_mutable_dict(java_info) + result.update( + compile_jars = java_info.transitive_compile_time_jars, + full_compile_jars = java_info._transitive_full_compile_time_jars, + ) + + # Omit jdeps, which aren't available transitively and aren't useful for reduced classpath + # pruning for non-strict targets: the direct classpath and transitive classpath are the same, + # so there's nothing to prune, and reading jdeps at compile-time isn't free. + result.update( + _compile_time_java_dependencies = depset(), + ) + return _new_javainfo(**result) + +def add_module_flags(java_info, add_exports = [], add_opens = []): + """Returns a new JavaInfo instance with the additional add_exports/add_opens + + Args: + java_info: (JavaInfo) The java info to enhance. + add_exports: ([str]) The /s given access to. + add_opens: ([str]) The /s given reflective access to. + Returns: + (JavaInfo) + """ + if not add_exports and not add_opens: + return java_info + + result = _to_mutable_dict(java_info) + result.update( + module_flags_info = _create_module_flags_info( + add_exports = depset(add_exports, transitive = [java_info.module_flags_info.add_exports]), + add_opens = depset(add_opens, transitive = [java_info.module_flags_info.add_opens]), + ), + ) + return _new_javainfo(**result) + +def set_annotation_processing( + java_info, + enabled = False, + processor_classnames = [], + processor_classpath = None, + class_jar = None, + source_jar = None): + """Returns a copy of the given JavaInfo with the given annotation_processing info. + + Args: + java_info: (JavaInfo) The JavaInfo to enhance. + enabled: (bool) Whether the rule uses annotation processing. + processor_classnames: ([str]) Class names of annotation processors applied. + processor_classpath: (depset[File]) Class names of annotation processors applied. + class_jar: (File) Optional. Jar that is the result of annotation processing. + source_jar: (File) Optional. Source archive resulting from annotation processing. + + Returns: + (JavaInfo) + """ + gen_jars_info = java_info.annotation_processing + if gen_jars_info: + # Existing Jars would be a problem b/c we can't remove them from transitiveXxx sets + if gen_jars_info.class_jar and gen_jars_info.class_jar != class_jar: + fail("Existing gen_class_jar:", gen_jars_info.class_jar) + if gen_jars_info.source_jar and gen_jars_info.source_jar != source_jar: + fail("Existing gen_source_jar:", gen_jars_info.class_jar) + transitive_class_jars = depset([class_jar] if class_jar else [], transitive = [gen_jars_info.transitive_class_jars]) + transitive_source_jars = depset([source_jar] if source_jar else [], transitive = [gen_jars_info.transitive_source_jars]) + else: + transitive_class_jars = depset([class_jar] if class_jar else []) + transitive_source_jars = depset([source_jar] if source_jar else []) + + result = _to_mutable_dict(java_info) + result.update( + annotation_processing = _JavaGenJarsInfo( + enabled = enabled, + class_jar = class_jar, + source_jar = source_jar, + processor_classnames = processor_classnames, + processor_classpath = processor_classpath if processor_classpath else depset(), + transitive_class_jars = transitive_class_jars, + transitive_source_jars = transitive_source_jars, + ), + ) + return _new_javainfo(**result) + +def java_info_for_compilation( + output_jar, + compile_jar, + source_jar, + generated_class_jar, + generated_source_jar, + plugin_info, + deps, + runtime_deps, + exports, + exported_plugins, + compile_jdeps, + jdeps, + native_headers_jar, + manifest_proto, + native_libraries, + neverlink, + add_exports, + add_opens, + direct_runtime_jars, + compilation_info): + """Creates a JavaInfo instance represiting the result of java compilation. + + Args: + output_jar: (File) The jar that was created as a result of a compilation. + compile_jar: (File) A jar that is the compile-time dependency in lieu of `output_jar`. + source_jar: (File) The source jar that was used to create the output jar. + generated_class_jar: (File) A jar file containing class files compiled from sources + generated during annotation processing. + generated_source_jar: (File) The source jar that was created as a result of annotation + processing. + plugin_info: (JavaPluginInfo) Information about annotation processing. + deps: ([JavaInfo]) Compile time dependencies that were used to create the output jar. + runtime_deps: ([JavaInfo]) Runtime dependencies that are needed for this library. + exports: ([JavaInfo]) Libraries to make available for users of this library. + exported_plugins: ([JavaPluginInfo]) A list of exported plugins. + compile_jdeps: (File) jdeps information about compile time dependencies to be consumed by + JavaCompileAction. This should be a binary proto encoded using the deps.proto protobuf + included with Bazel. If available this file is typically produced by a header compiler. + jdeps: (File) jdeps information for the rule output (if available). This should be a binary + proto encoded using the deps.proto protobuf included with Bazel. If available this file + is typically produced by a compiler. IDEs and other tools can use this information for + more efficient processing. + native_headers_jar: (File) A jar containing CC header files supporting native method + implementation (typically output of javac -h). + manifest_proto: (File) Manifest information for the rule output (if available). This should + be a binary proto encoded using the manifest.proto protobuf included with Bazel. IDEs + and other tools can use this information for more efficient processing. + native_libraries: ([CcInfo]) Native library dependencies that are needed for this library. + neverlink: (bool) If true, only use this library for compilation and not at runtime. + add_exports: ([str]) The /s this library was given access to. + add_opens: ([str]) The /s this library was given reflective access to. + direct_runtime_jars: ([File]) The class jars needed directly by this library at runtime. + This is usually just the output_jar or empty if there were no sources/resources. + compilation_info: (struct) Information for IDE/tools + + Returns: + (JavaInfo) the JavaInfo instance + """ + result, concatenated_deps = _javainfo_init_base( + output_jar, + compile_jar, + source_jar, + deps, + runtime_deps, + exports, + exported_plugins, + jdeps, + compile_jdeps, + native_headers_jar, + manifest_proto, + generated_class_jar, + generated_source_jar, + native_libraries, + neverlink, + ) + + # this differs ever so slightly from the usual JavaInfo in that direct_runtime_jars + # does not contain the output_jar is there were no sources/resources + transitive_runtime_jars = depset() if neverlink else depset( + order = "preorder", + direct = direct_runtime_jars, + transitive = [dep.transitive_runtime_jars for dep in concatenated_deps.exports_deps + runtime_deps], + ) + result.update( + runtime_output_jars = direct_runtime_jars, + transitive_runtime_jars = transitive_runtime_jars, + transitive_source_jars = depset( + direct = [source_jar], + # only differs from the usual java_info.transitive_source_jars in the order of deps + transitive = [dep.transitive_source_jars for dep in concatenated_deps.runtimedeps_exports_deps], + ), + # the JavaInfo constructor does not add flags from runtime_deps + module_flags_info = _create_module_flags_info( + add_exports = depset(add_exports, transitive = [ + dep.module_flags_info.add_exports + for dep in concatenated_deps.runtimedeps_exports_deps + ]), + add_opens = depset(add_opens, transitive = [ + dep.module_flags_info.add_opens + for dep in concatenated_deps.runtimedeps_exports_deps + ]), + ), + ) + if compilation_info: + result.update( + compilation_info = JavaCompilationInfo( + javac_options = compilation_info.javac_options, + boot_classpath = compilation_info.boot_classpath, + compilation_classpath = compilation_info.compilation_classpath, + runtime_classpath = compilation_info.runtime_classpath, + ), + annotation_processing = _JavaGenJarsInfo( + enabled = compilation_info.uses_annotation_processing, + class_jar = result["annotation_processing"].class_jar, + source_jar = result["annotation_processing"].source_jar, + processor_classnames = plugin_info.plugins.processor_classes.to_list(), + processor_classpath = plugin_info.plugins.processor_jars, + transitive_class_jars = result["annotation_processing"].transitive_class_jars, + transitive_source_jars = result["annotation_processing"].transitive_source_jars, + ), + ) + else: + result.update( + compilation_info = None, + annotation_processing = None, + ) + return _java_common_internal.wrap_java_info(_new_javainfo(**result)) + +def _validate_provider_list(provider_list, what, expected_provider_type): + _java_common_internal.check_provider_instances(provider_list, what, expected_provider_type) + +def _compute_concatenated_deps(deps, runtime_deps, exports): + deps_exports = [] + deps_exports.extend(deps) + deps_exports.extend(exports) + + exports_deps = [] + exports_deps.extend(exports) + exports_deps.extend(deps) + + runtimedeps_exports_deps = [] + runtimedeps_exports_deps.extend(runtime_deps) + runtimedeps_exports_deps.extend(exports_deps) + + return struct( + deps_exports = deps_exports, + exports_deps = exports_deps, + runtimedeps_exports_deps = runtimedeps_exports_deps, + ) + +def _javainfo_init_base( + output_jar, + compile_jar, + source_jar, + deps, + runtime_deps, + exports, + exported_plugins, + jdeps, + compile_jdeps, + native_headers_jar, + manifest_proto, + generated_class_jar, + generated_source_jar, + native_libraries, + neverlink): + _validate_provider_list(deps, "deps", JavaInfo) + _validate_provider_list(runtime_deps, "runtime_deps", JavaInfo) + _validate_provider_list(exports, "exports", JavaInfo) + _validate_provider_list(native_libraries, "native_libraries", CcInfo) + + concatenated_deps = _compute_concatenated_deps(deps, runtime_deps, exports) + + source_jars = [source_jar] if source_jar else [] + plugin_info = merge_plugin_info_without_outputs(exported_plugins + exports) + transitive_compile_time_jars = depset( + order = "preorder", + direct = [compile_jar] if compile_jar else [], + transitive = [dep.transitive_compile_time_jars for dep in concatenated_deps.exports_deps], + ) + java_outputs = [_JavaOutputInfo( + class_jar = output_jar, + compile_jar = compile_jar, + ijar = compile_jar, # deprecated + compile_jdeps = compile_jdeps, + generated_class_jar = generated_class_jar, + generated_source_jar = generated_source_jar, + native_headers_jar = native_headers_jar, + manifest_proto = manifest_proto, + jdeps = jdeps, + source_jars = depset(source_jars), + source_jar = source_jar, # deprecated + )] + result = { + "transitive_compile_time_jars": transitive_compile_time_jars, + "compile_jars": depset( + order = "preorder", + direct = [compile_jar] if compile_jar else [], + transitive = [dep.compile_jars for dep in exports], + ), + "full_compile_jars": depset( + order = "preorder", + direct = [output_jar], + transitive = [ + dep.full_compile_jars + for dep in exports + ], + ), + "source_jars": source_jars, + "runtime_output_jars": [output_jar], + "plugins": plugin_info.plugins, + "api_generating_plugins": plugin_info.api_generating_plugins, + "java_outputs": java_outputs, + # deprecated + "outputs": _JavaRuleOutputJarsInfo( + jars = java_outputs, + jdeps = jdeps, + native_headers = native_headers_jar, + ), + "annotation_processing": _JavaGenJarsInfo( + enabled = False, + class_jar = generated_class_jar, + source_jar = generated_source_jar, + transitive_class_jars = depset( + direct = [generated_class_jar] if generated_class_jar else [], + transitive = [ + dep.annotation_processing.transitive_class_jars + for dep in concatenated_deps.deps_exports + if dep.annotation_processing + ], + ), + transitive_source_jars = depset( + direct = [generated_source_jar] if generated_source_jar else [], + transitive = [ + dep.annotation_processing.transitive_source_jars + for dep in concatenated_deps.deps_exports + if dep.annotation_processing + ], + ), + processor_classnames = [], + processor_classpath = depset(), + ), + "_transitive_full_compile_time_jars": depset( + order = "preorder", + direct = [output_jar], + transitive = [dep._transitive_full_compile_time_jars for dep in concatenated_deps.exports_deps], + ), + "_compile_time_java_dependencies": depset( + order = "preorder", + transitive = [dep._compile_time_java_dependencies for dep in exports] + + ([depset([compile_jdeps])] if compile_jdeps else []), + ), + "_neverlink": bool(neverlink), + "compilation_info": None, + "_constraints": [], + } + + if _java_common_internal.google_legacy_api_enabled(): + transitive_cc_infos = [dep.cc_link_params_info for dep in concatenated_deps.runtimedeps_exports_deps] + transitive_cc_infos.extend(native_libraries) + cc_info = semantics.minimize_cc_info(cc_common.merge_cc_infos(cc_infos = transitive_cc_infos)) + result.update( + cc_link_params_info = cc_info, + transitive_native_libraries = cc_info.transitive_native_libraries(), + ) + else: + result.update( + transitive_native_libraries = depset( + order = "topological", + transitive = [dep.transitive_native_libraries for dep in concatenated_deps.runtimedeps_exports_deps] + + ([cc_common.merge_cc_infos(cc_infos = native_libraries).transitive_native_libraries()] if native_libraries else []), + ), + ) + return result, concatenated_deps + +def _javainfo_init( + output_jar, + compile_jar, + source_jar = None, + compile_jdeps = None, + generated_class_jar = None, + generated_source_jar = None, + native_headers_jar = None, + manifest_proto = None, + neverlink = False, + deps = [], + runtime_deps = [], + exports = [], + exported_plugins = [], + jdeps = None, + native_libraries = [], + add_exports = [], + add_opens = []): + """The JavaInfo constructor + + Args: + output_jar: (File) The jar that was created as a result of a compilation. + compile_jar: (File) A jar that is the compile-time dependency in lieu of `output_jar`. + source_jar: (File) The source jar that was used to create the output jar. Optional. + compile_jdeps: (File) jdeps information about compile time dependencies to be consumed by + JavaCompileAction. This should be a binary proto encoded using the deps.proto protobuf + included with Bazel. If available this file is typically produced by a header compiler. + Optional. + generated_class_jar: (File) A jar file containing class files compiled from sources + generated during annotation processing. Optional. + generated_source_jar: (File) The source jar that was created as a result of annotation + processing. Optional. + native_headers_jar: (File) A jar containing CC header files supporting native method + implementation (typically output of javac -h). Optional. + manifest_proto: (File) Manifest information for the rule output (if available). This should + be a binary proto encoded using the manifest.proto protobuf included with Bazel. IDEs + and other tools can use this information for more efficient processing. Optional. + neverlink: (bool) If true, only use this library for compilation and not at runtime. + deps: ([JavaInfo]) Compile time dependencies that were used to create the output jar. + runtime_deps: ([JavaInfo]) Runtime dependencies that are needed for this library. + exports: ([JavaInfo]) Libraries to make available for users of this library. + exported_plugins: ([JavaPluginInfo]) Optional. A list of exported plugins. + jdeps: (File) jdeps information for the rule output (if available). This should be a binary + proto encoded using the deps.proto protobuf included with Bazel. If available this file + is typically produced by a compiler. IDEs and other tools can use this information for + more efficient processing. Optional. + native_libraries: ([CcInfo]) Native library dependencies that are needed for this library. + add_exports: ([str]) The /s this library was given access to. + add_opens: ([str]) The /s this library was given reflective access to. + + Returns: + (dict) arguments to the JavaInfo provider constructor + """ + if add_exports or add_opens: + semantics.check_java_info_opens_exports() + + result, concatenated_deps = _javainfo_init_base( + output_jar, + compile_jar, + source_jar, + deps, + runtime_deps, + exports, + exported_plugins, + jdeps, + compile_jdeps, + native_headers_jar, + manifest_proto, + generated_class_jar, + generated_source_jar, + native_libraries, + neverlink, + ) + + if neverlink: + transitive_runtime_jars = depset() + else: + transitive_runtime_jars = depset( + order = "preorder", + direct = [output_jar], + transitive = [dep.transitive_runtime_jars for dep in concatenated_deps.exports_deps + runtime_deps], + ) + + # For backward compatibility, we use deps_exports for add_exports/add_opens + # for the JavaInfo constructor rather than runtimedeps_exports_deps (used + # by java_info_for_compilation). However, runtimedeps_exports_deps makes + # more sense, since add_exports/add_opens from runtime_deps are needed at + # runtime anyway. + # + # TODO: When this flag is removed, move this logic into _javainfo_init_base + # and remove the special case from java_info_for_compilation. + module_flags_deps = concatenated_deps.deps_exports + if _java_common_internal._incompatible_java_info_merge_runtime_module_flags(): + module_flags_deps = concatenated_deps.runtimedeps_exports_deps + + result.update( + transitive_runtime_jars = transitive_runtime_jars, + transitive_source_jars = depset( + direct = [source_jar] if source_jar else [], + # TODO(hvd): native also adds source jars from deps, but this should be unnecessary + transitive = [ + dep.transitive_source_jars + for dep in deps + runtime_deps + exports + ], + ), + module_flags_info = _create_module_flags_info( + add_exports = depset(add_exports, transitive = [ + dep.module_flags_info.add_exports + for dep in module_flags_deps + ]), + add_opens = depset(add_opens, transitive = [ + dep.module_flags_info.add_opens + for dep in module_flags_deps + ]), + ), + ) + return result + +JavaInfo, _new_javainfo = provider( + doc = "Info object encapsulating all information by java rules.", + fields = { + "transitive_runtime_jars": """(depset[File]) A transitive set of jars required on the + runtime classpath. +

Note: for binary targets (such as java_binary and java_test), this is empty, since such + targets are not intended to be dependencies of other Java targets. + """, + "transitive_compile_time_jars": """(depset[File]) The transitive set of jars required to + build the target. +

Note: for binary targets (such as java_binary and java_test), this is empty, since such + targets are not intended to be dependencies of other Java targets. + """, + "compile_jars": """(depset[File]) The jars required directly at compile time. They can be interface jars + (ijar or hjar), regular jars or both, depending on whether rule + implementations chose to create interface jars or not.""", + "full_compile_jars": """(depset[File]) The regular, full compile time Jars required by this target directly. + They can be: + - the corresponding regular Jars of the interface Jars returned by JavaInfo.compile_jars + - the regular (full) Jars returned by JavaInfo.compile_jars + + Note: JavaInfo.compile_jars can return a mix of interface Jars and + regular Jars.

Only use this method if interface Jars don't work with + your rule set(s) (e.g. some Scala targets) If you're working with + Java-only targets it's preferable to use interface Jars via + JavaInfo.compile_jars""", + "source_jars": """([File]) A list of Jars with all the source files (including those generated by + annotations) of the target itself, i.e. NOT including the sources of the + transitive dependencies.""", + "outputs": "Deprecated: use java_outputs.", + "annotation_processing": "Deprecated: Please use plugins instead.", + "runtime_output_jars": "([File]) A list of runtime Jars created by this Java/Java-like target.", + "transitive_source_jars": "(depset[File]) The Jars of all source files in the transitive closure.", + "transitive_native_libraries": """(depset[LibraryToLink]) The transitive set of CC native + libraries required by the target.""", + "cc_link_params_info": "Deprecated. Do not use. C++ libraries to be linked into Java targets.", + "module_flags_info": "(_ModuleFlagsInfo) The Java module flag configuration.", + "plugins": """(_JavaPluginDataInfo) Data about all plugins that a consuming target should + apply. + This is typically either a `java_plugin` itself or a `java_library` exporting + one or more plugins. + A `java_library` runs annotation processing with all plugins from this field + appearing in deps and `plugins` attributes.""", + "api_generating_plugins": """"(_JavaPluginDataInfo) Data about API generating plugins + defined or exported by this target. + Those annotation processors are applied to a Java target before + producing its header jars (which contain method signatures). When + no API plugins are present, header jars are generated from the + sources, reducing critical path. + The `api_generating_plugins` is a subset of `plugins`.""", + "java_outputs": "(_JavaOutputInfo) Information about outputs of this Java/Java-like target.", + "compilation_info": """(java_compilation_info) Compilation information for this + Java/Java-like target.""", + "_transitive_full_compile_time_jars": "internal API, do not use", + "_compile_time_java_dependencies": "internal API, do not use", + "_neverlink": "internal API, do not use", + "_constraints": "internal API, do not use", + "_is_binary": "internal API, do not use", + }, + init = _javainfo_init, +) + +JavaPluginDataInfo = provider( + doc = "Provider encapsulating information about a Java compatible plugin.", + fields = { + "processor_classes": "depset(str) The fully qualified classnames of entry points for the compiler", + "processor_jars": "depset(file) Deps containing an annotation processor", + "processor_data": "depset(file) Files needed during execution", + }, +) + +_EMPTY_PLUGIN_DATA = JavaPluginDataInfo( + processor_classes = depset(), + processor_jars = depset(), + processor_data = depset(), +) + +def _create_plugin_data_info(*, processor_classes, processor_jars, processor_data): + if processor_classes or processor_jars or processor_data: + return JavaPluginDataInfo( + processor_classes = processor_classes, + processor_jars = processor_jars, + processor_data = processor_data, + ) + else: + return _EMPTY_PLUGIN_DATA + +def disable_plugin_info_annotation_processing(plugin_info): + """Returns a copy of the provided JavaPluginInfo without annotation processing info + + Args: + plugin_info: (JavaPluginInfo) the instance to transform + + Returns: + (JavaPluginInfo) a new, transformed instance. + """ + return _new_javaplugininfo( + plugins = _create_plugin_data_info( + processor_classes = depset(order = "preorder"), + # Preserve the processor path, since it may contain Error Prone plugins + # which will be service-loaded by JavaBuilder. + processor_jars = plugin_info.plugins.processor_jars, + # Preserve data, which may be used by Error Prone plugins. + processor_data = plugin_info.plugins.processor_data, + ), + api_generating_plugins = _EMPTY_PLUGIN_DATA, + java_outputs = plugin_info.java_outputs, + ) + +def merge_plugin_info_without_outputs(infos): + """ Merge plugin information from a list of JavaPluginInfo or JavaInfo + + Args: + infos: ([JavaPluginInfo|JavaInfo]) list of providers to merge + + Returns: + (JavaPluginInfo) + """ + plugins = [] + api_generating_plugins = [] + for info in infos: + if _has_plugin_data(info.plugins): + plugins.append(info.plugins) + if _has_plugin_data(info.api_generating_plugins): + api_generating_plugins.append(info.api_generating_plugins) + return _new_javaplugininfo( + plugins = _merge_plugin_data(plugins), + api_generating_plugins = _merge_plugin_data(api_generating_plugins), + java_outputs = [], + ) + +def _has_plugin_data(plugin_data): + return plugin_data and ( + plugin_data.processor_classes or + plugin_data.processor_jars or + plugin_data.processor_data + ) + +def _merge_plugin_data(datas): + return _create_plugin_data_info( + processor_classes = depset(transitive = [p.processor_classes for p in datas]), + processor_jars = depset(transitive = [p.processor_jars for p in datas]), + processor_data = depset(transitive = [p.processor_data for p in datas]), + ) + +def _javaplugininfo_init( + runtime_deps, + processor_class, + data = [], + generates_api = False): + """ Constructs JavaPluginInfo + + Args: + runtime_deps: ([JavaInfo]) list of deps containing an annotation + processor. + processor_class: (String) The fully qualified class name that the Java + compiler uses as an entry point to the annotation processor. + data: (depset[File]) The files needed by this annotation + processor during execution. + generates_api: (boolean) Set to true when this annotation processor + generates API code. Such an annotation processor is applied to a + Java target before producing its header jars (which contains method + signatures). When no API plugins are present, header jars are + generated from the sources, reducing the critical path. + WARNING: This parameter affects build performance, use it only if + necessary. + + Returns: + (JavaPluginInfo) + """ + + java_infos = merge(runtime_deps) + processor_data = data if type(data) == "depset" else depset(data) + plugins = _create_plugin_data_info( + processor_classes = depset([processor_class]) if processor_class else depset(), + processor_jars = java_infos.transitive_runtime_jars, + processor_data = processor_data, + ) + return { + "plugins": plugins, + "api_generating_plugins": plugins if generates_api else _EMPTY_PLUGIN_DATA, + "java_outputs": java_infos.java_outputs, + } + +JavaPluginInfo, _new_javaplugininfo = provider( + doc = "Provider encapsulating information about Java plugins.", + fields = { + "plugins": """ + Returns data about all plugins that a consuming target should apply. + This is typically either a java_plugin itself or a + java_library exporting one or more plugins. + A java_library runs annotation processing with all + plugins from this field appearing in deps and + plugins attributes.""", + "api_generating_plugins": """ + Returns data about API generating plugins defined or exported by + this target. + Those annotation processors are applied to a Java target before + producing its header jars (which contain method signatures). When + no API plugins are present, header jars are generated from the + sources, reducing critical path. + The api_generating_plugins is a subset of + plugins.""", + "java_outputs": """ + Returns information about outputs of this Java/Java-like target. + """, + }, + init = _javaplugininfo_init, +) diff --git a/java/private/message_bundle_info.bzl b/java/private/message_bundle_info.bzl new file mode 100644 index 00000000..df77fce7 --- /dev/null +++ b/java/private/message_bundle_info.bzl @@ -0,0 +1,26 @@ +# Copyright 2023 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. + +""" +Definition of MessageBundleInfo provider. +""" + +visibility("private") + +MessageBundleInfo = provider( + doc = "Marks configured targets that are able to supply message bundles to their dependents.", + fields = { + "messages": "Sequence of message bundles", + }, +) diff --git a/java/toolchains/BUILD b/java/toolchains/BUILD index 894cf444..6b0fa913 100644 --- a/java/toolchains/BUILD +++ b/java/toolchains/BUILD @@ -14,7 +14,7 @@ bzl_library( name = "toolchain_rules", srcs = glob(["*.bzl"]), visibility = ["//visibility:public"], - deps = ["//java/private"], + deps = ["//java/private:native_bzl"], ) filegroup( From 2cc0a475f0f7deedad21be869bb3a69fba0afa5a Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 23 Oct 2024 01:08:22 -0700 Subject: [PATCH 062/465] Update rule documentation to use booleans for boolean values. RELNOTES: None. PiperOrigin-RevId: 688859329 Change-Id: If9869a85a183a6a46c6f6f6454d60f8c7f26e205 --- java/common/rules/java_binary.bzl | 2 +- java/common/rules/java_library.bzl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/java/common/rules/java_binary.bzl b/java/common/rules/java_binary.bzl index 5b8b1072..8e0ce02f 100644 --- a/java/common/rules/java_binary.bzl +++ b/java/common/rules/java_binary.bzl @@ -170,7 +170,7 @@ linked into a binary named {name}_nativedeps, where {name}name attribute of this java_binary rule. In this case, the linker will remove any code it thinks is unused from the resulting binary, which means any C++ code accessed only via JNI may not be linked in unless -that cc_library target specifies alwayslink = 1. +that cc_library target specifies alwayslink = True.

When using any launcher other than the default JDK launcher, the format diff --git a/java/common/rules/java_library.bzl b/java/common/rules/java_library.bzl index 9c04fe7c..cc6b749d 100644 --- a/java/common/rules/java_library.bzl +++ b/java/common/rules/java_library.bzl @@ -214,7 +214,7 @@ Useful if the library will be provided by the runtime environment during executi of such libraries are the IDE APIs for IDE plug-ins or tools.jar for anything running on a standard JDK.

- Note that neverlink = 1 does not prevent the compiler from inlining material + Note that neverlink = True does not prevent the compiler from inlining material from this library into compilation targets that depend on it, as permitted by the Java Language Specification (e.g., static final constants of String or of primitive types). The preferred use case is therefore when the runtime library is From ec8a985ae28e7e52a67583d404a6fe80f6b2a23e Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 25 Oct 2024 05:19:42 -0700 Subject: [PATCH 063/465] Release `rules_java` `v8.2.0` PiperOrigin-RevId: 689750164 Change-Id: Ie3e81e352a1bbe43a5689da593a43c4a1b3bfbf0 --- .bazelci/presubmit.yml | 12 ++++-------- MODULE.bazel | 2 +- java/docs/rules.md | 8 ++++---- test/BUILD.bazel | 2 +- 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 15c774d5..a4854462 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -5,6 +5,9 @@ build_targets: &build_targets # TODO: Look into broken targets in //toolchains - "-//toolchains/..." - "-//test/repo/..." + # TODO: re-enable docs after protobuf is fixed + - "-//java/docs/..." + - "-//test:docs_up_to_date_test" build_targets_bzlmod: &build_targets_bzlmod - "//..." @@ -53,14 +56,7 @@ tasks: name: "Bazel@HEAD" bazel: last_green platform: ubuntu2004 - build_targets: - # TODO: use *build_targets after protobuf is fixed - - "//..." - - "@remote_java_tools//java_tools/..." - - "-//toolchains/..." - - "-//test/repo/..." - - "-//java/docs/..." - - "-//test:docs_up_to_date_test" + build_targets: *build_targets ubuntu2004_integration_head: name: "Bazel@HEAD Integration" bazel: last_green diff --git a/MODULE.bazel b/MODULE.bazel index ef6c420c..91262abf 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.1.0", + version = "8.2.0", bazel_compatibility = [">=7.3.2"], compatibility_level = 1, ) diff --git a/java/docs/rules.md b/java/docs/rules.md index e64e05ca..b6dd015c 100644 --- a/java/docs/rules.md +++ b/java/docs/rules.md @@ -136,7 +136,7 @@ java_binary( | env | - | Dictionary: String -> String | optional | `{}` | | javacopts | Extra compiler options for this binary. Subject to "Make variable" substitution and Bourne shell tokenization.

These compiler options are passed to javac after the global compiler options.

| List of strings | optional | `[]` | | jvm_flags | A list of flags to embed in the wrapper script generated for running this binary. Subject to $(location) and "Make variable" substitution, and Bourne shell tokenization.

The wrapper script for a Java binary includes a CLASSPATH definition (to find all the dependent jars) and invokes the right Java interpreter. The command line generated by the wrapper script includes the name of the main class followed by a "$@" so you can pass along other arguments after the classname. However, arguments intended for parsing by the JVM must be specified before the classname on the command line. The contents of jvm_flags are added to the wrapper script before the classname is listed.



Note that this attribute has no effect on *_deploy.jar outputs.

| List of strings | optional | `[]` | -| launcher | Specify a binary that will be used to run your Java program instead of the normal bin/java program included with the JDK. The target must be a cc_binary. Any cc_binary that implements the Java Invocation API can be specified as a value for this attribute.

By default, Bazel will use the normal JDK launcher (bin/java or java.exe).



The related --java_launcher Bazel flag affects only those java_binary and java_test targets that have not specified a launcher attribute.



Note that your native (C++, SWIG, JNI) dependencies will be built differently depending on whether you are using the JDK launcher or another launcher:



  • If you are using the normal JDK launcher (the default), native dependencies are built as a shared library named {name}_nativedeps.so, where {name} is the name attribute of this java_binary rule. Unused code is not removed by the linker in this configuration.


  • If you are using any other launcher, native (C++) dependencies are statically linked into a binary named {name}_nativedeps, where {name} is the name attribute of this java_binary rule. In this case, the linker will remove any code it thinks is unused from the resulting binary, which means any C++ code accessed only via JNI may not be linked in unless that cc_library target specifies alwayslink = 1.


When using any launcher other than the default JDK launcher, the format of the *_deploy.jar output changes. See the main java_binary docs for details.

| Label | optional | `None` | +| launcher | Specify a binary that will be used to run your Java program instead of the normal bin/java program included with the JDK. The target must be a cc_binary. Any cc_binary that implements the Java Invocation API can be specified as a value for this attribute.

By default, Bazel will use the normal JDK launcher (bin/java or java.exe).



The related --java_launcher Bazel flag affects only those java_binary and java_test targets that have not specified a launcher attribute.



Note that your native (C++, SWIG, JNI) dependencies will be built differently depending on whether you are using the JDK launcher or another launcher:



  • If you are using the normal JDK launcher (the default), native dependencies are built as a shared library named {name}_nativedeps.so, where {name} is the name attribute of this java_binary rule. Unused code is not removed by the linker in this configuration.


  • If you are using any other launcher, native (C++) dependencies are statically linked into a binary named {name}_nativedeps, where {name} is the name attribute of this java_binary rule. In this case, the linker will remove any code it thinks is unused from the resulting binary, which means any C++ code accessed only via JNI may not be linked in unless that cc_library target specifies alwayslink = True.


When using any launcher other than the default JDK launcher, the format of the *_deploy.jar output changes. See the main java_binary docs for details.

| Label | optional | `None` | | licenses | - | List of strings | optional | `[]` | | main_class | Name of class with main() method to use as entry point. If a rule uses this option, it does not need a srcs=[...] list. Thus, with this attribute one can make an executable from a Java library that already contains one or more main() methods.

The value of this attribute is a class name, not a source file. The class must be available at runtime: it may be compiled by this rule (from srcs) or provided by direct or transitive dependencies (through runtime_deps or deps). If the class is unavailable, the binary will fail at runtime; there is no build-time check.

| String | optional | `""` | | neverlink | - | Boolean | optional | `False` | @@ -235,7 +235,7 @@ java_library(name, javabuilder_jvm_flags | Restricted API, do not use! | List of strings | optional | `[]` | | javacopts | Extra compiler options for this library. Subject to "Make variable" substitution and Bourne shell tokenization.

These compiler options are passed to javac after the global compiler options.

| List of strings | optional | `[]` | | licenses | - | List of strings | optional | `[]` | -| neverlink | Whether this library should only be used for compilation and not at runtime. Useful if the library will be provided by the runtime environment during execution. Examples of such libraries are the IDE APIs for IDE plug-ins or tools.jar for anything running on a standard JDK.

Note that neverlink = 1 does not prevent the compiler from inlining material from this library into compilation targets that depend on it, as permitted by the Java Language Specification (e.g., static final constants of String or of primitive types). The preferred use case is therefore when the runtime library is identical to the compilation library.

If the runtime library differs from the compilation library then you must ensure that it differs only in places that the JLS forbids compilers to inline (and that must hold for all future versions of the JLS).

| Boolean | optional | `False` | +| neverlink | Whether this library should only be used for compilation and not at runtime. Useful if the library will be provided by the runtime environment during execution. Examples of such libraries are the IDE APIs for IDE plug-ins or tools.jar for anything running on a standard JDK.

Note that neverlink = True does not prevent the compiler from inlining material from this library into compilation targets that depend on it, as permitted by the Java Language Specification (e.g., static final constants of String or of primitive types). The preferred use case is therefore when the runtime library is identical to the compilation library.

If the runtime library differs from the compilation library then you must ensure that it differs only in places that the JLS forbids compilers to inline (and that must hold for all future versions of the JLS).

| Boolean | optional | `False` | | plugins | Java compiler plugins to run at compile-time. Every java_plugin specified in this attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use exported_plugins. Resources generated by the plugin will be included in the resulting jar of this rule. | List of labels | optional | `[]` | | proguard_specs | Files to be used as Proguard specification. These will describe the set of specifications to be used by Proguard. If specified, they will be added to any android_binary target depending on this library.

The files included here must only have idempotent rules, namely -dontnote, -dontwarn, assumenosideeffects, and rules that start with -keep. Other options can only appear in android_binary's proguard_specs, to ensure non-tautological merges. | List of labels | optional | `[]` | | resource_strip_prefix | The path prefix to strip from Java resources.

If specified, this path prefix is stripped from every file in the resources attribute. It is an error for a resource file not to be under this directory. If not specified (the default), the path of resource file is determined according to the same logic as the Java package of source files. For example, a source file at stuff/java/foo/bar/a.txt will be located at foo/bar/a.txt.

| String | optional | `""` | @@ -344,7 +344,7 @@ java_plugin(name, de | javabuilder_jvm_flags | Restricted API, do not use! | List of strings | optional | `[]` | | javacopts | Extra compiler options for this library. Subject to "Make variable" substitution and Bourne shell tokenization.

These compiler options are passed to javac after the global compiler options.

| List of strings | optional | `[]` | | licenses | - | List of strings | optional | `[]` | -| neverlink | Whether this library should only be used for compilation and not at runtime. Useful if the library will be provided by the runtime environment during execution. Examples of such libraries are the IDE APIs for IDE plug-ins or tools.jar for anything running on a standard JDK.

Note that neverlink = 1 does not prevent the compiler from inlining material from this library into compilation targets that depend on it, as permitted by the Java Language Specification (e.g., static final constants of String or of primitive types). The preferred use case is therefore when the runtime library is identical to the compilation library.

If the runtime library differs from the compilation library then you must ensure that it differs only in places that the JLS forbids compilers to inline (and that must hold for all future versions of the JLS).

| Boolean | optional | `False` | +| neverlink | Whether this library should only be used for compilation and not at runtime. Useful if the library will be provided by the runtime environment during execution. Examples of such libraries are the IDE APIs for IDE plug-ins or tools.jar for anything running on a standard JDK.

Note that neverlink = True does not prevent the compiler from inlining material from this library into compilation targets that depend on it, as permitted by the Java Language Specification (e.g., static final constants of String or of primitive types). The preferred use case is therefore when the runtime library is identical to the compilation library.

If the runtime library differs from the compilation library then you must ensure that it differs only in places that the JLS forbids compilers to inline (and that must hold for all future versions of the JLS).

| Boolean | optional | `False` | | output_licenses | - | List of strings | optional | `[]` | | plugins | Java compiler plugins to run at compile-time. Every java_plugin specified in this attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use exported_plugins. Resources generated by the plugin will be included in the resulting jar of this rule. | List of labels | optional | `[]` | | processor_class | The processor class is the fully qualified type of the class that the Java compiler should use as entry point to the annotation processor. If not specified, this rule will not contribute an annotation processor to the Java compiler's annotation processing, but its runtime classpath will still be included on the compiler's annotation processor path. (This is primarily intended for use by Error Prone plugins, which are loaded from the annotation processor path using java.util.ServiceLoader.) | String | optional | `""` | @@ -473,7 +473,7 @@ java_test( | env_inherit | - | List of strings | optional | `[]` | | javacopts | Extra compiler options for this binary. Subject to "Make variable" substitution and Bourne shell tokenization.

These compiler options are passed to javac after the global compiler options.

| List of strings | optional | `[]` | | jvm_flags | A list of flags to embed in the wrapper script generated for running this binary. Subject to $(location) and "Make variable" substitution, and Bourne shell tokenization.

The wrapper script for a Java binary includes a CLASSPATH definition (to find all the dependent jars) and invokes the right Java interpreter. The command line generated by the wrapper script includes the name of the main class followed by a "$@" so you can pass along other arguments after the classname. However, arguments intended for parsing by the JVM must be specified before the classname on the command line. The contents of jvm_flags are added to the wrapper script before the classname is listed.



Note that this attribute has no effect on *_deploy.jar outputs.

| List of strings | optional | `[]` | -| launcher | Specify a binary that will be used to run your Java program instead of the normal bin/java program included with the JDK. The target must be a cc_binary. Any cc_binary that implements the Java Invocation API can be specified as a value for this attribute.

By default, Bazel will use the normal JDK launcher (bin/java or java.exe).



The related --java_launcher Bazel flag affects only those java_binary and java_test targets that have not specified a launcher attribute.



Note that your native (C++, SWIG, JNI) dependencies will be built differently depending on whether you are using the JDK launcher or another launcher:



  • If you are using the normal JDK launcher (the default), native dependencies are built as a shared library named {name}_nativedeps.so, where {name} is the name attribute of this java_binary rule. Unused code is not removed by the linker in this configuration.


  • If you are using any other launcher, native (C++) dependencies are statically linked into a binary named {name}_nativedeps, where {name} is the name attribute of this java_binary rule. In this case, the linker will remove any code it thinks is unused from the resulting binary, which means any C++ code accessed only via JNI may not be linked in unless that cc_library target specifies alwayslink = 1.


When using any launcher other than the default JDK launcher, the format of the *_deploy.jar output changes. See the main java_binary docs for details.

| Label | optional | `None` | +| launcher | Specify a binary that will be used to run your Java program instead of the normal bin/java program included with the JDK. The target must be a cc_binary. Any cc_binary that implements the Java Invocation API can be specified as a value for this attribute.

By default, Bazel will use the normal JDK launcher (bin/java or java.exe).



The related --java_launcher Bazel flag affects only those java_binary and java_test targets that have not specified a launcher attribute.



Note that your native (C++, SWIG, JNI) dependencies will be built differently depending on whether you are using the JDK launcher or another launcher:



  • If you are using the normal JDK launcher (the default), native dependencies are built as a shared library named {name}_nativedeps.so, where {name} is the name attribute of this java_binary rule. Unused code is not removed by the linker in this configuration.


  • If you are using any other launcher, native (C++) dependencies are statically linked into a binary named {name}_nativedeps, where {name} is the name attribute of this java_binary rule. In this case, the linker will remove any code it thinks is unused from the resulting binary, which means any C++ code accessed only via JNI may not be linked in unless that cc_library target specifies alwayslink = True.


When using any launcher other than the default JDK launcher, the format of the *_deploy.jar output changes. See the main java_binary docs for details.

| Label | optional | `None` | | licenses | - | List of strings | optional | `[]` | | main_class | Name of class with main() method to use as entry point. If a rule uses this option, it does not need a srcs=[...] list. Thus, with this attribute one can make an executable from a Java library that already contains one or more main() methods.

The value of this attribute is a class name, not a source file. The class must be available at runtime: it may be compiled by this rule (from srcs) or provided by direct or transitive dependencies (through runtime_deps or deps). If the class is unavailable, the binary will fail at runtime; there is no build-time check.

| String | optional | `""` | | neverlink | - | Boolean | optional | `False` | diff --git a/test/BUILD.bazel b/test/BUILD.bazel index a1d5be72..83186fbb 100644 --- a/test/BUILD.bazel +++ b/test/BUILD.bazel @@ -51,7 +51,7 @@ diff_test( failure_message = """ Docs are no longer up to date. Regenerate them by running: - bazel build //java/docs:rule_docs && \ + bazel build //java/docs:rules_docs && \ cp bazel-bin/java/docs/rules_docs.out java/docs/rules.md """, file1 = "//java/docs:rules.md", From d5c7eb1ac5cab8e02f64085a56f69ec7f98f7f55 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 29 Oct 2024 05:00:46 -0700 Subject: [PATCH 064/465] Drop `--experimental_google_legacy_api` in `rules_java` Update to Bazel 7.4.0 on CI PiperOrigin-RevId: 690972550 Change-Id: I6f5fcac68484afea4209d7145cedab2b26c0e201 --- .bazelci/presubmit.yml | 8 ++++---- .bazelrc | 3 --- test/repo/.bazelrc | 3 --- 3 files changed, 4 insertions(+), 10 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index a4854462..599b5f99 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -29,12 +29,12 @@ tasks: # Bazel 7.x ubuntu2004: name: "Bazel 7.x" - bazel: "7.3.2" + bazel: "7.4.0" build_targets: *build_targets test_targets: *test_targets ubuntu2004_integration: name: "Bazel 7.x Integration" - bazel: "7.3.2" + bazel: "7.4.0" platform: ubuntu2004 working_directory: "test/repo" shell_commands: @@ -45,11 +45,11 @@ tasks: - "@rules_java//java/..." macos: name: "Bazel 7.x" - bazel: "7.3.2" + bazel: "7.4.0" build_targets: *build_targets windows: name: "Bazel 7.x" - bazel: "7.3.2" + bazel: "7.4.0" build_targets: *build_targets # Bazel@HEAD ubuntu2004_head: diff --git a/.bazelrc b/.bazelrc index 03c47778..b55a2af3 100644 --- a/.bazelrc +++ b/.bazelrc @@ -1,5 +1,2 @@ common --incompatible_disallow_empty_glob common --experimental_rule_extension_api - -# TODO: remove once https://github.com/bazelbuild/bazel/commit/384e381fa841537987691f170ed9408dcfeed2ea is available -common --experimental_google_legacy_api diff --git a/test/repo/.bazelrc b/test/repo/.bazelrc index 1146197f..0a78015b 100644 --- a/test/repo/.bazelrc +++ b/test/repo/.bazelrc @@ -2,6 +2,3 @@ build:bzlmod --experimental_enable_bzlmod common --incompatible_disallow_empty_glob common --experimental_rule_extension_api - -# TODO: remove once https://github.com/bazelbuild/bazel/commit/384e381fa841537987691f170ed9408dcfeed2ea is available -common --experimental_google_legacy_api From e6afcd485bbf7dc345389f0082934f7f9ff37ce9 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 29 Oct 2024 05:52:02 -0700 Subject: [PATCH 065/465] Fix bazel_java_binary_wrapper.bzl visibility PiperOrigin-RevId: 690985575 Change-Id: I043784a1ef477d642245803322012a4bd8ee40d1 --- java/bazel/rules/bazel_java_binary_wrapper.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/bazel/rules/bazel_java_binary_wrapper.bzl b/java/bazel/rules/bazel_java_binary_wrapper.bzl index 15e8f6b2..0c61abf5 100644 --- a/java/bazel/rules/bazel_java_binary_wrapper.bzl +++ b/java/bazel/rules/bazel_java_binary_wrapper.bzl @@ -29,7 +29,7 @@ load(":bazel_java_binary_nonexec.bzl", java_bin_nonexec = "java_binary") _java_common_internal = java_common.internal_DO_NOT_USE() -visibility(["//java"]) +# copybara: default visibility def java_binary(**kwargs): if _java_common_internal.incompatible_disable_non_executable_java_binary(): From 0b8629c665466fa24fe2009be344a5add5332228 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 29 Oct 2024 05:56:20 -0700 Subject: [PATCH 066/465] Disable docs test on Bazel 7 PiperOrigin-RevId: 690986457 Change-Id: I9b285fd20c327c37c8a1aafd8d2e97f45ebf040b --- .bazelci/presubmit.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 599b5f99..3e2417fb 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -31,7 +31,10 @@ tasks: name: "Bazel 7.x" bazel: "7.4.0" build_targets: *build_targets - test_targets: *test_targets + test_targets: + - "//test/..." + - "//java/test/..." + - "-//test:docs_up_to_date_test" ubuntu2004_integration: name: "Bazel 7.x Integration" bazel: "7.4.0" From d291d3710a6acd400987f7200bd84cb60ff7abae Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 29 Oct 2024 08:28:15 -0700 Subject: [PATCH 067/465] Add an internal module extension to support Bazel 7 (and possibly 6 as well) Allows dropping use of `--experimental_rule_extension_api` PiperOrigin-RevId: 691029609 Change-Id: Ica6e9168d6403e84b51870c312cfc6fa6c75cdc5 --- .bazelrc | 1 - MODULE.bazel | 4 ++++ java/extensions.bzl | 6 ++++++ java/java_binary.bzl | 2 +- java/java_import.bzl | 2 +- java/java_library.bzl | 2 +- java/java_plugin.bzl | 2 +- java/java_test.bzl | 2 +- java/repositories.bzl | 42 ++++++++++++++++++++++++++++++++++++++++++ test/repo/.bazelrc | 1 - 10 files changed, 57 insertions(+), 7 deletions(-) diff --git a/.bazelrc b/.bazelrc index b55a2af3..5ef382d3 100644 --- a/.bazelrc +++ b/.bazelrc @@ -1,2 +1 @@ common --incompatible_disallow_empty_glob -common --experimental_rule_extension_api diff --git a/MODULE.bazel b/MODULE.bazel index 91262abf..0b4dcdeb 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -92,3 +92,7 @@ REMOTE_JDK_REPOS = [(("remote_jdk" if version == "8" else "remotejdk") + version # Dev dependencies bazel_dep(name = "rules_pkg", version = "0.9.1", dev_dependency = True) bazel_dep(name = "stardoc", version = "0.7.1", dev_dependency = True) + +# Compatibility layer +compat = use_extension("//java:extensions.bzl", "compatibility_proxy") +use_repo(compat, "compatibility_proxy") diff --git a/java/extensions.bzl b/java/extensions.bzl index f456f3f5..0530aa27 100644 --- a/java/extensions.bzl +++ b/java/extensions.bzl @@ -16,6 +16,7 @@ load("@bazel_features//:features.bzl", "bazel_features") load( "//java:repositories.bzl", + "compatibility_proxy_repo", "java_tools_repos", "local_jdk_repo", "remote_jdk11_repos", @@ -38,3 +39,8 @@ def _toolchains_impl(module_ctx): return None toolchains = module_extension(_toolchains_impl) + +def _compat_proxy_impl(_unused): + compatibility_proxy_repo() + +compatibility_proxy = module_extension(_compat_proxy_impl) diff --git a/java/java_binary.bzl b/java/java_binary.bzl index 18a3fed4..3c86ed21 100644 --- a/java/java_binary.bzl +++ b/java/java_binary.bzl @@ -13,7 +13,7 @@ # limitations under the License. """java_binary rule""" -load("//java/bazel/rules:bazel_java_binary_wrapper.bzl", _java_binary = "java_binary") +load("@compatibility_proxy//:proxy.bzl", _java_binary = "java_binary") def java_binary(**attrs): """Bazel java_binary rule. diff --git a/java/java_import.bzl b/java/java_import.bzl index 89f60309..7dfef834 100644 --- a/java/java_import.bzl +++ b/java/java_import.bzl @@ -13,7 +13,7 @@ # limitations under the License. """java_import rule""" -load("//java/bazel/rules:bazel_java_import.bzl", _java_import = "java_import") +load("@compatibility_proxy//:proxy.bzl", _java_import = "java_import") def java_import(**attrs): """Bazel java_import rule. diff --git a/java/java_library.bzl b/java/java_library.bzl index 90c72676..81e0ba16 100644 --- a/java/java_library.bzl +++ b/java/java_library.bzl @@ -13,7 +13,7 @@ # limitations under the License. """java_library rule""" -load("//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") +load("@compatibility_proxy//:proxy.bzl", _java_library = "java_library") def java_library(**attrs): """Bazel java_library rule. diff --git a/java/java_plugin.bzl b/java/java_plugin.bzl index 130dc625..e73843ab 100644 --- a/java/java_plugin.bzl +++ b/java/java_plugin.bzl @@ -13,7 +13,7 @@ # limitations under the License. """java_plugin rule""" -load("//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") +load("@compatibility_proxy//:proxy.bzl", _java_plugin = "java_plugin") def java_plugin(**attrs): """Bazel java_plugin rule. diff --git a/java/java_test.bzl b/java/java_test.bzl index 48a66551..d11f10bd 100644 --- a/java/java_test.bzl +++ b/java/java_test.bzl @@ -13,7 +13,7 @@ # limitations under the License. """java_test rule""" -load("//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") +load("@compatibility_proxy//:proxy.bzl", _java_test = "java_test") def java_test(**attrs): """Bazel java_test rule. diff --git a/java/repositories.bzl b/java/repositories.bzl index 50e7b760..712560fe 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -390,3 +390,45 @@ def rules_java_toolchains(name = "toolchains"): "@" + item.name + "_toolchain_config_repo//:toolchain", "@" + item.name + "_toolchain_config_repo//:bootstrap_runtime_toolchain", ) + +def _compatibility_proxy_repo_impl(rctx): + # TODO: use @bazel_features + bazel = native.bazel_version + rctx.file("BUILD.bazel", "") + if not bazel or bazel >= "8": + rctx.file( + "proxy.bzl", + """ +load("@rules_java//java/bazel/rules:bazel_java_binary_wrapper.bzl", _java_binary = "java_binary") # copybara-use-repo-external-label +load("@rules_java//java/bazel/rules:bazel_java_import.bzl", _java_import = "java_import") # copybara-use-repo-external-label +load("@rules_java//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") # copybara-use-repo-external-label +load("@rules_java//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") # copybara-use-repo-external-label +load("@rules_java//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") # copybara-use-repo-external-label + +java_binary = _java_binary +java_import = _java_import +java_library = _java_library +java_plugin = _java_plugin +java_test = _java_test + """, + ) + else: + rctx.file( + "proxy.bzl", + """ +java_binary = native.java_binary +java_import = native.java_import +java_library = native.java_library +java_plugin = native.java_plugin +java_test = native.java_test + """, + ) + +_compatibility_proxy_repo_rule = repository_rule( + _compatibility_proxy_repo_impl, + # force reruns on server restarts to use correct native.bazel_version + local = True, +) + +def compatibility_proxy_repo(): + maybe(_compatibility_proxy_repo_rule, name = "compatibility_proxy") diff --git a/test/repo/.bazelrc b/test/repo/.bazelrc index 0a78015b..e8aef359 100644 --- a/test/repo/.bazelrc +++ b/test/repo/.bazelrc @@ -1,4 +1,3 @@ build:bzlmod --experimental_enable_bzlmod common --incompatible_disallow_empty_glob -common --experimental_rule_extension_api From e14b558567ccf8353c30a419c320a5a61874c3b2 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 29 Oct 2024 23:14:59 -0700 Subject: [PATCH 068/465] Enable `rules_java` CI for Bazel 6 PiperOrigin-RevId: 691295884 Change-Id: Icf93e679c3a919983553ce47cd502e72d3216b15 --- .bazelci/presubmit.yml | 52 +++++++++++++++++++++++------------------- WORKSPACE | 19 +++++++++++++++ java/repositories.bzl | 33 +++++++++++++++++++++++++++ test/repo/WORKSPACE | 10 ++++++++ 4 files changed, 91 insertions(+), 23 deletions(-) create mode 100644 test/repo/WORKSPACE diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 3e2417fb..f89bc94c 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -9,14 +9,10 @@ build_targets: &build_targets - "-//java/docs/..." - "-//test:docs_up_to_date_test" -build_targets_bzlmod: &build_targets_bzlmod - - "//..." +build_targets_bazel6: &build_targets_bazel6 + - "//:all" - "@remote_java_tools//java_tools/..." - - "-//toolchains/..." - # TODO(pcloudy): pkg_tar doesn't work with Bzlmod due to https://github.com/bazelbuild/bazel/issues/14259 - # Enable once the issue is fixed. - - "-//distro/..." - - "-//test/repo/..." + - "//examples/..." test_targets: &test_targets - "//test/..." @@ -81,20 +77,30 @@ tasks: bazel: last_green platform: windows build_targets: *build_targets + # Bazel 6.x -# TODO: re-enable if possible to redirect to native rule impl -# ubuntu2004_bazel630: -# name: "Bazel 6.3.0" -# bazel: 6.3.0 -# platform: ubuntu2004 -# build_targets: *build_targets -# macos_bazel630: -# name: "Bazel 6.3.0" -# bazel: 6.3.0 -# platform: macos -# build_targets: *build_targets -# windows_bazel630: -# name: "Bazel 6.3.0" -# bazel: 6.3.0 -# platform: windows -# build_targets: *build_targets + ubuntu2004_bazel6: + name: "Bazel 6.x" + bazel: 6.5.0 + platform: ubuntu2004 + build_targets: *build_targets_bazel6 + ubuntu2004_integration_bazel6: + name: "Bazel 6.x Integration" + bazel: "6.5.0" + platform: ubuntu2004 + working_directory: "test/repo" + shell_commands: + - sh setup.sh + build_targets: + - "//..." + - "//:bin_deploy.jar" + macos_bazel6: + name: "Bazel 6.x" + bazel: 6.5.0 + platform: macos + build_targets: *build_targets_bazel6 + windows_bazel6: + name: "Bazel 6.x" + bazel: 6.5.0 + platform: windows + build_targets: *build_targets_bazel6 diff --git a/WORKSPACE b/WORKSPACE index 6e4b3c02..669f9743 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -27,3 +27,22 @@ http_archive( load("@rules_pkg//:deps.bzl", "rules_pkg_dependencies") rules_pkg_dependencies() + +http_archive( + name = "stardoc", + sha256 = "62bd2e60216b7a6fec3ac79341aa201e0956477e7c8f6ccc286f279ad1d96432", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/stardoc/releases/download/0.6.2/stardoc-0.6.2.tar.gz", + "https://github.com/bazelbuild/stardoc/releases/download/0.6.2/stardoc-0.6.2.tar.gz", + ], +) + +load("@stardoc//:setup.bzl", "stardoc_repositories") + +stardoc_repositories() + +load("//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchains") + +rules_java_dependencies() + +rules_java_toolchains() diff --git a/java/repositories.bzl b/java/repositories.bzl index 712560fe..84892d24 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -360,6 +360,35 @@ def remote_jdk21_repos(): """Imports OpenJDK 21 repositories.""" _remote_jdk_repos_for_version("21") +def protobuf_repo(): + maybe( + http_archive, + name = "protobuf", + sha256 = "da288bf1daa6c04d03a9051781caa52aceb9163586bff9aa6cfb12f69b9395aa", + strip_prefix = "protobuf-27.0", + url = "https://github.com/protocolbuffers/protobuf/releases/download/v27.0/protobuf-27.0.tar.gz", + ) + +def rules_cc_repo(): + maybe( + http_archive, + name = "rules_cc", + sha256 = "d9bdd3ec66b6871456ec9c965809f43a0901e692d754885e89293807762d3d80", + strip_prefix = "rules_cc-0.0.13", + urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.13/rules_cc-0.0.13.tar.gz"], + ) + +def bazel_skylib_repo(): + maybe( + http_archive, + name = "bazel_skylib", + sha256 = "f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz", + "https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz", + ], + ) + def rules_java_dependencies(): """An utility method to load all dependencies of rules_java. @@ -372,6 +401,10 @@ def rules_java_dependencies(): remote_jdk17_repos() remote_jdk21_repos() java_tools_repos() + compatibility_proxy_repo() + protobuf_repo() + rules_cc_repo() + bazel_skylib_repo() def rules_java_toolchains(name = "toolchains"): """An utility method to load all Java toolchains. diff --git a/test/repo/WORKSPACE b/test/repo/WORKSPACE new file mode 100644 index 00000000..c9614443 --- /dev/null +++ b/test/repo/WORKSPACE @@ -0,0 +1,10 @@ +local_repository( + name = "rules_java", + path = "../../", +) + +load("@rules_java//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchains") + +rules_java_dependencies() + +rules_java_toolchains() From 7253656054e6a9567c95c2713708c4c5d4272ba6 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 30 Oct 2024 04:32:36 -0700 Subject: [PATCH 069/465] Update `java_tools` to `v13.13` PiperOrigin-RevId: 691369022 Change-Id: Ie56d1a9f6a5dba19a927e5dca26b11f1550411d6 --- java/repositories.bzl | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/java/repositories.bzl b/java/repositories.bzl index 84892d24..81b12700 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.12", + "version": "v13.13", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.12/java_tools_linux-v13.12.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.12/java_tools_linux-v13.12.zip", - "sha": "ecdf36b1d93d1e6c270f6acf6e9cfd95b6ce52ce5e798f8a57aae6041d881cb9", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.13/java_tools_linux-v13.13.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.13/java_tools_linux-v13.13.zip", + "sha": "60c10e91f5900801423f9c5b020cc0c7da16dbaeee9c22891b38e7017306a8e7", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.12/java_tools_windows-v13.12.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.12/java_tools_windows-v13.12.zip", - "sha": "da590aa0bbc4f2967edcb7cc05cd0260412b6b057f9256bdd518a262a5f483c7", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.13/java_tools_windows-v13.13.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.13/java_tools_windows-v13.13.zip", + "sha": "f5de3f2afc49d1a457efa63926bcc0ca4cdb5fc4887160bf9163e49f059dd12c", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.12/java_tools_darwin_x86_64-v13.12.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.12/java_tools_darwin_x86_64-v13.12.zip", - "sha": "2a5c700567cae1f3dcfe42e702ee2fc5b1e4b66dfc13e8a2b5ccdddf12910e55", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.13/java_tools_darwin_x86_64-v13.13.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.13/java_tools_darwin_x86_64-v13.13.zip", + "sha": "d002ff57bd5e36d6d69a1c282fa571841816a1ccc5d28060cf7fe4c7257e376a", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.12/java_tools_darwin_arm64-v13.12.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.12/java_tools_darwin_arm64-v13.12.zip", - "sha": "97159db5a1f54301bc067ef1773c1eb7f7bc2f875bcb97a9e15baf4b08b129f2", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.13/java_tools_darwin_arm64-v13.13.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.13/java_tools_darwin_arm64-v13.13.zip", + "sha": "6d4b4e3a12cc5fd9f600b383465d0860afd5c11ba7c7386867bb621a55fa8452", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.12/java_tools-v13.12.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.12/java_tools-v13.12.zip", - "sha": "5f065d70984f607d1560f023348158bbbf6babdf4c4bbdd528ee867628b7fa1e", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.13/java_tools-v13.13.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.13/java_tools-v13.13.zip", + "sha": "df895d5067f2dad4524109ebfddac442d2514d0e2f95f6abc098cfae98b9bbb5", }, }, } From 6a34389003a6bed549858bb8f4673dd521ad8a54 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 30 Oct 2024 04:58:58 -0700 Subject: [PATCH 070/465] Release `rules_java` `v8.3.0` PiperOrigin-RevId: 691374574 Change-Id: I5facf50c5a6a57d15c716111d30072c82bccd599 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 0b4dcdeb..ac1d4987 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.2.0", + version = "8.3.0", bazel_compatibility = [">=7.3.2"], compatibility_level = 1, ) From 04598c7054a9034070147ddfb28f69f46ef26767 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 4 Nov 2024 02:03:08 -0800 Subject: [PATCH 071/465] Load `sh_test` from `@rules_shell` Fixes CI for Bazel@HEAD PiperOrigin-RevId: 692884241 Change-Id: I81cdd1916d7dd62459b89753a022a33380a09d76 --- MODULE.bazel | 1 + test/BUILD.bazel | 1 + 2 files changed, 2 insertions(+) diff --git a/MODULE.bazel b/MODULE.bazel index ac1d4987..f571952d 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -92,6 +92,7 @@ REMOTE_JDK_REPOS = [(("remote_jdk" if version == "8" else "remotejdk") + version # Dev dependencies bazel_dep(name = "rules_pkg", version = "0.9.1", dev_dependency = True) bazel_dep(name = "stardoc", version = "0.7.1", dev_dependency = True) +bazel_dep(name = "rules_shell", version = "0.2.0", dev_dependency = True) # Compatibility layer compat = use_extension("//java:extensions.bzl", "compatibility_proxy") diff --git a/test/BUILD.bazel b/test/BUILD.bazel index 83186fbb..cea33a5c 100644 --- a/test/BUILD.bazel +++ b/test/BUILD.bazel @@ -1,4 +1,5 @@ load("@bazel_skylib//rules:diff_test.bzl", "diff_test") +load("@rules_shell//shell:sh_test.bzl", "sh_test") # Copyright 2024 The Bazel Authors. All rights reserved. # From 309f6d2abce0a779eb9a171cfd44e3d4e493a6cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?X=C3=B9d=C5=8Dng=20Y=C3=A1ng?= Date: Tue, 5 Nov 2024 02:35:55 -0800 Subject: [PATCH 072/465] Add the repo rule `http_jar` Copybara Import from https://github.com/bazelbuild/rules_java/pull/238 BEGIN_PUBLIC Add the repo rule `http_jar` (#238) The repo rule `http_jar` currently lives in `@bazel_tools`, which results in an implicit dependency on `rules_java` because it creates a repo with a BUILD file that uses `java_import`. So this repo rule really belongs in `rules_java`. This PR copies it over from `@bazel_tools//tools/build_defs/repo:http.bzl` with minimal edits. Closes #238 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/238 from bazelbuild:wyv-http-jar 74d325a744cd7333e8669685d3ea1d3112a5078c PiperOrigin-RevId: 693270198 Change-Id: I44f6d60301f27db8515243af54f79cb0ab4a7c0c --- .bazelci/presubmit.yml | 5 + .bazelignore | 1 + java/http_jar.bzl | 200 ++++++++++++++++++++++++++++++++++++++ test/BUILD.bazel | 6 +- test/repo/BUILD.bazel | 10 +- test/repo/MODULE.bazel | 7 ++ test/repo/setup.sh | 6 +- test/repo/src/MyTest.java | 15 +++ test/testdata/BUILD.bazel | 7 ++ test/testdata/MyLib.java | 9 ++ 10 files changed, 259 insertions(+), 7 deletions(-) create mode 100644 .bazelignore create mode 100644 java/http_jar.bzl create mode 100644 test/repo/src/MyTest.java create mode 100644 test/testdata/BUILD.bazel create mode 100644 test/testdata/MyLib.java diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index f89bc94c..8971a404 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -42,6 +42,8 @@ tasks: - "//..." - "//:bin_deploy.jar" - "@rules_java//java/..." + test_targets: + - "//:MyTest" macos: name: "Bazel 7.x" bazel: "7.4.0" @@ -67,6 +69,8 @@ tasks: - "//..." - "//:bin_deploy.jar" - "@rules_java//java/..." + test_targets: + - "//:MyTest" macos_head: name: "Bazel@HEAD" bazel: last_green @@ -94,6 +98,7 @@ tasks: build_targets: - "//..." - "//:bin_deploy.jar" + - "-//:MyTest" macos_bazel6: name: "Bazel 6.x" bazel: 6.5.0 diff --git a/.bazelignore b/.bazelignore new file mode 100644 index 00000000..457eb2a0 --- /dev/null +++ b/.bazelignore @@ -0,0 +1 @@ +test/repo diff --git a/java/http_jar.bzl b/java/http_jar.bzl new file mode 100644 index 00000000..88654821 --- /dev/null +++ b/java/http_jar.bzl @@ -0,0 +1,200 @@ +"""The http_jar repo rule, for downloading jars over HTTP. + +### Setup + +To use this rule in a module extension, load it in your .bzl file and then call it from your +extension's implementation function. For example: + +```python +load("@rules_java//java:http_jar.bzl", "http_jar") + +def _my_extension_impl(mctx): + http_jar(name = "foo", urls = [...]) + +my_extension = module_extension(implementation = _my_extension_impl) +``` + +Alternatively, you can directly call it your MODULE.bazel file with `use_repo_rule`: + +```python +http_jar = use_repo_rule("@rules_java//java:http_jar.bzl", "http_jar") +http_jar(name = "foo", urls = [...]) +``` +""" + +load("@bazel_tools//tools/build_defs/repo:cache.bzl", "CANONICAL_ID_DOC", "DEFAULT_CANONICAL_ID_ENV", "get_default_canonical_id") +load("@bazel_tools//tools/build_defs/repo:utils.bzl", "get_auth", "update_attrs") + +_URL_DOC = """A URL to the jar that will be made available to Bazel. + +This must be a file, http or https URL. Redirections are followed. +Authentication is not supported. + +More flexibility can be achieved by the urls parameter that allows +to specify alternative URLs to fetch from.""" + +_URLS_DOC = """A list of URLs to the jar that will be made available to Bazel. + +Each entry must be a file, http or https URL. Redirections are followed. +Authentication is not supported. + +URLs are tried in order until one succeeds, so you should list local mirrors first. +If all downloads fail, the rule will fail.""" + +_AUTH_PATTERN_DOC = """An optional dict mapping host names to custom authorization patterns. + +If a URL's host name is present in this dict the value will be used as a pattern when +generating the authorization header for the http request. This enables the use of custom +authorization schemes used in a lot of common cloud storage providers. + +The pattern currently supports 2 tokens: <login> and +<password>, which are replaced with their equivalent value +in the netrc file for the same host name. After formatting, the result is set +as the value for the Authorization field of the HTTP request. + +Example attribute and netrc for a http download to an oauth2 enabled API using a bearer token: + +
+auth_patterns = {
+    "storage.cloudprovider.com": "Bearer <password>"
+}
+
+ +netrc: + +
+machine storage.cloudprovider.com
+        password RANDOM-TOKEN
+
+ +The final HTTP request would have the following header: + +
+Authorization: Bearer RANDOM-TOKEN
+
+""" + +def _get_source_urls(ctx): + """Returns source urls provided via the url, urls attributes. + + Also checks that at least one url is provided.""" + if not ctx.attr.url and not ctx.attr.urls: + fail("At least one of url and urls must be provided") + + source_urls = [] + if ctx.attr.urls: + source_urls = ctx.attr.urls + if ctx.attr.url: + source_urls = [ctx.attr.url] + source_urls + return source_urls + +def _update_integrity_attr(ctx, attrs, download_info): + # We don't need to override the integrity attribute if sha256 is already specified. + integrity_override = {} if ctx.attr.sha256 else {"integrity": download_info.integrity} + return update_attrs(ctx.attr, attrs.keys(), integrity_override) + +_HTTP_JAR_BUILD = """\ +load("{java_import_bzl}", "java_import") + +java_import( + name = 'jar', + jars = ["{file_name}"], + visibility = ['//visibility:public'], +) + +filegroup( + name = 'file', + srcs = ["{file_name}"], + visibility = ['//visibility:public'], +) + +""" + +def _http_jar_impl(ctx): + """Implementation of the http_jar rule.""" + source_urls = _get_source_urls(ctx) + downloaded_file_name = ctx.attr.downloaded_file_name + download_info = ctx.download( + source_urls, + "jar/" + downloaded_file_name, + ctx.attr.sha256, + canonical_id = ctx.attr.canonical_id or get_default_canonical_id(ctx, source_urls), + auth = get_auth(ctx, source_urls), + integrity = ctx.attr.integrity, + ) + ctx.file("jar/BUILD", _HTTP_JAR_BUILD.format( + java_import_bzl = str(Label("//java:java_import.bzl")), + file_name = downloaded_file_name, + )) + + return _update_integrity_attr(ctx, _http_jar_attrs, download_info) + +_http_jar_attrs = { + "sha256": attr.string( + doc = """The expected SHA-256 of the jar downloaded. + +This must match the SHA-256 of the jar downloaded. _It is a security risk +to omit the SHA-256 as remote files can change._ At best omitting this +field will make your build non-hermetic. It is optional to make development +easier but either this attribute or `integrity` should be set before shipping.""", + ), + "integrity": attr.string( + doc = """Expected checksum in Subresource Integrity format of the jar downloaded. + +This must match the checksum of the file downloaded. _It is a security risk +to omit the checksum as remote files can change._ At best omitting this +field will make your build non-hermetic. It is optional to make development +easier but either this attribute or `sha256` should be set before shipping.""", + ), + "canonical_id": attr.string( + doc = CANONICAL_ID_DOC, + ), + "url": attr.string(doc = _URL_DOC + "\n\nThe URL must end in `.jar`."), + "urls": attr.string_list(doc = _URLS_DOC + "\n\nAll URLs must end in `.jar`."), + "netrc": attr.string( + doc = "Location of the .netrc file to use for authentication", + ), + "auth_patterns": attr.string_dict( + doc = _AUTH_PATTERN_DOC, + ), + "downloaded_file_name": attr.string( + default = "downloaded.jar", + doc = "Filename assigned to the jar downloaded", + ), +} + +http_jar = repository_rule( + implementation = _http_jar_impl, + attrs = _http_jar_attrs, + environ = [DEFAULT_CANONICAL_ID_ENV], + doc = + """Downloads a jar from a URL and makes it available as java_import + +Downloaded files must have a .jar extension. + +Examples: + Suppose the current repository contains the source code for a chat program, rooted at the + directory `~/chat-app`. It needs to depend on an SSL library which is available from + `http://example.com/openssl-0.2.jar`. + + Targets in the `~/chat-app` repository can depend on this target if the following lines are + added to `~/chat-app/MODULE.bazel`: + + ```python + http_jar = use_repo_rule("@rules_java//java:http_jar.bzl", "http_jar") + + http_jar( + name = "my_ssl", + url = "http://example.com/openssl-0.2.jar", + sha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + ) + ``` + + Targets would specify `@my_ssl//jar` as a dependency to depend on this jar. + + You may also reference files on the current system (localhost) by using "file:///path/to/file" + if you are on Unix-based systems. If you're on Windows, use "file:///c:/path/to/file". In both + examples, note the three slashes (`/`) -- the first two slashes belong to `file://` and the third + one belongs to the absolute path to the file. +""", +) diff --git a/test/BUILD.bazel b/test/BUILD.bazel index cea33a5c..00506f87 100644 --- a/test/BUILD.bazel +++ b/test/BUILD.bazel @@ -1,6 +1,3 @@ -load("@bazel_skylib//rules:diff_test.bzl", "diff_test") -load("@rules_shell//shell:sh_test.bzl", "sh_test") - # Copyright 2024 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,6 +11,9 @@ load("@rules_shell//shell:sh_test.bzl", "sh_test") # 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("@bazel_skylib//rules:diff_test.bzl", "diff_test") +load("@rules_shell//shell:sh_test.bzl", "sh_test") load("//java:repositories.bzl", "JAVA_TOOLS_CONFIG", "REMOTE_JDK_CONFIGS") load(":check_remotejdk_configs_match.bzl", "validate_configs") diff --git a/test/repo/BUILD.bazel b/test/repo/BUILD.bazel index 6b7da400..20deeaeb 100644 --- a/test/repo/BUILD.bazel +++ b/test/repo/BUILD.bazel @@ -1,9 +1,9 @@ -load("@rules_java//java:defs.bzl", "java_binary", "java_library") # copybara-use-repo-external-label +load("@rules_java//java:defs.bzl", "java_binary", "java_library", "java_test") # copybara-use-repo-external-label load("@rules_java//toolchains:default_java_toolchain.bzl", "default_java_toolchain") # copybara-use-repo-external-label java_library( name = "lib", - srcs = glob(["src/*.java"]), + srcs = ["src/Main.java"], ) java_binary( @@ -12,6 +12,12 @@ java_binary( runtime_deps = [":lib"], ) +java_test( + name = "MyTest", + srcs = ["src/MyTest.java"], + deps = ["@my_jar//jar"], +) + default_java_toolchain( name = "my_funky_toolchain", ) diff --git a/test/repo/MODULE.bazel b/test/repo/MODULE.bazel index c9729b4d..5a4d6114 100644 --- a/test/repo/MODULE.bazel +++ b/test/repo/MODULE.bazel @@ -6,6 +6,13 @@ archive_override( urls = ["file:///tmp/rules_java-HEAD.tar.gz"], ) +http_jar = use_repo_rule("@rules_java//java:http_jar.bzl", "http_jar") + +http_jar( + name = "my_jar", + urls = ["file:///tmp/my_jar.jar"], +) + java_toolchains = use_extension("@rules_java//java:extensions.bzl", "toolchains") use_repo( java_toolchains, diff --git a/test/repo/setup.sh b/test/repo/setup.sh index 4c268fc6..7e3b369a 100644 --- a/test/repo/setup.sh +++ b/test/repo/setup.sh @@ -1,5 +1,7 @@ #!/usr/bin/env bash cd ../../ -bazel build //distro:all -cp -f bazel-bin/distro/rules_java-*.tar.gz /tmp/rules_java-HEAD.tar.gz \ No newline at end of file +bazel build //distro:all //test/testdata:my_jar +cp -f bazel-bin/distro/rules_java-*.tar.gz /tmp/rules_java-HEAD.tar.gz +cp -f bazel-bin/test/testdata/libmy_jar.jar /tmp/my_jar.jar + diff --git a/test/repo/src/MyTest.java b/test/repo/src/MyTest.java new file mode 100644 index 00000000..2de08a05 --- /dev/null +++ b/test/repo/src/MyTest.java @@ -0,0 +1,15 @@ +import static org.junit.Assert.assertEquals; + +import mypackage.MyLib; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class MyTest { + @Test + public void main() { + assertEquals(MyLib.myStr(), "my_string"); + } +} + diff --git a/test/testdata/BUILD.bazel b/test/testdata/BUILD.bazel new file mode 100644 index 00000000..ffcc5c35 --- /dev/null +++ b/test/testdata/BUILD.bazel @@ -0,0 +1,7 @@ +load("//java:java_library.bzl", "java_library") + +# Make a sample jar for the http_jar test. +java_library( + name = "my_jar", + srcs = ["MyLib.java"], +) diff --git a/test/testdata/MyLib.java b/test/testdata/MyLib.java new file mode 100644 index 00000000..48428f12 --- /dev/null +++ b/test/testdata/MyLib.java @@ -0,0 +1,9 @@ +package mypackage; + +/** A simple library for the http_jar test. */ +public class MyLib { + public static String myStr() { + return "my_string"; + } +} + From 9fd8c492e7e5751f809912554d5ee9a4cc3f53d9 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 8 Nov 2024 01:52:54 -0800 Subject: [PATCH 073/465] Use @com_google_protobuf instead of @protobuf in rules_java This is to support WORKSPACE mode. Bazel <=7 requires the repository to be called @com_google_protobuf because of the default value of --protocol_compiler flag. To make the migration smooth we need to have the same requirement in Bazel 8. Upgrade rules_cc to 0.0.15 because of the same thing. Patch BUILD.java_tools from Bazel with @com_google_protobuf. Reorder WORKSPACE, so that the correct version of Protobuf is picked up. PiperOrigin-RevId: 694411552 Change-Id: I1d5d30bc28becc8fe8575846c54bd5ef2d431aa8 --- MODULE.bazel | 4 +- WORKSPACE | 8 +- java/BUILD | 4 +- java/common/rules/impl/BUILD | 2 +- java/common/rules/impl/java_binary_impl.bzl | 2 +- java/defs.bzl | 4 +- java/repositories.bzl | 10 +- toolchains/BUILD.java_tools | 669 ++++++++++++++++++++ 8 files changed, 687 insertions(+), 16 deletions(-) create mode 100644 toolchains/BUILD.java_tools diff --git a/MODULE.bazel b/MODULE.bazel index f571952d..ee658f60 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -6,10 +6,10 @@ module( ) bazel_dep(name = "platforms", version = "0.0.4") -bazel_dep(name = "rules_cc", version = "0.0.13") +bazel_dep(name = "rules_cc", version = "0.0.15") bazel_dep(name = "bazel_features", version = "1.11.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") -bazel_dep(name = "protobuf", version = "27.0") +bazel_dep(name = "protobuf", version = "27.0", repo_name = "com_google_protobuf") # Required by @remote_java_tools, which is loaded via module extension. bazel_dep(name = "rules_license", version = "0.0.3") diff --git a/WORKSPACE b/WORKSPACE index 669f9743..7f4e8571 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -37,12 +37,12 @@ http_archive( ], ) -load("@stardoc//:setup.bzl", "stardoc_repositories") - -stardoc_repositories() - load("//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchains") rules_java_dependencies() rules_java_toolchains() + +load("@stardoc//:setup.bzl", "stardoc_repositories") + +stardoc_repositories() diff --git a/java/BUILD b/java/BUILD index 3e6823ff..17101290 100644 --- a/java/BUILD +++ b/java/BUILD @@ -26,8 +26,8 @@ bzl_library( ":core_rules", "//java/common", "//java/toolchains:toolchain_rules", - "@protobuf//bazel:java_lite_proto_library_bzl", - "@protobuf//bazel:java_proto_library_bzl", + "@com_google_protobuf//bazel:java_lite_proto_library_bzl", + "@com_google_protobuf//bazel:java_proto_library_bzl", ], ) diff --git a/java/common/rules/impl/BUILD b/java/common/rules/impl/BUILD index a1c0f91b..fc962030 100644 --- a/java/common/rules/impl/BUILD +++ b/java/common/rules/impl/BUILD @@ -17,7 +17,7 @@ bzl_library( visibility = ["//java:__subpackages__"], deps = [ ":java_helper_bzl", - "@protobuf//bazel/common:proto_info_bzl", + "@com_google_protobuf//bazel/common:proto_info_bzl", ], ) diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl index 80adbb5e..bdaa4acd 100644 --- a/java/common/rules/impl/java_binary_impl.bzl +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -14,7 +14,7 @@ """ Implementation of java_binary for bazel """ -load("@protobuf//bazel/common:proto_info.bzl", "ProtoInfo") +load("@com_google_protobuf//bazel/common:proto_info.bzl", "ProtoInfo") load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_common.bzl", "java_common") diff --git a/java/defs.bzl b/java/defs.bzl index e73d633f..f5b4de86 100644 --- a/java/defs.bzl +++ b/java/defs.bzl @@ -13,8 +13,8 @@ # limitations under the License. """Starlark rules for building Java projects.""" -load("@protobuf//bazel:java_lite_proto_library.bzl", _java_lite_proto_library = "java_lite_proto_library") -load("@protobuf//bazel:java_proto_library.bzl", _java_proto_library = "java_proto_library") +load("@com_google_protobuf//bazel:java_lite_proto_library.bzl", _java_lite_proto_library = "java_lite_proto_library") +load("@com_google_protobuf//bazel:java_proto_library.bzl", _java_proto_library = "java_proto_library") load("//java:java_binary.bzl", _java_binary = "java_binary") load("//java:java_import.bzl", _java_import = "java_import") load("//java:java_library.bzl", _java_library = "java_library") diff --git a/java/repositories.bzl b/java/repositories.bzl index 81b12700..2da0abef 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -49,6 +49,7 @@ JAVA_TOOLS_CONFIG = { "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.13/java_tools-v13.13.zip", "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.13/java_tools-v13.13.zip", "sha": "df895d5067f2dad4524109ebfddac442d2514d0e2f95f6abc098cfae98b9bbb5", + "build_file": "@rules_java//toolchains:BUILD.java_tools", }, }, } @@ -64,6 +65,7 @@ def java_tools_repos(): config["mirror_url"], config["github_url"], ], + build_file = config.get("build_file"), ) def local_jdk_repo(): @@ -363,7 +365,7 @@ def remote_jdk21_repos(): def protobuf_repo(): maybe( http_archive, - name = "protobuf", + name = "com_google_protobuf", sha256 = "da288bf1daa6c04d03a9051781caa52aceb9163586bff9aa6cfb12f69b9395aa", strip_prefix = "protobuf-27.0", url = "https://github.com/protocolbuffers/protobuf/releases/download/v27.0/protobuf-27.0.tar.gz", @@ -373,9 +375,9 @@ def rules_cc_repo(): maybe( http_archive, name = "rules_cc", - sha256 = "d9bdd3ec66b6871456ec9c965809f43a0901e692d754885e89293807762d3d80", - strip_prefix = "rules_cc-0.0.13", - urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.13/rules_cc-0.0.13.tar.gz"], + sha256 = "f4aadd8387f381033a9ad0500443a52a0cea5f8ad1ede4369d3c614eb7b2682e", + strip_prefix = "rules_cc-0.0.15", + urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.15/rules_cc-0.0.15.tar.gz"], ) def bazel_skylib_repo(): diff --git a/toolchains/BUILD.java_tools b/toolchains/BUILD.java_tools new file mode 100644 index 00000000..9c68b758 --- /dev/null +++ b/toolchains/BUILD.java_tools @@ -0,0 +1,669 @@ +load("@com_google_protobuf//bazel:cc_proto_library.bzl", "cc_proto_library") +load("@com_google_protobuf//bazel:proto_library.bzl", "proto_library") +load("@rules_cc//cc:cc_binary.bzl", "cc_binary") +load("@rules_cc//cc:cc_library.bzl", "cc_library") +load("@rules_java//java:java_binary.bzl", "java_binary") +load("@rules_java//java:java_import.bzl", "java_import") + +package(default_visibility = ["//visibility:public"]) + +exports_files(glob(["**/*.jar"])) + +licenses(["notice"]) # Apache 2.0 + +SUPRESSED_WARNINGS = select({ + ":windows": [], + "//conditions:default": [ + "-Wno-error", + "-Wno-old-style-cast", + ], +}) + +filegroup( + name = "GenClass", + srcs = ["java_tools/GenClass_deploy.jar"], +) + +filegroup( + name = "jacoco_coverage_runner_filegroup", + srcs = ["java_tools/JacocoCoverage_jarjar_deploy.jar"], +) + +java_import( + name = "jacoco_coverage_runner", + jars = ["java_tools/JacocoCoverage_jarjar_deploy.jar"], +) + +filegroup( + name = "JacocoCoverage", + srcs = ["java_tools/JacocoCoverage_jarjar_deploy.jar"], +) + +filegroup( + name = "JavaBuilder", + srcs = ["java_tools/JavaBuilder_deploy.jar"], +) + +filegroup( + name = "Runner", + srcs = ["java_tools/Runner_deploy.jar"], +) + +filegroup( + name = "VanillaJavaBuilder", + srcs = ["java_tools/VanillaJavaBuilder_deploy.jar"], +) + +filegroup( + name = "TurbineDirect", + srcs = ["java_tools/turbine_direct_binary_deploy.jar"], +) + +java_import( + name = "jacoco-agent", + jars = ["java_tools/third_party/java/jacoco/org.jacoco.agent-0.8.11.jar"], + srcjar = "java_tools/third_party/java/jacoco/org.jacoco.agent-0.8.11-sources.jar", +) + +java_import( + name = "jacoco-core", + jars = ["java_tools/third_party/java/jacoco/org.jacoco.core-0.8.11.jar"], + srcjar = "java_tools/third_party/java/jacoco/org.jacoco.core-0.8.11-sources.jar", + exports = [ + ":asm", + ":asm-commons", + ":asm-tree", + ], +) + +filegroup( + name = "jacoco-core-jars", + srcs = ["java_tools/third_party/java/jacoco/org.jacoco.core-0.8.11.jar"], +) + +java_import( + name = "jacoco-report", + jars = ["java_tools/third_party/java/jacoco/org.jacoco.report-0.8.11.jar"], + srcjar = "java_tools/third_party/java/jacoco/org.jacoco.report-0.8.11-sources.jar", + exports = [ + ":asm", + ":jacoco-core", + ], +) + +java_import( + name = "bazel-jacoco-agent", + jars = ["java_tools/third_party/java/jacoco/jacocoagent-0.8.11.jar"], +) + +java_import( + name = "bazel-jacoco-agent-neverlink", + jars = ["java_tools/third_party/java/jacoco/jacocoagent-0.8.11.jar"], + neverlink = 1, +) + +java_import( + name = "asm", + jars = ["java_tools/third_party/java/jacoco/asm-9.6.jar"], + srcjar = "java_tools/third_party/java/jacoco/asm-9.6-sources.jar", +) + +java_import( + name = "asm-commons", + jars = ["java_tools/third_party/java/jacoco/asm-commons-9.6.jar"], + srcjar = "java_tools/third_party/java/jacoco/asm-commons-9.6-sources.jar", + runtime_deps = [":asm-tree"], +) + +java_import( + name = "asm-tree", + jars = ["java_tools/third_party/java/jacoco/asm-tree-9.6.jar"], + srcjar = "java_tools/third_party/java/jacoco/asm-tree-9.6-sources.jar", + runtime_deps = [":asm"], +) + +config_setting( + name = "windows", + constraint_values = ["@platforms//os:windows"], +) + +config_setting( + name = "freebsd", + constraint_values = ["@platforms//os:freebsd"], + visibility = ["//visibility:public"], +) + +config_setting( + name = "openbsd", + constraint_values = ["@platforms//os:openbsd"], + visibility = ["//visibility:public"], +) + +# Create intermediate cc_library, which does not implicitly depend on "malloc" +# and "link_extra_lib" in @bazel_tools//tools/cpp, and thereby avoids include +# path /Iexternal/tools being used in compiling actions which would result in +# the wrong headers being picked up. +cc_library( + name = "ijar_cc_binary_main", + srcs = [ + "java_tools/ijar/classfile.cc", + "java_tools/ijar/ijar.cc", + ], + copts = SUPRESSED_WARNINGS, + linkstatic = 1, # provides main() + deps = [":zip"], + alwayslink = 1, +) + +cc_binary( + name = "ijar_cc_binary", + deps = [":ijar_cc_binary_main"], +) + +cc_library( + name = "zip", + srcs = [ + "java_tools/ijar/zip.cc", + ] + select({ + ":windows": [ + "java_tools/ijar/mapped_file_windows.cc", + ], + "//conditions:default": [ + "java_tools/ijar/mapped_file_unix.cc", + ], + }), + hdrs = [ + "java_tools/ijar/common.h", + "java_tools/ijar/mapped_file.h", + "java_tools/ijar/zip.h", + ], + copts = SUPRESSED_WARNINGS, + include_prefix = "third_party", + strip_include_prefix = "java_tools", + deps = [ + ":platform_utils", + ":zlib_client", + ] + select({ + ":windows": [ + ":errors", + ":filesystem", + ":logging", + ":strings", + ], + "//conditions:default": [ + ], + }), +) + +cc_library( + name = "platform_utils", + srcs = ["java_tools/ijar/platform_utils.cc"], + hdrs = [ + "java_tools/ijar/common.h", + "java_tools/ijar/platform_utils.h", + ], + copts = SUPRESSED_WARNINGS, + include_prefix = "third_party", + strip_include_prefix = "java_tools", + visibility = ["//visibility:private"], + deps = [ + ":errors", + ":filesystem", + ":logging", + ], +) + +cc_library( + name = "cpp_util", + hdrs = [ + "java_tools/src/main/cpp/util/errors.h", + "java_tools/src/main/cpp/util/file.h", + "java_tools/src/main/cpp/util/file_platform.h", + "java_tools/src/main/cpp/util/md5.h", + "java_tools/src/main/cpp/util/numbers.h", + "java_tools/src/main/cpp/util/path.h", + "java_tools/src/main/cpp/util/path_platform.h", + "java_tools/src/main/cpp/util/port.h", + ], + strip_include_prefix = "java_tools", + visibility = ["//visibility:public"], + deps = [ + ":blaze_exit_code", + ":errors", + ":filesystem", + ":md5", + ":numbers", + ":port", + ":strings", + ], +) + +cc_library( + name = "md5", + srcs = ["java_tools/src/main/cpp/util/md5.cc"], + hdrs = ["java_tools/src/main/cpp/util/md5.h"], + strip_include_prefix = "java_tools", +) + +cc_library( + name = "numbers", + srcs = ["java_tools/src/main/cpp/util/numbers.cc"], + hdrs = ["java_tools/src/main/cpp/util/numbers.h"], + strip_include_prefix = "java_tools", + deps = [":strings"], +) + +cc_library( + name = "filesystem", + srcs = [ + "java_tools/src/main/cpp/util/file.cc", + "java_tools/src/main/cpp/util/path.cc", + ] + select({ + ":windows": [ + "java_tools/src/main/cpp/util/file_windows.cc", + "java_tools/src/main/cpp/util/path_windows.cc", + ], + "//conditions:default": [ + "java_tools/src/main/cpp/util/file_posix.cc", + "java_tools/src/main/cpp/util/path_posix.cc", + ], + }), + hdrs = [ + "java_tools/src/main/cpp/util/file.h", + "java_tools/src/main/cpp/util/file_platform.h", + "java_tools/src/main/cpp/util/path.h", + "java_tools/src/main/cpp/util/path_platform.h", + ], + strip_include_prefix = "java_tools", + deps = [ + ":blaze_exit_code", + ":errors", + ":logging", + ":strings", + ] + select({ + ":windows": [":lib-file"], + "//conditions:default": [], + }), +) + +cc_library( + name = "lib-file", + srcs = [ + "java_tools/src/main/native/windows/file.cc", + "java_tools/src/main/native/windows/util.cc", + ], + hdrs = [ + "java_tools/src/main/native/windows/file.h", + "java_tools/src/main/native/windows/util.h", + ], + linkopts = [ + "-DEFAULTLIB:advapi32.lib", + ], + strip_include_prefix = "java_tools", +) + +cc_library( + name = "errors", + srcs = select({ + ":windows": ["java_tools/src/main/cpp/util/errors_windows.cc"], + "//conditions:default": ["java_tools/src/main/cpp/util/errors_posix.cc"], + }), + hdrs = ["java_tools/src/main/cpp/util/errors.h"], + strip_include_prefix = "java_tools", + deps = [ + ":logging", + ":port", + ":strings", + ], +) + +cc_library( + name = "strings", + srcs = ["java_tools/src/main/cpp/util/strings.cc"], + hdrs = ["java_tools/src/main/cpp/util/strings.h"], + copts = SUPRESSED_WARNINGS, + # Automatically propagate the symbol definition to rules depending on this. + defines = [ + "BLAZE_OPENSOURCE", + ], + strip_include_prefix = "java_tools", + deps = [":blaze_exit_code"], +) + +cc_library( + name = "blaze_exit_code", + hdrs = ["java_tools/src/main/cpp/util/exit_code.h"], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", +) + +cc_library( + name = "port", + srcs = ["java_tools/src/main/cpp/util/port.cc"], + hdrs = ["java_tools/src/main/cpp/util/port.h"], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", +) + +cc_library( + name = "logging", + srcs = ["java_tools/src/main/cpp/util/logging.cc"], + hdrs = ["java_tools/src/main/cpp/util/logging.h"], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + deps = [ + ":blaze_exit_code", + ":strings", + ], +) + +cc_library( + name = "zlib_client", + srcs = ["java_tools/ijar/zlib_client.cc"], + hdrs = [ + "java_tools/ijar/common.h", + "java_tools/ijar/zlib_client.h", + ], + copts = SUPRESSED_WARNINGS, + include_prefix = "third_party", + strip_include_prefix = "java_tools", + deps = ["//java_tools/zlib"], +) + +##################### singlejar + +# See comment for ":ijar_cc_binary_main". +cc_library( + name = "singlejar_cc_bin_main", + srcs = [ + "java_tools/src/tools/singlejar/singlejar_main.cc", + ], + copts = SUPRESSED_WARNINGS, + linkopts = select({ + ":freebsd": ["-lm"], + ":openbsd": ["-lm"], + "//conditions:default": [], + }), + linkstatic = 1, # provides main() + deps = [ + ":combiners", + ":diag", + ":options", + ":output_jar", + "//java_tools/zlib", + ], + alwayslink = 1, +) + +cc_binary( + name = "singlejar_cc_bin", + linkstatic = 1, + visibility = ["//visibility:public"], + deps = [":singlejar_cc_bin_main"], +) + +cc_binary( + name = "singlejar_local", + srcs = [ + "java_tools/src/tools/singlejar/singlejar_local_main.cc", + ], + copts = SUPRESSED_WARNINGS, + linkopts = select({ + ":freebsd": ["-lm"], + ":openbsd": ["-lm"], + "//conditions:default": [], + }), + linkstatic = 1, + visibility = ["//visibility:public"], + deps = [ + ":combiners", + ":desugar_checking", + ":options", + ":output_jar", + "//java_tools/zlib", + ], +) + +cc_library( + name = "combiners", + srcs = [ + "java_tools/src/tools/singlejar/combiners.cc", + ], + hdrs = [ + "java_tools/src/tools/singlejar/combiners.h", + ":transient_bytes", + ], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + deps = [ + "//java_tools/zlib", + ], +) + +proto_library( + name = "desugar_deps_proto", + srcs = ["java_tools/src/main/protobuf/desugar_deps.proto"], +) + +cc_proto_library( + name = "desugar_deps_cc_proto", + deps = [":desugar_deps_proto"], +) + +cc_library( + name = "desugar_checking", + srcs = ["java_tools/src/tools/singlejar/desugar_checking.cc"], + hdrs = ["java_tools/src/tools/singlejar/desugar_checking.h"], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + deps = [ + ":combiners", + ":desugar_deps_cc_proto", + ], +) + +cc_library( + name = "diag", + hdrs = ["java_tools/src/tools/singlejar/diag.h"], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + visibility = ["//visibility:private"], +) + +cc_library( + name = "singlejar_port", + hdrs = ["java_tools/src/tools/singlejar/port.h"], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + visibility = ["//visibility:private"], +) + +cc_library( + name = "mapped_file", + srcs = ["java_tools/src/tools/singlejar/mapped_file.cc"], + hdrs = ["java_tools/src/tools/singlejar/mapped_file.h"] + + select({ + ":windows": ["java_tools/src/tools/singlejar/mapped_file_windows.inc"], + "//conditions:default": ["java_tools/src/tools/singlejar/mapped_file_posix.inc"], + }), + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + visibility = ["//visibility:private"], + deps = [ + ":cpp_util", + ":diag", + ":singlejar_port", + ], +) + +cc_library( + name = "input_jar", + srcs = [ + "java_tools/src/tools/singlejar/input_jar.cc", + ], + hdrs = [ + "java_tools/src/tools/singlejar/input_jar.h", + "java_tools/src/tools/singlejar/zip_headers.h", + ], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + deps = [ + ":diag", + ":mapped_file", + ], +) + +cc_library( + name = "options", + srcs = [ + "java_tools/src/tools/singlejar/options.cc", + "java_tools/src/tools/singlejar/options.h", + ], + hdrs = ["java_tools/src/tools/singlejar/options.h"], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + deps = [ + ":diag", + ":token_stream", + ], +) + +cc_library( + name = "output_jar", + srcs = [ + "java_tools/src/tools/singlejar/output_jar.cc", + "java_tools/src/tools/singlejar/output_jar.h", + ":zip_headers", + ], + hdrs = ["java_tools/src/tools/singlejar/output_jar.h"], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + deps = [ + ":combiners", + ":cpp_util", + ":diag", + ":input_jar", + ":mapped_file", + ":options", + ":singlejar_port", + "//java_tools/zlib", + ], +) + +cc_library( + name = "token_stream", + hdrs = ["java_tools/src/tools/singlejar/token_stream.h"], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + deps = [ + ":diag", + ":filesystem", + ], +) + +filegroup( + name = "transient_bytes", + srcs = [ + "java_tools/src/tools/singlejar/diag.h", + "java_tools/src/tools/singlejar/transient_bytes.h", + "java_tools/src/tools/singlejar/zlib_interface.h", + ":zip_headers", + ], +) + +filegroup( + name = "zip_headers", + srcs = ["java_tools/src/tools/singlejar/zip_headers.h"], +) + +################### Proguard ################### +java_import( + name = "proguard_import", + jars = ["java_tools/third_party/java/proguard/proguard.jar"], +) + +java_binary( + name = "proguard", + main_class = "proguard.ProGuard", + visibility = ["//visibility:public"], + runtime_deps = [":proguard_import"], +) + +##################### one_version + +# See comment for ":ijar_cc_binary_main". +cc_library( + name = "one_version_cc_bin_main", + srcs = [ + "java_tools/src/tools/one_version/one_version_main.cc", + ], + copts = SUPRESSED_WARNINGS, + linkopts = select({ + ":freebsd": ["-lm"], + ":openbsd": ["-lm"], + "//conditions:default": [], + }), + linkstatic = 1, # provides main() + deps = [ + ":allowlist", + ":duplicate_class_collector", + ":input_jar", + ":one_version", + ":token_stream", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/container:flat_hash_set", + "@com_google_absl//absl/log:die_if_null", + "@com_google_absl//absl/strings", + ], + alwayslink = 1, +) + +cc_binary( + name = "one_version_cc_bin", + linkstatic = 1, + visibility = ["//visibility:public"], + deps = [":one_version_cc_bin_main"], +) + +cc_library( + name = "duplicate_class_collector", + srcs = ["java_tools/src/tools/one_version/duplicate_class_collector.cc"], + hdrs = ["java_tools/src/tools/one_version/duplicate_class_collector.h"], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + deps = [ + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/strings", + ], +) + +cc_library( + name = "allowlist", + srcs = ["java_tools/src/tools/one_version/allowlist.cc"], + hdrs = ["java_tools/src/tools/one_version/allowlist.h"], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + deps = [ + ":duplicate_class_collector", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/container:flat_hash_set", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + ], +) + +cc_library( + name = "one_version", + srcs = ["java_tools/src/tools/one_version/one_version.cc"], + hdrs = ["java_tools/src/tools/one_version/one_version.h"], + copts = SUPRESSED_WARNINGS, + strip_include_prefix = "java_tools", + deps = [ + ":allowlist", + ":duplicate_class_collector", + ":input_jar", + "@com_google_absl//absl/log:die_if_null", + "@com_google_absl//absl/memory", + "@com_google_absl//absl/strings", + ], +) From dded932c1f4a495f21845f1f6252545521b1d1f3 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 8 Nov 2024 02:41:16 -0800 Subject: [PATCH 074/465] Release `rules_java` `v8.3.1` PiperOrigin-RevId: 694422564 Change-Id: I10ad35659a1c822b335342227f0597525ea1aa65 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index ee658f60..3147a975 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.3.0", + version = "8.3.1", bazel_compatibility = [">=7.3.2"], compatibility_level = 1, ) From 20fc864b2962a7018ac5c11c119a2865ee0f604e Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 8 Nov 2024 10:49:22 -0800 Subject: [PATCH 075/465] Add deprecation message to java_proto_library and java_lite_proto_library rules in rules_java. PiperOrigin-RevId: 694561296 Change-Id: I99e991cf03c33bbc2e6b5b0a4f89ee784786ec99 --- java/defs.bzl | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/java/defs.bzl b/java/defs.bzl index f5b4de86..da1d6af8 100644 --- a/java/defs.bzl +++ b/java/defs.bzl @@ -43,8 +43,17 @@ java_package_configuration = _java_package_configuration # Proto rules # Deprecated: don't use java proto libraries from here -java_proto_library = _java_proto_library -java_lite_proto_library = _java_lite_proto_library +def java_proto_library(**kwargs): + if "deprecation" not in kwargs: + _java_proto_library(deprecation = "Use java_proto_library from com_google_protobuf", **kwargs) + else: + _java_proto_library(**kwargs) + +def java_lite_proto_library(**kwargs): + if "deprecation" not in kwargs: + _java_lite_proto_library(deprecation = "Use java_lite_proto_library from com_google_protobuf", **kwargs) + else: + _java_lite_proto_library(**kwargs) # Modules and providers From db85b7f5557d4711d5090879413ec33e551bd582 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 11 Nov 2024 04:21:43 -0800 Subject: [PATCH 076/465] Release `rules_java` `v8.3.2` - Update skylib dep for WORKSPACE - Lower the minimim Bazel compatibility version to `6.3.0` PiperOrigin-RevId: 695281310 Change-Id: Ib131bfe0b651e1da707a040bd66f981f6416f4be --- .bazelci/presubmit.yml | 8 ++++---- MODULE.bazel | 4 ++-- WORKSPACE | 6 +++--- java/repositories.bzl | 6 +++--- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 8971a404..78e1d50e 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -85,12 +85,12 @@ tasks: # Bazel 6.x ubuntu2004_bazel6: name: "Bazel 6.x" - bazel: 6.5.0 + bazel: 6.3.0 platform: ubuntu2004 build_targets: *build_targets_bazel6 ubuntu2004_integration_bazel6: name: "Bazel 6.x Integration" - bazel: "6.5.0" + bazel: 6.3.0 platform: ubuntu2004 working_directory: "test/repo" shell_commands: @@ -101,11 +101,11 @@ tasks: - "-//:MyTest" macos_bazel6: name: "Bazel 6.x" - bazel: 6.5.0 + bazel: 6.3.0 platform: macos build_targets: *build_targets_bazel6 windows_bazel6: name: "Bazel 6.x" - bazel: 6.5.0 + bazel: 6.3.0 platform: windows build_targets: *build_targets_bazel6 diff --git a/MODULE.bazel b/MODULE.bazel index 3147a975..77f7bb58 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,7 +1,7 @@ module( name = "rules_java", - version = "8.3.1", - bazel_compatibility = [">=7.3.2"], + version = "8.3.2", + bazel_compatibility = [">=6.3.0"], compatibility_level = 1, ) diff --git a/WORKSPACE b/WORKSPACE index 7f4e8571..cbe4e809 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -4,10 +4,10 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "bazel_skylib", - sha256 = "9f38886a40548c6e96c106b752f242130ee11aaa068a56ba7e56f4511f33e4f2", + sha256 = "bc283cdfcd526a52c3201279cda4bc298652efa898b10b4db0837dc51652756f", urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.6.1/bazel-skylib-1.6.1.tar.gz", - "https://github.com/bazelbuild/bazel-skylib/releases/download/1.6.1/bazel-skylib-1.6.1.tar.gz", + "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", + "https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", ], ) diff --git a/java/repositories.bzl b/java/repositories.bzl index 2da0abef..31862112 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -384,10 +384,10 @@ def bazel_skylib_repo(): maybe( http_archive, name = "bazel_skylib", - sha256 = "f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728", + sha256 = "bc283cdfcd526a52c3201279cda4bc298652efa898b10b4db0837dc51652756f", urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz", - "https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz", + "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", + "https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", ], ) From 80de6ea6ca9fd0aec52ee9c3dfc1cb336682231d Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 13 Nov 2024 01:36:47 -0800 Subject: [PATCH 077/465] Add CI for testing rules_java with WORKSPACE only (no bzlmod) PiperOrigin-RevId: 696033105 Change-Id: I01aeb15fe709244c9f2ea1200a23f1884f044fd5 --- .bazelci/presubmit.yml | 39 ++++++++++++++++++++++++++++++++++++++- WORKSPACE | 4 ++++ java/repositories.bzl | 12 +++++++++--- test/repo/WORKSPACE | 13 +++++++++++++ 4 files changed, 64 insertions(+), 4 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 78e1d50e..be62c01f 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -44,6 +44,24 @@ tasks: - "@rules_java//java/..." test_targets: - "//:MyTest" + ubuntu2004_integration_workspace: + name: "Bazel 7.x Integration (WORKSPACE)" + bazel: "7.4.0" + platform: ubuntu2004 + working_directory: "test/repo" + shell_commands: + - sh setup.sh + build_targets: + - "//..." + - "//:bin_deploy.jar" + build_flags: + - "--noenable_bzlmod" + - "--enable_workspace" + test_targets: + - "//:MyTest" + test_flags: + - "--noenable_bzlmod" + - "--enable_workspace" macos: name: "Bazel 7.x" bazel: "7.4.0" @@ -71,6 +89,24 @@ tasks: - "@rules_java//java/..." test_targets: - "//:MyTest" + ubuntu2004_integration_head_workspace: + name: "Bazel@HEAD Integration (WORKSPACE)" + bazel: "last_green" + platform: ubuntu2004 + working_directory: "test/repo" + shell_commands: + - sh setup.sh + build_targets: + - "//..." + - "//:bin_deploy.jar" + build_flags: + - "--noenable_bzlmod" + - "--enable_workspace" + test_targets: + - "//:MyTest" + test_flags: + - "--noenable_bzlmod" + - "--enable_workspace" macos_head: name: "Bazel@HEAD" bazel: last_green @@ -98,7 +134,8 @@ tasks: build_targets: - "//..." - "//:bin_deploy.jar" - - "-//:MyTest" + test_targets: + - "//:MyTest" macos_bazel6: name: "Bazel 6.x" bazel: 6.3.0 diff --git a/WORKSPACE b/WORKSPACE index cbe4e809..49422df8 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -41,6 +41,10 @@ load("//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchain rules_java_dependencies() +load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_bazel_features") # buildifier: disable=bzl-visibility + +proto_bazel_features(name = "proto_bazel_features") + rules_java_toolchains() load("@stardoc//:setup.bzl", "stardoc_repositories") diff --git a/java/repositories.bzl b/java/repositories.bzl index 31862112..60f94ef6 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -366,9 +366,9 @@ def protobuf_repo(): maybe( http_archive, name = "com_google_protobuf", - sha256 = "da288bf1daa6c04d03a9051781caa52aceb9163586bff9aa6cfb12f69b9395aa", - strip_prefix = "protobuf-27.0", - url = "https://github.com/protocolbuffers/protobuf/releases/download/v27.0/protobuf-27.0.tar.gz", + sha256 = "ce5d00b78450a0ca400bf360ac00c0d599cc225f049d986a27e9a4e396c5a84a", + strip_prefix = "protobuf-29.0-rc2", + url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.0-rc2/protobuf-29.0-rc2.tar.gz", ) def rules_cc_repo(): @@ -439,23 +439,29 @@ load("@rules_java//java/bazel/rules:bazel_java_import.bzl", _java_import = "java load("@rules_java//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") # copybara-use-repo-external-label load("@rules_java//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") # copybara-use-repo-external-label load("@rules_java//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") # copybara-use-repo-external-label +load("@rules_java//java:http_jar.bzl", _http_jar = "http_jar") # copybara-use-repo-external-label java_binary = _java_binary java_import = _java_import java_library = _java_library java_plugin = _java_plugin java_test = _java_test + +http_jar = _http_jar """, ) else: rctx.file( "proxy.bzl", """ +load("@bazel_tools//tools/build_defs/repo:http.bzl", _http_jar = "http_jar") java_binary = native.java_binary java_import = native.java_import java_library = native.java_library java_plugin = native.java_plugin java_test = native.java_test + +http_jar = _http_jar """, ) diff --git a/test/repo/WORKSPACE b/test/repo/WORKSPACE index c9614443..c4f22a68 100644 --- a/test/repo/WORKSPACE +++ b/test/repo/WORKSPACE @@ -1,3 +1,5 @@ +workspace(name = "integration_test_repo") + local_repository( name = "rules_java", path = "../../", @@ -7,4 +9,15 @@ load("@rules_java//java:repositories.bzl", "rules_java_dependencies", "rules_jav rules_java_dependencies() +load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_bazel_features") # buildifier: disable=bzl-visibility + +proto_bazel_features(name = "proto_bazel_features") + rules_java_toolchains() + +load("@compatibility_proxy//:proxy.bzl", "http_jar") + +http_jar( + name = "my_jar", + urls = ["file:///tmp/my_jar.jar"], +) From 865f285e07e4baae912a51182153b9fa8723cb13 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Fri, 15 Nov 2024 02:42:07 -0800 Subject: [PATCH 078/465] Use hermetic Java runtimes Copybara Import from https://github.com/bazelbuild/rules_java/pull/241 BEGIN_PUBLIC Use hermetic Java runtimes (#241) Makes it easier to contribute to the project while ensuring that it remains compatible with Java 8. Closes #241 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/241 from fmeum:hermetic-ci 1cd4a4d8bd880889b7fe8b711abda5bebed69024 PiperOrigin-RevId: 696820025 Change-Id: I166118e9814b1e0bde93c95e4e9ff9a6e05a49c4 --- .bazelrc | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.bazelrc b/.bazelrc index 5ef382d3..526b36d8 100644 --- a/.bazelrc +++ b/.bazelrc @@ -1 +1,10 @@ common --incompatible_disallow_empty_glob + +# Use hermetic JDKs for testing and ensure compatibliity with Java 8. +common --java_language_version=8 +common --java_runtime_version=remotejdk_8 +common --tool_java_language_version=8 +common --tool_java_runtime_version=remotejdk_8 + +# Hide Java 8 deprecation warnings. +common --javacopt=-Xlint:-options From 6bb53061432c59b6ea043cbebf9deae8c8bee4fd Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Fri, 15 Nov 2024 14:01:19 -0800 Subject: [PATCH 079/465] Copy over runfiles library from Bazel Copybara Import from https://github.com/bazelbuild/rules_java/pull/239 BEGIN_PUBLIC Copy over runfiles library from Bazel (#239) The runfiles library can be maintained independently of Bazel releases and `bazel_tools` can refer to it via an alias. Also set flags to build and test with a hermetic JDK 8 to ensure compatibility with that version. Closes #239 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/239 from fmeum:runfiles 6428328ba2bb206a281e7c02e80827f638216d96 PiperOrigin-RevId: 696993940 Change-Id: Id2ee9f4f2d15a1063c4db1e913b375ba40b8e439 --- .gitignore | 2 + MODULE.bazel | 9 +- WORKSPACE | 4 + java/runfiles/BUILD.bazel | 5 + .../build/runfiles/AutoBazelRepository.java | 29 + .../AutoBazelRepositoryProcessor.java | 121 ++++ .../devtools/build/runfiles/BUILD.bazel | 23 + .../devtools/build/runfiles/Runfiles.java | 582 +++++++++++++++++ .../google/devtools/build/runfiles/Util.java | 49 ++ test/repositories.bzl | 23 + .../devtools/build/runfiles/BUILD.bazel | 34 + .../devtools/build/runfiles/RunfilesTest.java | 601 ++++++++++++++++++ .../devtools/build/runfiles/UtilTest.java | 47 ++ 13 files changed, 1526 insertions(+), 3 deletions(-) create mode 100644 java/runfiles/BUILD.bazel create mode 100644 java/runfiles/src/main/java/com/google/devtools/build/runfiles/AutoBazelRepository.java create mode 100644 java/runfiles/src/main/java/com/google/devtools/build/runfiles/AutoBazelRepositoryProcessor.java create mode 100644 java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD.bazel create mode 100644 java/runfiles/src/main/java/com/google/devtools/build/runfiles/Runfiles.java create mode 100644 java/runfiles/src/main/java/com/google/devtools/build/runfiles/Util.java create mode 100644 test/repositories.bzl create mode 100644 test/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel create mode 100644 test/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java create mode 100644 test/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java diff --git a/.gitignore b/.gitignore index ef436251..86e15abe 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,5 @@ # Ignore jekyll build output. /production /.sass-cache +# Ignore MODULE.bazel.lock as this is a library project. +MODULE.bazel.lock diff --git a/MODULE.bazel b/MODULE.bazel index 77f7bb58..ec262421 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -89,11 +89,14 @@ REMOTE_JDK_REPOS = [(("remote_jdk" if version == "8" else "remotejdk") + version [register_toolchains("@" + name + "_toolchain_config_repo//:all") for name in REMOTE_JDK_REPOS] +# Compatibility layer +compat = use_extension("//java:extensions.bzl", "compatibility_proxy") +use_repo(compat, "compatibility_proxy") + # Dev dependencies bazel_dep(name = "rules_pkg", version = "0.9.1", dev_dependency = True) bazel_dep(name = "stardoc", version = "0.7.1", dev_dependency = True) bazel_dep(name = "rules_shell", version = "0.2.0", dev_dependency = True) -# Compatibility layer -compat = use_extension("//java:extensions.bzl", "compatibility_proxy") -use_repo(compat, "compatibility_proxy") +test_repositories = use_extension("//test:repositories.bzl", "test_repositories_ext", dev_dependency = True) +use_repo(test_repositories, "guava", "truth") diff --git a/WORKSPACE b/WORKSPACE index 49422df8..f58f31c2 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -50,3 +50,7 @@ rules_java_toolchains() load("@stardoc//:setup.bzl", "stardoc_repositories") stardoc_repositories() + +load("//test:repositories.bzl", "test_repositories") + +test_repositories() diff --git a/java/runfiles/BUILD.bazel b/java/runfiles/BUILD.bazel new file mode 100644 index 00000000..792e45f7 --- /dev/null +++ b/java/runfiles/BUILD.bazel @@ -0,0 +1,5 @@ +alias( + name = "runfiles", + actual = "//java/runfiles/src/main/java/com/google/devtools/build/runfiles", + visibility = ["//visibility:public"], +) diff --git a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/AutoBazelRepository.java b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/AutoBazelRepository.java new file mode 100644 index 00000000..6dc53300 --- /dev/null +++ b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/AutoBazelRepository.java @@ -0,0 +1,29 @@ +// 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. + +package com.google.devtools.build.runfiles; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotating a class {@code Fooer} with this annotation generates a class {@code + * AutoBazelRepository_Fooer} defining a {@link String} constant {@code NAME} containing the + * canonical name of the repository containing the Bazel target that compiled the annotated class. + */ +@Retention(RetentionPolicy.SOURCE) +@Target(ElementType.TYPE) +public @interface AutoBazelRepository {} diff --git a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/AutoBazelRepositoryProcessor.java b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/AutoBazelRepositoryProcessor.java new file mode 100644 index 00000000..2b0ce9d2 --- /dev/null +++ b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/AutoBazelRepositoryProcessor.java @@ -0,0 +1,121 @@ +// 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. + +package com.google.devtools.build.runfiles; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.Set; +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedOptions; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import javax.tools.Diagnostic.Kind; + +/** Processor for {@link AutoBazelRepository}. */ +@SupportedAnnotationTypes("com.google.devtools.build.runfiles.AutoBazelRepository") +@SupportedOptions(AutoBazelRepositoryProcessor.BAZEL_REPOSITORY_OPTION) +public final class AutoBazelRepositoryProcessor extends AbstractProcessor { + + static final String BAZEL_REPOSITORY_OPTION = "bazel.repository"; + + @Override + public SourceVersion getSupportedSourceVersion() { + return SourceVersion.latestSupported(); + } + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + annotations.stream() + .flatMap(element -> roundEnv.getElementsAnnotatedWith(element).stream()) + .map(element -> (TypeElement) element) + .forEach(this::emitClass); + return false; + } + + private void emitClass(TypeElement annotatedClass) { + // This option is always provided by the Java rule implementations. + if (!processingEnv.getOptions().containsKey(BAZEL_REPOSITORY_OPTION)) { + processingEnv + .getMessager() + .printMessage( + Kind.ERROR, + String.format( + "The %1$s annotation processor option is not set. To use this annotation" + + " processor, provide the canonical repository name of the current target as" + + " the value of the -A%1$s flag.", + BAZEL_REPOSITORY_OPTION), + annotatedClass); + return; + } + String repositoryName = processingEnv.getOptions().get(BAZEL_REPOSITORY_OPTION); + if (repositoryName == null) { + // javac translates '-Abazel.repository=' into a null value. + // https://github.com/openjdk/jdk/blob/7a49c9baa1d4ad7df90e7ca626ec48ba76881822/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/JavacProcessingEnvironment.java#L651 + repositoryName = ""; + } + + // For a nested class Outer.Middle.Inner, generate a class with simple name + // AutoBazelRepository_Outer_Middle_Inner. + // Note: There can be collisions when local classes are involved, but since the definition of a + // class depends only on the containing Bazel target, this does not result in ambiguity. + Deque classNameSegments = new ArrayDeque<>(); + Element element = annotatedClass; + while (element instanceof TypeElement) { + classNameSegments.addFirst(element.getSimpleName().toString()); + element = element.getEnclosingElement(); + } + classNameSegments.addFirst("AutoBazelRepository"); + String generatedClassSimpleName = String.join("_", classNameSegments); + + String generatedClassPackage = + processingEnv.getElementUtils().getPackageOf(annotatedClass).getQualifiedName().toString(); + + String generatedClassName = + generatedClassPackage.isEmpty() + ? generatedClassSimpleName + : generatedClassPackage + "." + generatedClassSimpleName; + + try (PrintWriter out = + new PrintWriter( + processingEnv.getFiler().createSourceFile(generatedClassName).openWriter())) { + if (!generatedClassPackage.isEmpty()) { + // This annotation may exist on a class which is at the root package + out.printf("package %s;\n", generatedClassPackage); + } + out.printf("\n"); + out.printf("class %s {\n", generatedClassSimpleName); + out.printf(" /**\n"); + out.printf(" * The canonical name of the repository containing the Bazel target that\n"); + out.printf(" * compiled {@link %s}.\n", annotatedClass.getQualifiedName().toString()); + out.printf(" */\n"); + out.printf(" static final String NAME = \"%s\";\n", repositoryName); + out.printf("\n"); + out.printf(" private %s() {}\n", generatedClassSimpleName); + out.printf("}\n"); + } catch (IOException e) { + processingEnv + .getMessager() + .printMessage( + Kind.ERROR, + String.format("Failed to generate %s: %s", generatedClassName, e.getMessage()), + annotatedClass); + } + } +} diff --git a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD.bazel b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD.bazel new file mode 100644 index 00000000..fd351b73 --- /dev/null +++ b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD.bazel @@ -0,0 +1,23 @@ +load("@rules_java//java:defs.bzl", "java_library", "java_plugin") + +java_library( + name = "runfiles", + srcs = [ + "Runfiles.java", + "Util.java", + ], + exported_plugins = [":auto_bazel_repository_processor"], + visibility = ["//java/runfiles:__pkg__"], + exports = [":auto_bazel_repository"], +) + +java_library( + name = "auto_bazel_repository", + srcs = ["AutoBazelRepository.java"], +) + +java_plugin( + name = "auto_bazel_repository_processor", + srcs = ["AutoBazelRepositoryProcessor.java"], + processor_class = "com.google.devtools.build.runfiles.AutoBazelRepositoryProcessor", +) diff --git a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Runfiles.java b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Runfiles.java new file mode 100644 index 00000000..bec2091a --- /dev/null +++ b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Runfiles.java @@ -0,0 +1,582 @@ +// Copyright 2018 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. + +package com.google.devtools.build.runfiles; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.ref.SoftReference; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * Runfiles lookup library for Bazel-built Java binaries and tests. + * + *

USAGE: + * + *

1. Depend on this runfiles library from your build rule: + * + *

+ *   java_binary(
+ *       name = "my_binary",
+ *       ...
+ *       deps = ["@rules_java//java/runfiles"],
+ *   )
+ * 
+ * + *

2. Import the runfiles library. + * + *

+ *   import com.google.devtools.build.runfiles.Runfiles;
+ * 
+ * + *

3. Create a {@link Runfiles.Preloaded} object: + * + *

+ *   public void myFunction() {
+ *     Runfiles.Preloaded runfiles = Runfiles.preload();
+ *     ...
+ * 
+ * + *

4. To look up a runfile, use either of the following approaches: + * + *

4a. Annotate the class from which runfiles should be looked up with {@link + * AutoBazelRepository} and obtain the name of the Bazel repository containing the class from a + * constant generated by this annotation: + * + *

+ *   import com.google.devtools.build.runfiles.AutoBazelRepository;
+ *   @AutoBazelRepository
+ *   public class MyClass {
+ *     public void myFunction() {
+ *       Runfiles.Preloaded runfiles = Runfiles.preload();
+ *       String path = runfiles.withSourceRepository(AutoBazelRepository_MyClass.NAME)
+ *                             .rlocation("my_workspace/path/to/my/data.txt");
+ *       ...
+ *
+ * 
+ * + *

4b. Let Bazel compute the path passed to rlocation and pass it into a java_binary + * via an argument or an environment variable: + * + *

+ *   java_binary(
+ *       name = "my_binary",
+ *       srcs = ["MyClass.java"],
+ *       data = ["@my_workspace//path/to/my:data.txt"],
+ *       env = {"MY_RUNFILE": "$(rlocationpath @my_workspace//path/to/my:data.txt)"},
+ *   )
+ * 
+ * + *
+ *   public class MyClass {
+ *     public void myFunction() {
+ *       Runfiles.Preloaded runfiles = Runfiles.preload();
+ *       String path = runfiles.unmapped().rlocation(System.getenv("MY_RUNFILE"));
+ *       ...
+ *
+ * 
+ * + * For more details on why it is required to pass in the current repository name, see {@see + * https://bazel.build/build/bzlmod#repository-names}. + * + *

Subprocesses

+ * + *

If you want to start subprocesses that also need runfiles, you need to set the right + * environment variables for them: + * + *

+ *   String path = r.rlocation("path/to/binary");
+ *   ProcessBuilder pb = new ProcessBuilder(path);
+ *   pb.environment().putAll(r.getEnvVars());
+ *   ...
+ *   Process p = pb.start();
+ * 
+ * + *

{@link Runfiles.Preloaded} vs. {@link Runfiles}

+ * + *

Instances of {@link Runfiles.Preloaded} are meant to be stored and passed around to other + * components that need to access runfiles. They are created by calling {@link Runfiles#preload()} + * {@link Runfiles#preload(java.util.Map)} and immutably encapsulate all data required to look up + * runfiles with the repository mapping of any Bazel repository specified at a later time. + * + *

Creating {@link Runfiles.Preloaded} instances can be costly, so applications should try to + * create as few instances as possible. {@link Runfiles#preload()}, but not {@link + * Runfiles#preload(java.util.Map)}, returns a single global, softly cached instance of {@link + * Runfiles.Preloaded} that is constructed based on the JVM's environment variables. + * + *

Instance of {@link Runfiles} are only meant to be used by code located in a single Bazel + * repository and should not be passed around. They are created by calling {@link + * Runfiles.Preloaded#withSourceRepository(String)} or {@link Runfiles.Preloaded#unmapped()} and in + * addition to the data in {@link Runfiles.Preloaded} also fix a source repository relative to which + * apparent repository names are resolved. + * + *

Creating {@link Runfiles.Preloaded} instances is cheap. + */ +public final class Runfiles { + + /** + * A class that encapsulates all data required to look up runfiles relative to any Bazel + * repository fixed at a later time. + * + *

This class is immutable. + */ + public abstract static class Preloaded { + + /** See {@link com.google.devtools.build.lib.analysis.RepoMappingManifestAction.Entry}. */ + static class RepoMappingKey { + + public final String sourceRepo; + public final String targetRepoApparentName; + + public RepoMappingKey(String sourceRepo, String targetRepoApparentName) { + this.sourceRepo = sourceRepo; + this.targetRepoApparentName = targetRepoApparentName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || !(o instanceof RepoMappingKey)) { + return false; + } + RepoMappingKey that = (RepoMappingKey) o; + return sourceRepo.equals(that.sourceRepo) + && targetRepoApparentName.equals(that.targetRepoApparentName); + } + + @Override + public int hashCode() { + return Objects.hash(sourceRepo, targetRepoApparentName); + } + } + + /** + * Returns a {@link Runfiles} instance that uses the provided source repository's repository + * mapping to translate apparent into canonical repository names. + * + *

{@see https://bazel.build/build/bzlmod#repository-names} + * + * @param sourceRepository the canonical name of the Bazel repository relative to which apparent + * repository names should be resolved. Should generally coincide with the Bazel repository + * that contains the caller of this method, which can be obtained via {@link + * AutoBazelRepository}. + * @return a {@link Runfiles} instance that looks up runfiles relative to the provided source + * repository and shares all other data with this {@link Runfiles.Preloaded} instance. + */ + public final Runfiles withSourceRepository(String sourceRepository) { + Util.checkArgument(sourceRepository != null); + return new Runfiles(this, sourceRepository); + } + + /** + * Returns a {@link Runfiles} instance backed by the preloaded runfiles data that can be used to + * look up runfiles paths with canonical repository names only. + * + * @return a {@link Runfiles} instance that can only look up paths with canonical repository + * names and shared all data with this {@link Runfiles.Preloaded} instance. + */ + public final Runfiles unmapped() { + return new Runfiles(this, null); + } + + protected abstract Map getEnvVars(); + + protected abstract String rlocationChecked(String path); + + protected abstract Map getRepoMapping(); + + // Private constructor, so only nested classes may extend it. + private Preloaded() {} + } + + private static final String MAIN_REPOSITORY = ""; + + private static SoftReference defaultInstance = new SoftReference<>(null); + + private final Preloaded preloadedRunfiles; + private final String sourceRepository; + + private Runfiles(Preloaded preloadedRunfiles, String sourceRepository) { + this.preloadedRunfiles = preloadedRunfiles; + this.sourceRepository = sourceRepository; + } + + /** + * Returns the softly cached global {@link Runfiles.Preloaded} instance, creating it if needed. + * + *

This method passes the JVM's environment variable map to {@link #create(java.util.Map)}. + */ + public static synchronized Preloaded preload() throws IOException { + Preloaded instance = defaultInstance.get(); + if (instance != null) { + return instance; + } + instance = preload(System.getenv()); + defaultInstance = new SoftReference<>(instance); + return instance; + } + + /** + * Returns a new {@link Runfiles.Preloaded} instance. + * + *

The returned object is either: + * + *

    + *
  • manifest-based, meaning it looks up runfile paths from a manifest file, or + *
  • directory-based, meaning it looks up runfile paths under a given directory path + *
+ * + *

If {@code env} contains "RUNFILES_MANIFEST_ONLY" with value "1", this method returns a + * manifest-based implementation. The manifest's path is defined by the "RUNFILES_MANIFEST_FILE" + * key's value in {@code env}. + * + *

Otherwise this method returns a directory-based implementation. The directory's path is + * defined by the value in {@code env} under the "RUNFILES_DIR" key, or if absent, then under the + * "JAVA_RUNFILES" key. + * + *

Note about performance: the manifest-based implementation eagerly reads and caches the whole + * manifest file upon instantiation. + * + * @throws java.io.IOException if RUNFILES_MANIFEST_ONLY=1 is in {@code env} but there's no + * "RUNFILES_MANIFEST_FILE", "RUNFILES_DIR", or "JAVA_RUNFILES" key in {@code env} or their + * values are empty, or some IO error occurs + */ + public static Preloaded preload(Map env) throws IOException { + if (isManifestOnly(env)) { + // On Windows, Bazel sets RUNFILES_MANIFEST_ONLY=1. + // On every platform, Bazel also sets RUNFILES_MANIFEST_FILE, but on Linux and macOS it's + // faster to use RUNFILES_DIR. + return new ManifestBased(getManifestPath(env)); + } else { + return new DirectoryBased(getRunfilesDir(env)); + } + } + + /** + * Returns a new {@link Runfiles} instance. + * + *

This method passes the JVM's environment variable map to {@link #create(java.util.Map)}. + * + * @deprecated Use {@link #preload()} instead. With {@code --enable_bzlmod}, this function does + * not work correctly. + */ + @Deprecated + public static Runfiles create() throws IOException { + return preload().withSourceRepository(MAIN_REPOSITORY); + } + + /** + * Returns a new {@link Runfiles} instance. + * + *

The returned object is either: + * + *

    + *
  • manifest-based, meaning it looks up runfile paths from a manifest file, or + *
  • directory-based, meaning it looks up runfile paths under a given directory path + *
+ * + *

If {@code env} contains "RUNFILES_MANIFEST_ONLY" with value "1", this method returns a + * manifest-based implementation. The manifest's path is defined by the "RUNFILES_MANIFEST_FILE" + * key's value in {@code env}. + * + *

Otherwise this method returns a directory-based implementation. The directory's path is + * defined by the value in {@code env} under the "RUNFILES_DIR" key, or if absent, then under the + * "JAVA_RUNFILES" key. + * + *

Note about performance: the manifest-based implementation eagerly reads and caches the whole + * manifest file upon instantiation. + * + * @throws IOException if RUNFILES_MANIFEST_ONLY=1 is in {@code env} but there's no + * "RUNFILES_MANIFEST_FILE", "RUNFILES_DIR", or "JAVA_RUNFILES" key in {@code env} or their + * values are empty, or some IO error occurs + * @deprecated Use {@link #preload(java.util.Map)} instead. With {@code --enable_bzlmod}, this + * function does not work correctly. + */ + @Deprecated + public static Runfiles create(Map env) throws IOException { + return preload(env).withSourceRepository(MAIN_REPOSITORY); + } + + /** + * Returns the runtime path of a runfile (a Bazel-built binary's/test's data-dependency). + * + *

The returned path may not be valid. The caller should check the path's validity and that the + * path exists. + * + *

The function may return null. In that case the caller can be sure that the rule does not + * know about this data-dependency. + * + * @param path runfiles-root-relative path of the runfile + * @throws IllegalArgumentException if {@code path} fails validation, for example if it's null or + * empty, or not normalized (contains "./", "../", or "//") + */ + public String rlocation(String path) { + Util.checkArgument(path != null); + Util.checkArgument(!path.isEmpty()); + Util.checkArgument( + !path.startsWith("../") + && !path.contains("/..") + && !path.startsWith("./") + && !path.contains("/./") + && !path.endsWith("/.") + && !path.contains("//"), + "path is not normalized: \"%s\"", + path); + Util.checkArgument( + !path.startsWith("\\"), "path is absolute without a drive letter: \"%s\"", path); + if (new File(path).isAbsolute()) { + return path; + } + + if (sourceRepository == null) { + return preloadedRunfiles.rlocationChecked(path); + } + String[] apparentTargetAndRemainder = path.split("/", 2); + if (apparentTargetAndRemainder.length < 2) { + return preloadedRunfiles.rlocationChecked(path); + } + String targetCanonical = getCanonicalRepositoryName(apparentTargetAndRemainder[0]); + return preloadedRunfiles.rlocationChecked( + targetCanonical + "/" + apparentTargetAndRemainder[1]); + } + + /** + * Returns environment variables for subprocesses. + * + *

The caller should add the returned key-value pairs to the environment of subprocesses in + * case those subprocesses are also Bazel-built binaries that need to use runfiles. + */ + public Map getEnvVars() { + return preloadedRunfiles.getEnvVars(); + } + + String getCanonicalRepositoryName(String apparentRepositoryName) { + return preloadedRunfiles + .getRepoMapping() + .getOrDefault( + new Preloaded.RepoMappingKey(sourceRepository, apparentRepositoryName), + apparentRepositoryName); + } + + /** Returns true if the platform supports runfiles only via manifests. */ + private static boolean isManifestOnly(Map env) { + return "1".equals(env.get("RUNFILES_MANIFEST_ONLY")); + } + + private static String getManifestPath(Map env) throws IOException { + String value = env.get("RUNFILES_MANIFEST_FILE"); + if (Util.isNullOrEmpty(value)) { + throw new IOException( + "Cannot load runfiles manifest: $RUNFILES_MANIFEST_ONLY is 1 but" + + " $RUNFILES_MANIFEST_FILE is empty or undefined"); + } + return value; + } + + private static String getRunfilesDir(Map env) throws IOException { + String value = env.get("RUNFILES_DIR"); + if (Util.isNullOrEmpty(value)) { + value = env.get("JAVA_RUNFILES"); + } + if (Util.isNullOrEmpty(value)) { + throw new IOException( + "Cannot find runfiles: $RUNFILES_DIR and $JAVA_RUNFILES are both unset or empty"); + } + return value; + } + + private static Map loadRepositoryMapping(String path) + throws IOException { + if (path == null || !new File(path).exists()) { + return Collections.emptyMap(); + } + + try (BufferedReader r = + new BufferedReader( + new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8))) { + return Collections.unmodifiableMap( + r.lines() + .filter(line -> !line.isEmpty()) + .map( + line -> { + String[] split = line.split(","); + if (split.length != 3) { + throw new IllegalArgumentException( + "Invalid line in repository mapping: '" + line + "'"); + } + return split; + }) + .collect( + Collectors.toMap( + split -> new Preloaded.RepoMappingKey(split[0], split[1]), + split -> split[2]))); + } + } + + /** {@link Runfiles} implementation that parses a runfiles-manifest file to look up runfiles. */ + private static final class ManifestBased extends Preloaded { + + private final Map runfiles; + private final String manifestPath; + private final Map repoMapping; + + ManifestBased(String manifestPath) throws IOException { + Util.checkArgument(manifestPath != null); + Util.checkArgument(!manifestPath.isEmpty()); + this.manifestPath = manifestPath; + this.runfiles = loadRunfiles(manifestPath); + this.repoMapping = loadRepositoryMapping(rlocationChecked("_repo_mapping")); + } + + @Override + protected String rlocationChecked(String path) { + String exactMatch = runfiles.get(path); + if (exactMatch != null) { + return exactMatch; + } + // If path references a runfile that lies under a directory that itself is a runfile, then + // only the directory is listed in the manifest. Look up all prefixes of path in the manifest + // and append the relative path from the prefix if there is a match. + int prefixEnd = path.length(); + while ((prefixEnd = path.lastIndexOf('/', prefixEnd - 1)) != -1) { + String prefixMatch = runfiles.get(path.substring(0, prefixEnd)); + if (prefixMatch != null) { + return prefixMatch + '/' + path.substring(prefixEnd + 1); + } + } + return null; + } + + @Override + protected Map getEnvVars() { + HashMap result = new HashMap<>(4); + result.put("RUNFILES_MANIFEST_ONLY", "1"); + result.put("RUNFILES_MANIFEST_FILE", manifestPath); + String runfilesDir = findRunfilesDir(manifestPath); + result.put("RUNFILES_DIR", runfilesDir); + // TODO(laszlocsomor): remove JAVA_RUNFILES once the Java launcher can pick up RUNFILES_DIR. + result.put("JAVA_RUNFILES", runfilesDir); + return result; + } + + @Override + protected Map getRepoMapping() { + return repoMapping; + } + + private static Map loadRunfiles(String path) throws IOException { + HashMap result = new HashMap<>(); + try (BufferedReader r = + new BufferedReader( + new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8))) { + String line; + while ((line = r.readLine()) != null) { + String runfile; + String realPath; + if (line.startsWith(" ")) { + // In lines starting with a space, the runfile path contains spaces and backslashes + // escaped with a backslash. The real path is the rest of the line after the first + // unescaped space. + int firstSpace = line.indexOf(' ', 1); + if (firstSpace == -1) { + throw new IOException( + "Invalid runfiles manifest line, expected at least one space after the leading" + + " space: " + + line); + } + runfile = + line.substring(1, firstSpace) + .replace("\\s", " ") + .replace("\\n", "\n") + .replace("\\b", "\\"); + realPath = line.substring(firstSpace + 1).replace("\\n", "\n").replace("\\b", "\\"); + } else { + int firstSpace = line.indexOf(' '); + if (firstSpace == -1) { + throw new IOException( + "Invalid runfiles manifest line, expected at least one space: " + line); + } + runfile = line.substring(0, firstSpace); + realPath = line.substring(firstSpace + 1); + } + result.put(runfile, realPath); + } + } + return Collections.unmodifiableMap(result); + } + + private static String findRunfilesDir(String manifest) { + if (manifest.endsWith("/MANIFEST") + || manifest.endsWith("\\MANIFEST") + || manifest.endsWith(".runfiles_manifest")) { + String path = manifest.substring(0, manifest.length() - 9); + if (new File(path).isDirectory()) { + return path; + } + } + return ""; + } + } + + /** {@link Runfiles} implementation that appends runfiles paths to the runfiles root. */ + private static final class DirectoryBased extends Preloaded { + + private final String runfilesRoot; + private final Map repoMapping; + + DirectoryBased(String runfilesDir) throws IOException { + Util.checkArgument(!Util.isNullOrEmpty(runfilesDir)); + Util.checkArgument(new File(runfilesDir).isDirectory()); + this.runfilesRoot = runfilesDir; + this.repoMapping = loadRepositoryMapping(rlocationChecked("_repo_mapping")); + } + + @Override + protected String rlocationChecked(String path) { + return runfilesRoot + "/" + path; + } + + @Override + protected Map getRepoMapping() { + return repoMapping; + } + + @Override + protected Map getEnvVars() { + HashMap result = new HashMap<>(2); + result.put("RUNFILES_DIR", runfilesRoot); + // TODO(laszlocsomor): remove JAVA_RUNFILES once the Java launcher can pick up RUNFILES_DIR. + result.put("JAVA_RUNFILES", runfilesRoot); + return result; + } + } + + static Preloaded createManifestBasedForTesting(String manifestPath) throws IOException { + return new ManifestBased(manifestPath); + } + + static Preloaded createDirectoryBasedForTesting(String runfilesDir) throws IOException { + return new DirectoryBased(runfilesDir); + } +} diff --git a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Util.java b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Util.java new file mode 100644 index 00000000..73f0b98e --- /dev/null +++ b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Util.java @@ -0,0 +1,49 @@ +// Copyright 2018 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. + +package com.google.devtools.build.runfiles; + +/** + * Utilities for the other classes in this package. + * + *

These functions are implementations of some basic utilities in the Guava library. We + * reimplement these functions instead of depending on Guava, so that the Runfiles library has no + * third-party dependencies, thus any Java project can depend on it without the risk of pulling + * unwanted or conflicting dependencies (for example if the project already depends on Guava, or + * wishes not to depend on it at all). + */ +class Util { + private Util() {} + + /** Returns true when {@code s} is null or an empty string. */ + public static boolean isNullOrEmpty(String s) { + return s == null || s.isEmpty(); + } + + /** Throws an {@code IllegalArgumentException} if {@code condition} is false. */ + public static void checkArgument(boolean condition) { + checkArgument(condition, null, null); + } + + /** Throws an {@code IllegalArgumentException} if {@code condition} is false. */ + public static void checkArgument(boolean condition, String error, Object arg1) { + if (!condition) { + if (isNullOrEmpty(error)) { + throw new IllegalArgumentException("argument validation failed"); + } else { + throw new IllegalArgumentException(String.format(error, arg1)); + } + } + } +} diff --git a/test/repositories.bzl b/test/repositories.bzl new file mode 100644 index 00000000..5d4f568d --- /dev/null +++ b/test/repositories.bzl @@ -0,0 +1,23 @@ +"""Test dependencies for rules_java.""" + +load("@bazel_skylib//lib:modules.bzl", "modules") + +# TODO: Use http_jar from //java:http_jar.bzl once it doesn't refert to cache.bzl from @bazel_tools +# anymore, which isn't available in Bazel 6. +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") + +def test_repositories(): + http_file( + name = "guava", + url = "https://repo1.maven.org/maven2/com/google/guava/guava/33.3.1-jre/guava-33.3.1-jre.jar", + integrity = "sha256-S/Dixa+ORSXJbo/eF6T3MH+X+EePEcTI41oOMpiuTpA=", + downloaded_file_path = "guava.jar", + ) + http_file( + name = "truth", + url = "https://repo1.maven.org/maven2/com/google/truth/truth/1.4.4/truth-1.4.4.jar", + integrity = "sha256-Ushs3a3DG8hFfB4VaJ/Gt14ul84qg9i1S3ldVW1In4w=", + downloaded_file_path = "truth.jar", + ) + +test_repositories_ext = modules.as_extension(test_repositories) diff --git a/test/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel b/test/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel new file mode 100644 index 00000000..67a11ca5 --- /dev/null +++ b/test/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel @@ -0,0 +1,34 @@ +load("@rules_java//java:java_import.bzl", "java_import") +load("@rules_java//java:java_test.bzl", "java_test") + +java_test( + name = "RunfilesTest", + srcs = ["RunfilesTest.java"], + test_class = "com.google.devtools.build.runfiles.RunfilesTest", + deps = [ + ":guava", + ":truth", + "//java/runfiles", + ], +) + +java_test( + name = "UtilTest", + srcs = ["UtilTest.java"], + test_class = "com.google.devtools.build.runfiles.UtilTest", + deps = [ + ":guava", + ":truth", + "//java/runfiles", + ], +) + +java_import( + name = "guava", + jars = ["@guava//file"], +) + +java_import( + name = "truth", + jars = ["@truth//file"], +) diff --git a/test/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java b/test/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java new file mode 100644 index 00000000..035a0b52 --- /dev/null +++ b/test/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java @@ -0,0 +1,601 @@ +// Copyright 2018 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. + +package com.google.devtools.build.runfiles; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import javax.annotation.Nullable; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link Runfiles}. */ +@RunWith(JUnit4.class) +public final class RunfilesTest { + + @Rule + public TemporaryFolder tempDir = new TemporaryFolder(new File(System.getenv("TEST_TMPDIR"))); + + private static boolean isWindows() { + return File.separatorChar == '\\'; + } + + private void assertRlocationArg(Runfiles runfiles, String path, @Nullable String error) { + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, () -> runfiles.rlocation(path)); + if (error != null) { + assertThat(e).hasMessageThat().contains(error); + } + } + + @Test + public void testRlocationArgumentValidation() throws Exception { + Path dir = + Files.createTempDirectory( + FileSystems.getDefault().getPath(System.getenv("TEST_TMPDIR")), null); + + Runfiles r = Runfiles.create(ImmutableMap.of("RUNFILES_DIR", dir.toString())); + assertRlocationArg(r, null, null); + assertRlocationArg(r, "", null); + assertRlocationArg(r, "../foo", "is not normalized"); + assertRlocationArg(r, "foo/..", "is not normalized"); + assertRlocationArg(r, "foo/../bar", "is not normalized"); + assertRlocationArg(r, "./foo", "is not normalized"); + assertRlocationArg(r, "foo/.", "is not normalized"); + assertRlocationArg(r, "foo/./bar", "is not normalized"); + assertRlocationArg(r, "//foobar", "is not normalized"); + assertRlocationArg(r, "foo//", "is not normalized"); + assertRlocationArg(r, "foo//bar", "is not normalized"); + assertRlocationArg(r, "\\foo", "path is absolute without a drive letter"); + } + + @Test + public void testCreatesManifestBasedRunfiles() throws Exception { + Path mf = tempFile("foo.runfiles_manifest", ImmutableList.of("a/b c/d")); + Runfiles r = + Runfiles.create( + ImmutableMap.of( + "RUNFILES_MANIFEST_ONLY", "1", + "RUNFILES_MANIFEST_FILE", mf.toString(), + "RUNFILES_DIR", "ignored when RUNFILES_MANIFEST_ONLY=1", + "JAVA_RUNFILES", "ignored when RUNFILES_DIR has a value", + "TEST_SRCDIR", "should always be ignored")); + assertThat(r.rlocation("a/b")).isEqualTo("c/d"); + assertThat(r.rlocation("foo")).isNull(); + + if (isWindows()) { + assertThat(r.rlocation("c:/foo")).isEqualTo("c:/foo"); + assertThat(r.rlocation("c:\\foo")).isEqualTo("c:\\foo"); + } else { + assertThat(r.rlocation("/foo")).isEqualTo("/foo"); + } + } + + @Test + public void testCreatesDirectoryBasedRunfiles() throws Exception { + Path dir = + Files.createTempDirectory( + FileSystems.getDefault().getPath(System.getenv("TEST_TMPDIR")), null); + + Runfiles r = + Runfiles.create( + ImmutableMap.of( + "RUNFILES_MANIFEST_FILE", "ignored when RUNFILES_MANIFEST_ONLY is not set to 1", + "RUNFILES_DIR", dir.toString(), + "JAVA_RUNFILES", "ignored when RUNFILES_DIR has a value", + "TEST_SRCDIR", "should always be ignored")); + assertThat(r.rlocation("a/b")).endsWith("/a/b"); + assertThat(r.rlocation("foo")).endsWith("/foo"); + + r = + Runfiles.create( + ImmutableMap.of( + "RUNFILES_MANIFEST_FILE", "ignored when RUNFILES_MANIFEST_ONLY is not set to 1", + "RUNFILES_DIR", "", + "JAVA_RUNFILES", dir.toString(), + "TEST_SRCDIR", "should always be ignored")); + assertThat(r.rlocation("a/b")).endsWith("/a/b"); + assertThat(r.rlocation("foo")).endsWith("/foo"); + } + + @Test + public void testIgnoresTestSrcdirWhenJavaRunfilesIsUndefinedAndJustFails() throws Exception { + Path dir = + Files.createTempDirectory( + FileSystems.getDefault().getPath(System.getenv("TEST_TMPDIR")), null); + + Runfiles.create( + ImmutableMap.of( + "RUNFILES_DIR", dir.toString(), + "RUNFILES_MANIFEST_FILE", "ignored when RUNFILES_MANIFEST_ONLY is not set to 1", + "TEST_SRCDIR", "should always be ignored")); + + Runfiles.create( + ImmutableMap.of( + "JAVA_RUNFILES", dir.toString(), + "RUNFILES_MANIFEST_FILE", "ignored when RUNFILES_MANIFEST_ONLY is not set to 1", + "TEST_SRCDIR", "should always be ignored")); + + IOException e = + assertThrows( + IOException.class, + () -> + Runfiles.create( + ImmutableMap.of( + "RUNFILES_DIR", + "", + "JAVA_RUNFILES", + "", + "RUNFILES_MANIFEST_FILE", + "ignored when RUNFILES_MANIFEST_ONLY is not set to 1", + "TEST_SRCDIR", + "should always be ignored"))); + assertThat(e).hasMessageThat().contains("$RUNFILES_DIR and $JAVA_RUNFILES"); + } + + @Test + public void testFailsToCreateManifestBasedBecauseManifestDoesNotExist() { + IOException e = + assertThrows( + IOException.class, + () -> + Runfiles.create( + ImmutableMap.of( + "RUNFILES_MANIFEST_ONLY", "1", + "RUNFILES_MANIFEST_FILE", "non-existing path"))); + assertThat(e).hasMessageThat().contains("non-existing path"); + } + + @Test + public void testManifestBasedEnvVars() throws Exception { + Path mf = tempFile("MANIFEST", ImmutableList.of()); + Map envvars = + Runfiles.create( + ImmutableMap.of( + "RUNFILES_MANIFEST_ONLY", "1", + "RUNFILES_MANIFEST_FILE", mf.toString(), + "RUNFILES_DIR", "ignored when RUNFILES_MANIFEST_ONLY=1", + "JAVA_RUNFILES", "ignored when RUNFILES_DIR has a value", + "TEST_SRCDIR", "should always be ignored")) + .getEnvVars(); + assertThat(envvars.keySet()) + .containsExactly( + "RUNFILES_MANIFEST_ONLY", "RUNFILES_MANIFEST_FILE", "RUNFILES_DIR", "JAVA_RUNFILES"); + assertThat(envvars.get("RUNFILES_MANIFEST_ONLY")).isEqualTo("1"); + assertThat(envvars.get("RUNFILES_MANIFEST_FILE")).isEqualTo(mf.toString()); + assertThat(envvars.get("RUNFILES_DIR")).isEqualTo(tempDir.getRoot().toString()); + assertThat(envvars.get("JAVA_RUNFILES")).isEqualTo(tempDir.getRoot().toString()); + + Path rfDir = tempDir.getRoot().toPath().resolve("foo.runfiles"); + Files.createDirectories(rfDir); + mf = tempFile("foo.runfiles_manifest", ImmutableList.of()); + envvars = + Runfiles.create( + ImmutableMap.of( + "RUNFILES_MANIFEST_ONLY", "1", + "RUNFILES_MANIFEST_FILE", mf.toString(), + "RUNFILES_DIR", "ignored when RUNFILES_MANIFEST_ONLY=1", + "JAVA_RUNFILES", "ignored when RUNFILES_DIR has a value", + "TEST_SRCDIR", "should always be ignored")) + .getEnvVars(); + assertThat(envvars.get("RUNFILES_MANIFEST_ONLY")).isEqualTo("1"); + assertThat(envvars.get("RUNFILES_MANIFEST_FILE")).isEqualTo(mf.toString()); + assertThat(envvars.get("RUNFILES_DIR")).isEqualTo(rfDir.toString()); + assertThat(envvars.get("JAVA_RUNFILES")).isEqualTo(rfDir.toString()); + } + + @Test + public void testDirectoryBasedEnvVars() throws Exception { + Map envvars = + Runfiles.create( + ImmutableMap.of( + "RUNFILES_MANIFEST_FILE", + "ignored when RUNFILES_MANIFEST_ONLY is not set to 1", + "RUNFILES_DIR", + tempDir.getRoot().toString(), + "JAVA_RUNFILES", + "ignored when RUNFILES_DIR has a value", + "TEST_SRCDIR", + "should always be ignored")) + .getEnvVars(); + assertThat(envvars.keySet()).containsExactly("RUNFILES_DIR", "JAVA_RUNFILES"); + assertThat(envvars.get("RUNFILES_DIR")).isEqualTo(tempDir.getRoot().toString()); + assertThat(envvars.get("JAVA_RUNFILES")).isEqualTo(tempDir.getRoot().toString()); + } + + @Test + public void testDirectoryBasedRlocation() throws IOException { + // The DirectoryBased implementation simply joins the runfiles directory and the runfile's path + // on a "/". DirectoryBased does not perform any normalization, nor does it check that the path + // exists. + File dir = new File(System.getenv("TEST_TMPDIR"), "mock/runfiles"); + assertThat(dir.mkdirs()).isTrue(); + Runfiles r = Runfiles.createDirectoryBasedForTesting(dir.toString()).withSourceRepository(""); + // Escaping for "\": once for string and once for regex. + assertThat(r.rlocation("arg")).matches(".*[/\\\\]mock[/\\\\]runfiles[/\\\\]arg"); + } + + @Test + public void testManifestBasedRlocation() throws Exception { + Path mf = + tempFile( + "MANIFEST", + ImmutableList.of( + "Foo/runfile1 C:/Actual Path\\runfile1", + "Foo/Bar/runfile2 D:\\the path\\run file 2.txt", + "Foo/Bar/Dir E:\\Actual Path\\bDirectory", + " h/\\si F:\\bjk", + " dir\\swith\\sspaces F:\\bj k\\bdir with spaces", + " h/\\s\\n\\bi F:\\bjk\\nb")); + Runfiles r = Runfiles.createManifestBasedForTesting(mf.toString()).withSourceRepository(""); + assertThat(r.rlocation("Foo/runfile1")).isEqualTo("C:/Actual Path\\runfile1"); + assertThat(r.rlocation("Foo/Bar/runfile2")).isEqualTo("D:\\the path\\run file 2.txt"); + assertThat(r.rlocation("Foo/Bar/Dir")).isEqualTo("E:\\Actual Path\\bDirectory"); + assertThat(r.rlocation("Foo/Bar/Dir/File")).isEqualTo("E:\\Actual Path\\bDirectory/File"); + assertThat(r.rlocation("Foo/Bar/Dir/Deeply/Nested/File")) + .isEqualTo("E:\\Actual Path\\bDirectory/Deeply/Nested/File"); + assertThat(r.rlocation("Foo/Bar/Dir/Deeply/Nested/File With Spaces")) + .isEqualTo("E:\\Actual Path\\bDirectory/Deeply/Nested/File With Spaces"); + assertThat(r.rlocation("h/ i")).isEqualTo("F:\\jk"); + assertThat(r.rlocation("h/ \n\\i")).isEqualTo("F:\\jk\nb"); + assertThat(r.rlocation("dir with spaces")).isEqualTo("F:\\j k\\dir with spaces"); + assertThat(r.rlocation("dir with spaces/file")).isEqualTo("F:\\j k\\dir with spaces/file"); + assertThat(r.rlocation("unknown")).isNull(); + } + + @Test + public void testManifestBasedRlocationWithRepoMapping_fromMain() throws Exception { + Path rm = + tempFile( + "foo.repo_mapping", + ImmutableList.of( + ",config.json,config.json+1.2.3", + ",my_module,_main", + ",my_protobuf,protobuf+3.19.2", + ",my_workspace,_main", + "protobuf+3.19.2,config.json,config.json+1.2.3", + "protobuf+3.19.2,protobuf,protobuf+3.19.2")); + Path mf = + tempFile( + "foo.runfiles_manifest", + ImmutableList.of( + "_repo_mapping " + rm, + "config.json /etc/config.json", + "protobuf+3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile", + "_main/bar/runfile /the/path/./to/other//other runfile.txt", + "protobuf+3.19.2/bar/dir E:\\Actual Path\\Directory")); + Runfiles r = Runfiles.createManifestBasedForTesting(mf.toString()).withSourceRepository(""); + + assertThat(r.rlocation("my_module/bar/runfile")) + .isEqualTo("/the/path/./to/other//other runfile.txt"); + assertThat(r.rlocation("my_workspace/bar/runfile")) + .isEqualTo("/the/path/./to/other//other runfile.txt"); + assertThat(r.rlocation("my_protobuf/foo/runfile")) + .isEqualTo("C:/Actual Path\\protobuf\\runfile"); + assertThat(r.rlocation("my_protobuf/bar/dir")).isEqualTo("E:\\Actual Path\\Directory"); + assertThat(r.rlocation("my_protobuf/bar/dir/file")) + .isEqualTo("E:\\Actual Path\\Directory/file"); + assertThat(r.rlocation("my_protobuf/bar/dir/de eply/nes ted/fi+le")) + .isEqualTo("E:\\Actual Path\\Directory/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("protobuf/foo/runfile")).isNull(); + assertThat(r.rlocation("protobuf/bar/dir")).isNull(); + assertThat(r.rlocation("protobuf/bar/dir/file")).isNull(); + assertThat(r.rlocation("protobuf/bar/dir/dir/de eply/nes ted/fi+le")).isNull(); + + assertThat(r.rlocation("_main/bar/runfile")) + .isEqualTo("/the/path/./to/other//other runfile.txt"); + assertThat(r.rlocation("protobuf+3.19.2/foo/runfile")) + .isEqualTo("C:/Actual Path\\protobuf\\runfile"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir")).isEqualTo("E:\\Actual Path\\Directory"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir/file")) + .isEqualTo("E:\\Actual Path\\Directory/file"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le")) + .isEqualTo("E:\\Actual Path\\Directory/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("config.json")).isEqualTo("/etc/config.json"); + assertThat(r.rlocation("_main")).isNull(); + assertThat(r.rlocation("my_module")).isNull(); + assertThat(r.rlocation("protobuf")).isNull(); + } + + @Test + public void testManifestBasedRlocationUnmapped() throws Exception { + Path rm = + tempFile( + "foo.repo_mapping", + ImmutableList.of( + ",config.json,config.json+1.2.3", + ",my_module,_main", + ",my_protobuf,protobuf+3.19.2", + ",my_workspace,_main", + "protobuf+3.19.2,config.json,config.json+1.2.3", + "protobuf+3.19.2,protobuf,protobuf+3.19.2")); + Path mf = + tempFile( + "foo.runfiles_manifest", + ImmutableList.of( + "_repo_mapping " + rm, + "config.json /etc/config.json", + "protobuf+3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile", + "_main/bar/runfile /the/path/./to/other//other runfile.txt", + "protobuf+3.19.2/bar/dir E:\\Actual Path\\Directory")); + Runfiles r = Runfiles.createManifestBasedForTesting(mf.toString()).unmapped(); + + assertThat(r.rlocation("my_module/bar/runfile")).isNull(); + assertThat(r.rlocation("my_workspace/bar/runfile")).isNull(); + assertThat(r.rlocation("my_protobuf/foo/runfile")).isNull(); + assertThat(r.rlocation("my_protobuf/bar/dir")).isNull(); + assertThat(r.rlocation("my_protobuf/bar/dir/file")).isNull(); + assertThat(r.rlocation("my_protobuf/bar/dir/de eply/nes ted/fi+le")).isNull(); + + assertThat(r.rlocation("protobuf/foo/runfile")).isNull(); + assertThat(r.rlocation("protobuf/bar/dir")).isNull(); + assertThat(r.rlocation("protobuf/bar/dir/file")).isNull(); + assertThat(r.rlocation("protobuf/bar/dir/dir/de eply/nes ted/fi+le")).isNull(); + + assertThat(r.rlocation("_main/bar/runfile")) + .isEqualTo("/the/path/./to/other//other runfile.txt"); + assertThat(r.rlocation("protobuf+3.19.2/foo/runfile")) + .isEqualTo("C:/Actual Path\\protobuf\\runfile"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir")).isEqualTo("E:\\Actual Path\\Directory"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir/file")) + .isEqualTo("E:\\Actual Path\\Directory/file"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le")) + .isEqualTo("E:\\Actual Path\\Directory/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("config.json")).isEqualTo("/etc/config.json"); + assertThat(r.rlocation("_main")).isNull(); + assertThat(r.rlocation("my_module")).isNull(); + assertThat(r.rlocation("protobuf")).isNull(); + } + + @Test + public void testManifestBasedRlocationWithRepoMapping_fromOtherRepo() throws Exception { + Path rm = + tempFile( + "foo.repo_mapping", + ImmutableList.of( + ",config.json,config.json+1.2.3", + ",my_module,_main", + ",my_protobuf,protobuf+3.19.2", + ",my_workspace,_main", + "protobuf+3.19.2,config.json,config.json+1.2.3", + "protobuf+3.19.2,protobuf,protobuf+3.19.2")); + Path mf = + tempFile( + "foo.runfiles/MANIFEST", + ImmutableList.of( + "_repo_mapping " + rm, + "config.json /etc/config.json", + "protobuf+3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile", + "_main/bar/runfile /the/path/./to/other//other runfile.txt", + "protobuf+3.19.2/bar/dir E:\\Actual Path\\Directory")); + Runfiles r = + Runfiles.createManifestBasedForTesting(mf.toString()) + .withSourceRepository("protobuf+3.19.2"); + + assertThat(r.rlocation("protobuf/foo/runfile")).isEqualTo("C:/Actual Path\\protobuf\\runfile"); + assertThat(r.rlocation("protobuf/bar/dir")).isEqualTo("E:\\Actual Path\\Directory"); + assertThat(r.rlocation("protobuf/bar/dir/file")).isEqualTo("E:\\Actual Path\\Directory/file"); + assertThat(r.rlocation("protobuf/bar/dir/de eply/nes ted/fi+le")) + .isEqualTo("E:\\Actual Path\\Directory/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("my_module/bar/runfile")).isNull(); + assertThat(r.rlocation("my_protobuf/foo/runfile")).isNull(); + assertThat(r.rlocation("my_protobuf/bar/dir")).isNull(); + assertThat(r.rlocation("my_protobuf/bar/dir/file")).isNull(); + assertThat(r.rlocation("my_protobuf/bar/dir/de eply/nes ted/fi+le")).isNull(); + + assertThat(r.rlocation("_main/bar/runfile")) + .isEqualTo("/the/path/./to/other//other runfile.txt"); + assertThat(r.rlocation("protobuf+3.19.2/foo/runfile")) + .isEqualTo("C:/Actual Path\\protobuf\\runfile"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir")).isEqualTo("E:\\Actual Path\\Directory"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir/file")) + .isEqualTo("E:\\Actual Path\\Directory/file"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le")) + .isEqualTo("E:\\Actual Path\\Directory/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("config.json")).isEqualTo("/etc/config.json"); + assertThat(r.rlocation("_main")).isNull(); + assertThat(r.rlocation("my_module")).isNull(); + assertThat(r.rlocation("protobuf")).isNull(); + } + + @Test + public void testDirectoryBasedRlocationWithRepoMapping_fromMain() throws Exception { + Path dir = tempDir.newFolder("foo.runfiles").toPath(); + Path unused = + tempFile( + dir.resolve("_repo_mapping").toString(), + ImmutableList.of( + ",config.json,config.json+1.2.3", + ",my_module,_main", + ",my_protobuf,protobuf+3.19.2", + ",my_workspace,_main", + "protobuf+3.19.2,config.json,config.json+1.2.3", + "protobuf+3.19.2,protobuf,protobuf+3.19.2")); + Runfiles r = Runfiles.createDirectoryBasedForTesting(dir.toString()).withSourceRepository(""); + + assertThat(r.rlocation("my_module/bar/runfile")).isEqualTo(dir + "/_main/bar/runfile"); + assertThat(r.rlocation("my_workspace/bar/runfile")).isEqualTo(dir + "/_main/bar/runfile"); + assertThat(r.rlocation("my_protobuf/foo/runfile")) + .isEqualTo(dir + "/protobuf+3.19.2/foo/runfile"); + assertThat(r.rlocation("my_protobuf/bar/dir")).isEqualTo(dir + "/protobuf+3.19.2/bar/dir"); + assertThat(r.rlocation("my_protobuf/bar/dir/file")) + .isEqualTo(dir + "/protobuf+3.19.2/bar/dir/file"); + assertThat(r.rlocation("my_protobuf/bar/dir/de eply/nes ted/fi+le")) + .isEqualTo(dir + "/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("protobuf/foo/runfile")).isEqualTo(dir + "/protobuf/foo/runfile"); + assertThat(r.rlocation("protobuf/bar/dir/dir/de eply/nes ted/fi+le")) + .isEqualTo(dir + "/protobuf/bar/dir/dir/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("_main/bar/runfile")).isEqualTo(dir + "/_main/bar/runfile"); + assertThat(r.rlocation("protobuf+3.19.2/foo/runfile")) + .isEqualTo(dir + "/protobuf+3.19.2/foo/runfile"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir")).isEqualTo(dir + "/protobuf+3.19.2/bar/dir"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir/file")) + .isEqualTo(dir + "/protobuf+3.19.2/bar/dir/file"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le")) + .isEqualTo(dir + "/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("config.json")).isEqualTo(dir + "/config.json"); + } + + @Test + public void testDirectoryBasedRlocationUnmapped() throws Exception { + Path dir = tempDir.newFolder("foo.runfiles").toPath(); + Path unused = + tempFile( + dir.resolve("_repo_mapping").toString(), + ImmutableList.of( + ",config.json,config.json+1.2.3", + ",my_module,_main", + ",my_protobuf,protobuf+3.19.2", + ",my_workspace,_main", + "protobuf+3.19.2,config.json,config.json+1.2.3", + "protobuf+3.19.2,protobuf,protobuf+3.19.2")); + Runfiles r = Runfiles.createDirectoryBasedForTesting(dir.toString()).unmapped(); + + assertThat(r.rlocation("my_module/bar/runfile")).isEqualTo(dir + "/my_module/bar/runfile"); + assertThat(r.rlocation("my_workspace/bar/runfile")) + .isEqualTo(dir + "/my_workspace/bar/runfile"); + assertThat(r.rlocation("my_protobuf/foo/runfile")).isEqualTo(dir + "/my_protobuf/foo/runfile"); + assertThat(r.rlocation("my_protobuf/bar/dir")).isEqualTo(dir + "/my_protobuf/bar/dir"); + assertThat(r.rlocation("my_protobuf/bar/dir/file")) + .isEqualTo(dir + "/my_protobuf/bar/dir/file"); + assertThat(r.rlocation("my_protobuf/bar/dir/de eply/nes ted/fi+le")) + .isEqualTo(dir + "/my_protobuf/bar/dir/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("protobuf/foo/runfile")).isEqualTo(dir + "/protobuf/foo/runfile"); + assertThat(r.rlocation("protobuf/bar/dir/dir/de eply/nes ted/fi+le")) + .isEqualTo(dir + "/protobuf/bar/dir/dir/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("_main/bar/runfile")).isEqualTo(dir + "/_main/bar/runfile"); + assertThat(r.rlocation("protobuf+3.19.2/foo/runfile")) + .isEqualTo(dir + "/protobuf+3.19.2/foo/runfile"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir")).isEqualTo(dir + "/protobuf+3.19.2/bar/dir"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir/file")) + .isEqualTo(dir + "/protobuf+3.19.2/bar/dir/file"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le")) + .isEqualTo(dir + "/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("config.json")).isEqualTo(dir + "/config.json"); + } + + @Test + public void testDirectoryBasedRlocationWithRepoMapping_fromOtherRepo() throws Exception { + Path dir = tempDir.newFolder("foo.runfiles").toPath(); + Path unused = + tempFile( + dir.resolve("_repo_mapping").toString(), + ImmutableList.of( + ",config.json,config.json+1.2.3", + ",my_module,_main", + ",my_protobuf,protobuf+3.19.2", + ",my_workspace,_main", + "protobuf+3.19.2,config.json,config.json+1.2.3", + "protobuf+3.19.2,protobuf,protobuf+3.19.2")); + Runfiles r = + Runfiles.createDirectoryBasedForTesting(dir.toString()) + .withSourceRepository("protobuf+3.19.2"); + + assertThat(r.rlocation("protobuf/foo/runfile")).isEqualTo(dir + "/protobuf+3.19.2/foo/runfile"); + assertThat(r.rlocation("protobuf/bar/dir")).isEqualTo(dir + "/protobuf+3.19.2/bar/dir"); + assertThat(r.rlocation("protobuf/bar/dir/file")) + .isEqualTo(dir + "/protobuf+3.19.2/bar/dir/file"); + assertThat(r.rlocation("protobuf/bar/dir/de eply/nes ted/fi+le")) + .isEqualTo(dir + "/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("my_module/bar/runfile")).isEqualTo(dir + "/my_module/bar/runfile"); + assertThat(r.rlocation("my_protobuf/bar/dir/de eply/nes ted/fi+le")) + .isEqualTo(dir + "/my_protobuf/bar/dir/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("_main/bar/runfile")).isEqualTo(dir + "/_main/bar/runfile"); + assertThat(r.rlocation("protobuf+3.19.2/foo/runfile")) + .isEqualTo(dir + "/protobuf+3.19.2/foo/runfile"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir")).isEqualTo(dir + "/protobuf+3.19.2/bar/dir"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir/file")) + .isEqualTo(dir + "/protobuf+3.19.2/bar/dir/file"); + assertThat(r.rlocation("protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le")) + .isEqualTo(dir + "/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le"); + + assertThat(r.rlocation("config.json")).isEqualTo(dir + "/config.json"); + } + + @Test + public void testDirectoryBasedCtorArgumentValidation() throws IOException { + assertThrows( + IllegalArgumentException.class, + () -> Runfiles.createDirectoryBasedForTesting(null).withSourceRepository("")); + + assertThrows( + IllegalArgumentException.class, + () -> Runfiles.createDirectoryBasedForTesting("").withSourceRepository("")); + + assertThrows( + IllegalArgumentException.class, + () -> + Runfiles.createDirectoryBasedForTesting("non-existent directory is bad") + .withSourceRepository("")); + + Runfiles unused = + Runfiles.createDirectoryBasedForTesting(System.getenv("TEST_TMPDIR")) + .withSourceRepository(""); + } + + @Test + public void testManifestBasedCtorArgumentValidation() throws Exception { + assertThrows( + IllegalArgumentException.class, + () -> Runfiles.createManifestBasedForTesting(null).withSourceRepository("")); + + assertThrows( + IllegalArgumentException.class, + () -> Runfiles.createManifestBasedForTesting("").withSourceRepository("")); + + Path mf = tempFile("foobar", ImmutableList.of("a b")); + Runfiles unused = Runfiles.createManifestBasedForTesting(mf.toString()).withSourceRepository(""); + } + + @Test + public void testInvalidRepoMapping() throws Exception { + Path rm = tempFile("foo.repo_mapping", ImmutableList.of("a,b,c,d")); + Path mf = tempFile("foo.runfiles/MANIFEST", ImmutableList.of("_repo_mapping " + rm)); + assertThrows( + IllegalArgumentException.class, + () -> Runfiles.createManifestBasedForTesting(mf.toString()).withSourceRepository("")); + } + + private Path tempFile(String path, ImmutableList lines) throws IOException { + Path file = tempDir.getRoot().toPath().resolve(path.replace('/', File.separatorChar)); + Files.createDirectories(file.getParent()); + return Files.write(file, lines, StandardCharsets.UTF_8); + } +} diff --git a/test/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java b/test/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java new file mode 100644 index 00000000..38273261 --- /dev/null +++ b/test/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java @@ -0,0 +1,47 @@ +// Copyright 2018 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. + +package com.google.devtools.build.runfiles; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link Util}. */ +@RunWith(JUnit4.class) +public final class UtilTest { + + @Test + public void testIsNullOrEmpty() { + assertThat(Util.isNullOrEmpty(null)).isTrue(); + assertThat(Util.isNullOrEmpty("")).isTrue(); + assertThat(Util.isNullOrEmpty("\0")).isFalse(); + assertThat(Util.isNullOrEmpty("some text")).isFalse(); + } + + @Test + public void testCheckArgument() { + Util.checkArgument(true, null, null); + + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, () -> Util.checkArgument(false, null, null)); + assertThat(e).hasMessageThat().isEqualTo("argument validation failed"); + + e = assertThrows(IllegalArgumentException.class, () -> Util.checkArgument(false, "foo-%s", 42)); + assertThat(e).hasMessageThat().isEqualTo("foo-42"); + } +} From ba2744a29a712addade081e8fd6958e2c2e81024 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 19 Nov 2024 01:55:24 -0800 Subject: [PATCH 080/465] Release `rules_java` `v8.4.0` PiperOrigin-RevId: 697926251 Change-Id: Iae32aa323d539358bd17d9925890e4fe072b5841 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index ec262421..857c7a32 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.3.2", + version = "8.4.0", bazel_compatibility = [">=6.3.0"], compatibility_level = 1, ) From a156fe9afc192a9eccda07d322ad1aee7090e67f Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 19 Nov 2024 06:46:27 -0800 Subject: [PATCH 081/465] Move (and enable) remaining java rules & providers out of `@_builtins` PiperOrigin-RevId: 697997376 Change-Id: I1ef76949530cd89498826f2bae32b92d57c29f04 --- MODULE.bazel | 2 +- WORKSPACE | 4 +- java/bazel/rules/bazel_java_binary.bzl | 2 +- .../bazel/rules/bazel_java_binary_wrapper.bzl | 6 +- java/bazel/rules/bazel_java_import.bzl | 2 +- java/bazel/rules/bazel_java_library.bzl | 2 +- java/bazel/rules/bazel_java_plugin.bzl | 2 +- java/common/BUILD | 2 +- java/common/java_common.bzl | 4 +- java/common/java_info.bzl | 4 +- java/common/java_plugin_info.bzl | 4 +- java/common/java_semantics.bzl | 6 +- java/common/rules/android_lint.bzl | 6 +- java/common/rules/basic_java_library.bzl | 4 +- .../rules/impl/basic_java_library_impl.bzl | 10 +- .../rules/impl/bazel_java_import_impl.bzl | 8 +- java/common/rules/impl/compile_action.bzl | 4 +- java/common/rules/impl/java_binary_impl.bzl | 15 +- java/common/rules/impl/java_helper.bzl | 30 ++ java/common/rules/java_binary.bzl | 25 +- java/common/rules/java_import.bzl | 2 +- java/common/rules/java_library.bzl | 4 +- .../rules/java_package_configuration.bzl | 11 +- java/common/rules/java_runtime.bzl | 4 +- java/common/rules/java_toolchain.bzl | 4 +- java/extensions.bzl | 6 - java/private/BUILD | 4 +- java/private/boot_class_path_info.bzl | 4 +- java/private/java_common.bzl | 25 +- java/private/java_common_internal.bzl | 435 ++++++++++++++++++ java/private/java_info.bzl | 21 +- java/private/native.bzl | 9 + java/private/proto_support.bzl | 6 +- java/repositories.bzl | 97 +--- java/rules_java_deps.bzl | 117 +++++ .../toolchains/java_package_configuration.bzl | 5 +- java/toolchains/java_runtime.bzl | 5 +- java/toolchains/java_toolchain.bzl | 5 +- test/repo/WORKSPACE | 4 +- 39 files changed, 702 insertions(+), 208 deletions(-) create mode 100644 java/private/java_common_internal.bzl create mode 100644 java/rules_java_deps.bzl diff --git a/MODULE.bazel b/MODULE.bazel index 857c7a32..648c2b2a 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -90,7 +90,7 @@ REMOTE_JDK_REPOS = [(("remote_jdk" if version == "8" else "remotejdk") + version [register_toolchains("@" + name + "_toolchain_config_repo//:all") for name in REMOTE_JDK_REPOS] # Compatibility layer -compat = use_extension("//java:extensions.bzl", "compatibility_proxy") +compat = use_extension("//java:rules_java_deps.bzl", "compatibility_proxy") use_repo(compat, "compatibility_proxy") # Dev dependencies diff --git a/WORKSPACE b/WORKSPACE index f58f31c2..d5e6a7e7 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -37,7 +37,7 @@ http_archive( ], ) -load("//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchains") +load("//java:rules_java_deps.bzl", "rules_java_dependencies") rules_java_dependencies() @@ -45,6 +45,8 @@ load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_baze proto_bazel_features(name = "proto_bazel_features") +load("//java:repositories.bzl", "rules_java_toolchains") + rules_java_toolchains() load("@stardoc//:setup.bzl", "stardoc_repositories") diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl index 7d0e75b7..06e8421a 100644 --- a/java/bazel/rules/bazel_java_binary.bzl +++ b/java/bazel/rules/bazel_java_binary.bzl @@ -15,7 +15,6 @@ load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc:find_cc_toolchain.bzl", "use_cc_toolchain") -load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") load( "//java/common/rules:android_lint.bzl", @@ -26,6 +25,7 @@ load("//java/common/rules:rule_util.bzl", "merge_attrs") load("//java/common/rules/impl:java_binary_deploy_jar.bzl", "create_deploy_archives") load("//java/common/rules/impl:java_binary_impl.bzl", "basic_java_binary") load("//java/common/rules/impl:java_helper.bzl", "helper") +load("//java/private:java_info.bzl", "JavaInfo") def _bazel_java_binary_impl(ctx): return bazel_base_binary_impl(ctx, is_test_rule_class = False) + helper.executable_providers(ctx) diff --git a/java/bazel/rules/bazel_java_binary_wrapper.bzl b/java/bazel/rules/bazel_java_binary_wrapper.bzl index 0c61abf5..517dcd62 100644 --- a/java/bazel/rules/bazel_java_binary_wrapper.bzl +++ b/java/bazel/rules/bazel_java_binary_wrapper.bzl @@ -18,21 +18,19 @@ This is needed since the `executable` nature of the target must be computed from the supplied value of the `create_executable` attribute. """ -load("//java/common:java_common.bzl", "java_common") load( "//java/common/rules:java_binary_wrapper.bzl", "register_java_binary_rules", "register_legacy_java_binary_rules", ) +load("//java/private:native.bzl", "get_internal_java_common") load(":bazel_java_binary.bzl", java_bin_exec = "java_binary") load(":bazel_java_binary_nonexec.bzl", java_bin_nonexec = "java_binary") -_java_common_internal = java_common.internal_DO_NOT_USE() - # copybara: default visibility def java_binary(**kwargs): - if _java_common_internal.incompatible_disable_non_executable_java_binary(): + if get_internal_java_common().incompatible_disable_non_executable_java_binary(): register_java_binary_rules( java_bin_exec, **kwargs diff --git a/java/bazel/rules/bazel_java_import.bzl b/java/bazel/rules/bazel_java_import.bzl index 702dcf94..855420fe 100644 --- a/java/bazel/rules/bazel_java_import.bzl +++ b/java/bazel/rules/bazel_java_import.bzl @@ -16,10 +16,10 @@ Definition of java_import rule. """ -load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") load("//java/common/rules:java_import.bzl", "JAVA_IMPORT_ATTRS") load("//java/common/rules/impl:bazel_java_import_impl.bzl", "bazel_java_import_rule") +load("//java/private:java_info.bzl", "JavaInfo") def _proxy(ctx): return bazel_java_import_rule( diff --git a/java/bazel/rules/bazel_java_library.bzl b/java/bazel/rules/bazel_java_library.bzl index 425a91a3..2c923946 100644 --- a/java/bazel/rules/bazel_java_library.bzl +++ b/java/bazel/rules/bazel_java_library.bzl @@ -16,11 +16,11 @@ Definition of java_library rule. """ -load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") load("//java/common/rules:android_lint.bzl", "android_lint_subrule") load("//java/common/rules:java_library.bzl", "JAVA_LIBRARY_ATTRS") load("//java/common/rules/impl:bazel_java_library_impl.bzl", "bazel_java_library_rule") +load("//java/private:java_info.bzl", "JavaInfo") def _proxy(ctx): return bazel_java_library_rule( diff --git a/java/bazel/rules/bazel_java_plugin.bzl b/java/bazel/rules/bazel_java_plugin.bzl index b1bfacbf..f2619ede 100644 --- a/java/bazel/rules/bazel_java_plugin.bzl +++ b/java/bazel/rules/bazel_java_plugin.bzl @@ -16,13 +16,13 @@ Definition of java_plugin rule. """ -load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/common:java_semantics.bzl", "semantics") load("//java/common/rules:android_lint.bzl", "android_lint_subrule") load("//java/common/rules:java_library.bzl", "JAVA_LIBRARY_IMPLICIT_ATTRS") load("//java/common/rules:java_plugin.bzl", "JAVA_PLUGIN_ATTRS") load("//java/common/rules:rule_util.bzl", "merge_attrs") load("//java/common/rules/impl:basic_java_library_impl.bzl", "basic_java_library", "construct_defaultinfo") +load("//java/private:java_info.bzl", "JavaPluginInfo") def bazel_java_plugin_rule( ctx, diff --git a/java/common/BUILD b/java/common/BUILD index 01fab794..62e47db2 100644 --- a/java/common/BUILD +++ b/java/common/BUILD @@ -16,7 +16,7 @@ bzl_library( name = "common", srcs = glob(["*.bzl"]), visibility = ["//visibility:public"], - deps = ["//java/private:native_bzl"], + deps = ["//java/private:internals"], ) filegroup( diff --git a/java/common/java_common.bzl b/java/common/java_common.bzl index 201beba7..ed55bdb7 100644 --- a/java/common/java_common.bzl +++ b/java/common/java_common.bzl @@ -13,6 +13,6 @@ # limitations under the License. """java_common module""" -load("//java/private:native.bzl", "native_java_common") +load("@compatibility_proxy//:proxy.bzl", _java_common = "java_common") -java_common = native_java_common +java_common = _java_common diff --git a/java/common/java_info.bzl b/java/common/java_info.bzl index e22fb3d8..2748f6d6 100644 --- a/java/common/java_info.bzl +++ b/java/common/java_info.bzl @@ -13,6 +13,6 @@ # limitations under the License. """JavaInfo provider""" -load("//java/private:native.bzl", "NativeJavaInfo") +load("@compatibility_proxy//:proxy.bzl", _JavaInfo = "JavaInfo") -JavaInfo = NativeJavaInfo +JavaInfo = _JavaInfo diff --git a/java/common/java_plugin_info.bzl b/java/common/java_plugin_info.bzl index 36d84f94..b43dfd54 100644 --- a/java/common/java_plugin_info.bzl +++ b/java/common/java_plugin_info.bzl @@ -13,6 +13,6 @@ # limitations under the License. """JavaPluginInfo provider""" -load("//java/private:native.bzl", "NativeJavaPluginInfo") +load("@compatibility_proxy//:proxy.bzl", _JavaPluginInfo = "JavaPluginInfo") -JavaPluginInfo = NativeJavaPluginInfo +JavaPluginInfo = _JavaPluginInfo diff --git a/java/common/java_semantics.bzl b/java/common/java_semantics.bzl index ec17c92d..a08717b7 100644 --- a/java/common/java_semantics.bzl +++ b/java/common/java_semantics.bzl @@ -66,10 +66,6 @@ system property. }, ) -tokenize_javacopts = cc_helper.tokenize - -PLATFORMS_ROOT = "@platforms//" - semantics = struct( JAVA_TOOLCHAIN_LABEL = "@bazel_tools//tools/jdk:current_java_toolchain", JAVA_TOOLCHAIN_TYPE = "@bazel_tools//tools/jdk:toolchain_type", @@ -108,4 +104,6 @@ semantics = struct( for_attribute = lambda name: _DOCS.ATTRS.get(name, ""), ), minimize_cc_info = _minimize_cc_info, + tokenize_javacopts = cc_helper.tokenize, + PLATFORMS_ROOT = "@platforms//", ) diff --git a/java/common/rules/android_lint.bzl b/java/common/rules/android_lint.bzl index d7fec44b..5275ec20 100644 --- a/java/common/rules/android_lint.bzl +++ b/java/common/rules/android_lint.bzl @@ -14,13 +14,13 @@ """Creates the android lint action for java rules""" -load("//java/common:java_semantics.bzl", "semantics", _semantics_tokenize_javacopts = "tokenize_javacopts") +load("//java/common:java_semantics.bzl", "semantics") # copybara: default visibility def _tokenize_opts(opts_depset): opts = reversed(opts_depset.to_list()) - return _semantics_tokenize_javacopts(opts) + return semantics.tokenize_javacopts(opts) def _android_lint_action(ctx, source_files, source_jars, compilation_info): """ @@ -112,7 +112,7 @@ def _android_lint_action(ctx, source_files, source_jars, compilation_info): args.add_all(linter.lint_opts) for package_config in linter.package_config: - if package_config.matches(ctx.label): + if package_config.matches(package_config.package_specs, ctx.label): # wrap in a list so that map_each passes the depset to _tokenize_opts package_opts = [package_config.javac_opts] args.add_all(package_opts, map_each = _tokenize_opts) diff --git a/java/common/rules/basic_java_library.bzl b/java/common/rules/basic_java_library.bzl index c8a13fb5..f55351e1 100644 --- a/java/common/rules/basic_java_library.bzl +++ b/java/common/rules/basic_java_library.bzl @@ -16,9 +16,9 @@ Common code for reuse across java_* rules """ -load("//java/common:java_common.bzl", "java_common") -load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/common:java_semantics.bzl", "semantics") +load("//java/private:java_common.bzl", "java_common") +load("//java/private:java_info.bzl", "JavaPluginInfo") load(":rule_util.bzl", "merge_attrs") visibility([ diff --git a/java/common/rules/impl/basic_java_library_impl.bzl b/java/common/rules/impl/basic_java_library_impl.bzl index 8ba53430..da5b2bc7 100644 --- a/java/common/rules/impl/basic_java_library_impl.bzl +++ b/java/common/rules/impl/basic_java_library_impl.bzl @@ -17,10 +17,10 @@ Common code for reuse across java_* rules """ load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") -load("//java/common:java_common.bzl", "java_common") -load("//java/common:java_info.bzl", "JavaInfo") -load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/common/rules:android_lint.bzl", "android_lint_subrule") +load("//java/private:boot_class_path_info.bzl", "BootClassPathInfo") +load("//java/private:java_common_internal.bzl", "target_kind") +load("//java/private:java_info.bzl", "JavaInfo", "JavaPluginInfo") load(":compile_action.bzl", "compile_action") load(":proguard_validation.bzl", "validate_proguard_specs") @@ -28,10 +28,6 @@ visibility([ "//java/...", ]) -_java_common_internal = java_common.internal_DO_NOT_USE() -BootClassPathInfo = java_common.BootClassPathInfo -target_kind = _java_common_internal.target_kind - def _filter_srcs(srcs, ext): return [f for f in srcs if f.extension == ext] diff --git a/java/common/rules/impl/bazel_java_import_impl.bzl b/java/common/rules/impl/bazel_java_import_impl.bzl index 6d636dc3..4df2ab84 100644 --- a/java/common/rules/impl/bazel_java_import_impl.bzl +++ b/java/common/rules/impl/bazel_java_import_impl.bzl @@ -17,18 +17,16 @@ Definition of java_import rule. """ load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") -load("//java/common:java_common.bzl", "java_common") -load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") load("//java/common/rules/impl:basic_java_library_impl.bzl", "construct_defaultinfo") load("//java/common/rules/impl:import_deps_check.bzl", "import_deps_check") +load("//java/private:java_common.bzl", "java_common") +load("//java/private:java_common_internal.bzl", _run_ijar_private_for_builtins = "run_ijar") +load("//java/private:java_info.bzl", "JavaInfo") load(":proguard_validation.bzl", "validate_proguard_specs") # copybara: default visibility -_java_common_internal = java_common.internal_DO_NOT_USE() -_run_ijar_private_for_builtins = _java_common_internal.run_ijar_private_for_builtins - def _filter_provider(provider, *attrs): return [dep[provider] for attr in attrs for dep in attr if provider in dep] diff --git a/java/common/rules/impl/compile_action.bzl b/java/common/rules/impl/compile_action.bzl index d1c7f0ed..bf5b9359 100644 --- a/java/common/rules/impl/compile_action.bzl +++ b/java/common/rules/impl/compile_action.bzl @@ -17,12 +17,10 @@ Java compile action """ load("//java/common:java_semantics.bzl", "semantics") +load("//java/private:java_common_internal.bzl", _compile_private_for_builtins = "compile") visibility("private") -_java_common_internal = java_common.internal_DO_NOT_USE() -_compile_private_for_builtins = _java_common_internal.compile - def _filter_strict_deps(mode): return "error" if mode in ["strict", "default"] else mode diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl index bdaa4acd..7de9d306 100644 --- a/java/common/rules/impl/java_binary_impl.bzl +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -17,21 +17,20 @@ load("@com_google_protobuf//bazel/common:proto_info.bzl", "ProtoInfo") load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") -load("//java/common:java_common.bzl", "java_common") -load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") load("//java/common/rules/impl:basic_java_library_impl.bzl", "basic_java_library", "collect_deps") +load("//java/private:java_common.bzl", "java_common") +load( + "//java/private:java_common_internal.bzl", + "collect_native_deps_dirs", + "get_runtime_classpath_for_archive", +) +load("//java/private:java_info.bzl", "JavaCompilationInfo", "JavaInfo", "to_java_binary_info") load(":java_binary_deploy_jar.bzl", "create_deploy_archive") load(":java_helper.bzl", "helper") # copybara: default visibility -_java_common_internal = java_common.internal_DO_NOT_USE() -JavaCompilationInfo = _java_common_internal.JavaCompilationInfo -collect_native_deps_dirs = _java_common_internal.collect_native_deps_dirs -get_runtime_classpath_for_archive = _java_common_internal.get_runtime_classpath_for_archive -to_java_binary_info = _java_common_internal.to_java_binary_info - InternalDeployJarInfo = provider( "Provider for passing info to deploy jar rule", fields = [ diff --git a/java/common/rules/impl/java_helper.bzl b/java/common/rules/impl/java_helper.bzl index 87465f0a..fa828986 100644 --- a/java/common/rules/impl/java_helper.bzl +++ b/java/common/rules/impl/java_helper.bzl @@ -450,6 +450,35 @@ def _get_relative(path_a, path_b): return path_b return paths.normalize(paths.join(path_a, path_b)) +def _tokenize_javacopts(ctx = None, opts = []): + """Tokenizes a list or depset of options to a list. + + Iff opts is a depset, we reverse the flattened list to ensure right-most + duplicates are preserved in their correct position. + + If the ctx parameter is omitted, a slow, but pure Starlark, implementation + of shell tokenization is used. Otherwise, tokenization is performed using + ctx.tokenize() which has significantly better performance (up to 100x for + large options lists). + + Args: + ctx: (RuleContext|None) the rule context + opts: (depset[str]|[str]) the javac options to tokenize + Returns: + [str] list of tokenized options + """ + if hasattr(opts, "to_list"): + opts = reversed(opts.to_list()) + if ctx: + return [ + token + for opt in opts + for token in ctx.tokenize(opt) + ] + else: + # TODO: optimize and use the pure Starlark implementation in cc_helper + return semantics.tokenize_javacopts(opts) + helper = struct( collect_all_targets_as_deps = _collect_all_targets_as_deps, filter_launcher_for_target = _filter_launcher_for_target, @@ -474,6 +503,7 @@ helper = struct( create_single_jar = _create_single_jar, shell_escape = _shell_escape, detokenize_javacopts = _detokenize_javacopts, + tokenize_javacopts = _tokenize_javacopts, derive_output_file = _derive_output_file, is_stamping_enabled = _is_stamping_enabled, get_relative = _get_relative, diff --git a/java/common/rules/java_binary.bzl b/java/common/rules/java_binary.bzl index 8e0ce02f..09b6b121 100644 --- a/java/common/rules/java_binary.bzl +++ b/java/common/rules/java_binary.bzl @@ -16,18 +16,17 @@ load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") -load("//java/common:java_common.bzl", "java_common") -load("//java/common:java_info.bzl", "JavaInfo") -load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") -load("//java/common:java_semantics.bzl", "PLATFORMS_ROOT", "semantics") +load("//java/common:java_semantics.bzl", "semantics") +load("//java/private:java_common.bzl", "java_common") +load("//java/private:java_info.bzl", "JavaInfo", "JavaPluginInfo") +load("//java/private:native.bzl", "get_internal_java_common") load(":basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS") load(":rule_util.bzl", "merge_attrs") # copybara: default visibility BootClassPathInfo = java_common.BootClassPathInfo - -_java_common_internal = java_common.internal_DO_NOT_USE() +_PLATFORMS_ROOT = semantics.PLATFORMS_ROOT BASIC_JAVA_BINARY_ATTRIBUTES = merge_attrs( BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS, @@ -321,10 +320,10 @@ binaries and not libraries, due to the danger of namespace conflicts. ), "_java_toolchain_type": attr.label(default = semantics.JAVA_TOOLCHAIN_TYPE), "_windows_constraints": attr.label_list( - default = [paths.join(PLATFORMS_ROOT, "os:windows")], + default = [paths.join(_PLATFORMS_ROOT, "os:windows")], ), "_build_info_translator": attr.label(default = semantics.BUILD_INFO_TRANSLATOR_LABEL), - } | ({} if _java_common_internal.incompatible_disable_non_executable_java_binary() else {"create_executable": attr.bool(default = True, doc = "Deprecated, use java_single_jar instead.")}), + } | ({} if get_internal_java_common().incompatible_disable_non_executable_java_binary() else {"create_executable": attr.bool(default = True, doc = "Deprecated, use java_single_jar instead.")}), ) BASE_TEST_ATTRIBUTES = { @@ -367,11 +366,11 @@ The Java class to be loaded by the test runner.
"env_inherit": attr.string_list(), "_apple_constraints": attr.label_list( default = [ - paths.join(PLATFORMS_ROOT, "os:ios"), - paths.join(PLATFORMS_ROOT, "os:macos"), - paths.join(PLATFORMS_ROOT, "os:tvos"), - paths.join(PLATFORMS_ROOT, "os:visionos"), - paths.join(PLATFORMS_ROOT, "os:watchos"), + paths.join(_PLATFORMS_ROOT, "os:ios"), + paths.join(_PLATFORMS_ROOT, "os:macos"), + paths.join(_PLATFORMS_ROOT, "os:tvos"), + paths.join(_PLATFORMS_ROOT, "os:visionos"), + paths.join(_PLATFORMS_ROOT, "os:watchos"), ], ), "_legacy_any_type_attrs": attr.string_list(default = ["stamp"]), diff --git a/java/common/rules/java_import.bzl b/java/common/rules/java_import.bzl index 029f0ab6..4a22b2ab 100644 --- a/java/common/rules/java_import.bzl +++ b/java/common/rules/java_import.bzl @@ -16,8 +16,8 @@ Definition of java_import rule. """ -load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") +load("//java/private:java_info.bzl", "JavaInfo") # copybara: default visibility diff --git a/java/common/rules/java_library.bzl b/java/common/rules/java_library.bzl index cc6b749d..77861ac5 100644 --- a/java/common/rules/java_library.bzl +++ b/java/common/rules/java_library.bzl @@ -17,9 +17,9 @@ Definition of java_library rule. """ load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") -load("//java/common:java_info.bzl", "JavaInfo") -load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/common:java_semantics.bzl", "semantics") +load("//java/private:java_common.bzl", "java_common") +load("//java/private:java_info.bzl", "JavaInfo", "JavaPluginInfo") load(":basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS") load(":rule_util.bzl", "merge_attrs") diff --git a/java/common/rules/java_package_configuration.bzl b/java/common/rules/java_package_configuration.bzl index 49b24053..0752e411 100644 --- a/java/common/rules/java_package_configuration.bzl +++ b/java/common/rules/java_package_configuration.bzl @@ -14,15 +14,12 @@ """Implementation for the java_package_configuration rule""" -load("//java/common:java_common.bzl", "java_common") load("//java/common/rules/impl:java_helper.bzl", "helper") +load("//java/private:boot_class_path_info.bzl", "BootClassPathInfo") +load("//java/private:native.bzl", "get_internal_java_common") # copybara: default visibility -_java_common_internal = java_common.internal_DO_NOT_USE() - -BootClassPathInfo = java_common.BootClassPathInfo - JavaPackageConfigurationInfo = provider( "A provider for Java per-package configuration", fields = [ @@ -41,7 +38,7 @@ def _matches(package_specs, label): return False def _rule_impl(ctx): - javacopts = _java_common_internal.expand_java_opts(ctx, "javacopts", tokenize = True) + javacopts = get_internal_java_common().expand_java_opts(ctx, "javacopts", tokenize = True) javacopts_depset = helper.detokenize_javacopts(javacopts) package_specs = [package[PackageSpecificationInfo] for package in ctx.attr.packages] system = ctx.attr.system[BootClassPathInfo] if ctx.attr.system else None @@ -50,7 +47,7 @@ def _rule_impl(ctx): JavaPackageConfigurationInfo( data = depset(ctx.files.data), javac_opts = javacopts_depset, - matches = lambda label: _matches(package_specs, label), + matches = _matches, package_specs = package_specs, system = system, ), diff --git a/java/common/rules/java_runtime.bzl b/java/common/rules/java_runtime.bzl index 602819b2..fa0bd52b 100644 --- a/java/common/rules/java_runtime.bzl +++ b/java/common/rules/java_runtime.bzl @@ -18,7 +18,7 @@ Definition of java_runtime rule and JavaRuntimeInfo provider. load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") -load("//java/common:java_semantics.bzl", "PLATFORMS_ROOT") +load("//java/common:java_semantics.bzl", "semantics") load("//java/common/rules/impl:java_helper.bzl", "helper") # copybara: default visibility @@ -249,7 +249,7 @@ The feature version of the Java runtime. I.e., the integer returned by # buildifier: disable=attr-licenses "output_licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), "_windows_constraints": attr.label_list( - default = [paths.join(PLATFORMS_ROOT, "os:windows")], + default = [paths.join(semantics.PLATFORMS_ROOT, "os:windows")], ), }, fragments = ["java"], diff --git a/java/common/rules/java_toolchain.bzl b/java/common/rules/java_toolchain.bzl index 174733dc..829386f0 100644 --- a/java/common/rules/java_toolchain.bzl +++ b/java/common/rules/java_toolchain.bzl @@ -18,6 +18,8 @@ Definition of java_toolchain rule and JavaToolchainInfo provider. load("//java/common:java_semantics.bzl", "semantics") load("//java/common/rules/impl:java_helper.bzl", "helper") +load("//java/private:boot_class_path_info.bzl", "BootClassPathInfo") +load("//java/private:java_info.bzl", "JavaPluginDataInfo") load(":java_package_configuration.bzl", "JavaPackageConfigurationInfo") load(":java_runtime.bzl", "JavaRuntimeInfo") @@ -25,8 +27,6 @@ load(":java_runtime.bzl", "JavaRuntimeInfo") _java_common_internal = java_common.internal_DO_NOT_USE() ToolchainInfo = platform_common.ToolchainInfo -BootClassPathInfo = java_common.BootClassPathInfo -JavaPluginDataInfo = _java_common_internal.JavaPluginDataInfo def _java_toolchain_info_init(**_kwargs): fail("JavaToolchainInfo instantiation is a private API") diff --git a/java/extensions.bzl b/java/extensions.bzl index 0530aa27..f456f3f5 100644 --- a/java/extensions.bzl +++ b/java/extensions.bzl @@ -16,7 +16,6 @@ load("@bazel_features//:features.bzl", "bazel_features") load( "//java:repositories.bzl", - "compatibility_proxy_repo", "java_tools_repos", "local_jdk_repo", "remote_jdk11_repos", @@ -39,8 +38,3 @@ def _toolchains_impl(module_ctx): return None toolchains = module_extension(_toolchains_impl) - -def _compat_proxy_impl(_unused): - compatibility_proxy_repo() - -compatibility_proxy = module_extension(_compat_proxy_impl) diff --git a/java/private/BUILD b/java/private/BUILD index 8197421d..af9edbec 100644 --- a/java/private/BUILD +++ b/java/private/BUILD @@ -15,16 +15,17 @@ bzl_library( srcs = [ "boot_class_path_info.bzl", "java_common.bzl", + "java_common_internal.bzl", "java_info.bzl", "message_bundle_info.bzl", ], visibility = ["//java:__subpackages__"], deps = [ ":native_bzl", - "//java/common", "//java/common/rules:toolchain_rules", "//java/common/rules/impl:java_helper_bzl", "@bazel_skylib//lib:paths", + "@rules_cc//cc:find_cc_toolchain_bzl", "@rules_cc//cc/common", ], ) @@ -48,6 +49,7 @@ filegroup( testonly = 1, srcs = [ "BUILD", + ":internals", ":native_bzl", ":proto_support", ], diff --git a/java/private/boot_class_path_info.bzl b/java/private/boot_class_path_info.bzl index 7280da31..f742e8fa 100644 --- a/java/private/boot_class_path_info.bzl +++ b/java/private/boot_class_path_info.bzl @@ -18,7 +18,9 @@ Definition of the BootClassPathInfo provider. load("@bazel_skylib//lib:paths.bzl", "paths") -visibility("private") +visibility( + ["//java/..."], +) def _init(bootclasspath = [], auxiliary = [], system = None): """The BootClassPathInfo constructor. diff --git a/java/private/java_common.bzl b/java/private/java_common.bzl index 5175ac55..ebaa35d5 100644 --- a/java/private/java_common.bzl +++ b/java/private/java_common.bzl @@ -20,6 +20,11 @@ load("//java/common/rules:java_runtime.bzl", "JavaRuntimeInfo") load("//java/common/rules:java_toolchain.bzl", "JavaToolchainInfo") load("//java/common/rules/impl:java_helper.bzl", "helper") load(":boot_class_path_info.bzl", "BootClassPathInfo") +load( + ":java_common_internal.bzl", + _compile_internal = "compile", + _run_ijar_internal = "run_ijar", +) load( ":java_info.bzl", "JavaInfo", @@ -30,11 +35,9 @@ load( _java_info_set_annotation_processing = "set_annotation_processing", ) load(":message_bundle_info.bzl", "MessageBundleInfo") -load(":native.bzl", _native_java_common = "native_java_common") - -visibility("private") +load(":native.bzl", "get_internal_java_common") -_java_common_internal = _native_java_common.internal_DO_NOT_USE() +# copybara: default visibility JavaRuntimeClasspathInfo = provider( "Provider for the runtime classpath contributions of a Java binary.", @@ -65,7 +68,7 @@ def _compile( enable_annotation_processing = True, add_exports = [], add_opens = []): - return _java_common_internal.compile( + return _compile_internal( ctx, output, java_toolchain, @@ -92,8 +95,8 @@ def _compile( ) def _run_ijar(actions, jar, java_toolchain, target_label = None): - _java_common_internal.check_java_toolchain_is_declared_on_rule(actions) - return _java_common_internal.run_ijar_private_for_builtins( + get_internal_java_common().check_java_toolchain_is_declared_on_rule(actions) + return _run_ijar_internal( actions = actions, jar = jar, java_toolchain = java_toolchain, @@ -117,7 +120,7 @@ def _stamp_jar(actions, jar, java_toolchain, target_label): (File) The output artifact """ - _java_common_internal.check_java_toolchain_is_declared_on_rule(actions) + get_internal_java_common().check_java_toolchain_is_declared_on_rule(actions) output = actions.declare_file(paths.replace_extension(jar.basename, "-stamped.jar"), sibling = jar) args = actions.args() args.add(jar) @@ -156,7 +159,7 @@ def _pack_sources( Returns: (File) The output artifact """ - _java_common_internal.check_java_toolchain_is_declared_on_rule(actions) + get_internal_java_common().check_java_toolchain_is_declared_on_rule(actions) return helper.create_single_jar( actions, toolchain = java_toolchain, @@ -287,7 +290,7 @@ def _java_toolchain_label(java_toolchain): # (discouraged) use of --experimental_google_legacy_api. return None - _java_common_internal.check_provider_instances([java_toolchain], "java_toolchain", JavaToolchainInfo) + get_internal_java_common().check_provider_instances([java_toolchain], "java_toolchain", JavaToolchainInfo) return java_toolchain.label def _make_java_common(): @@ -307,7 +310,7 @@ def _make_java_common(): "BootClassPathInfo": BootClassPathInfo, "JavaRuntimeClasspathInfo": JavaRuntimeClasspathInfo, } - if _java_common_internal.google_legacy_api_enabled(): + if get_internal_java_common().google_legacy_api_enabled(): methods.update( MessageBundleInfo = _get_message_bundle_info(), # struct field that is None in bazel add_constraints = _add_constraints, diff --git a/java/private/java_common_internal.bzl b/java/private/java_common_internal.bzl new file mode 100644 index 00000000..78a8ee2c --- /dev/null +++ b/java/private/java_common_internal.bzl @@ -0,0 +1,435 @@ +# Copyright 2023 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. + +""" Private utilities for Java compilation support in Starlark. """ + +load("@bazel_skylib//lib:paths.bzl", "paths") +load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_toolchain.bzl", "JavaToolchainInfo") +load("//java/common/rules/impl:java_helper.bzl", "helper") +load( + ":java_info.bzl", + "JavaPluginInfo", + "disable_plugin_info_annotation_processing", + "java_info_for_compilation", + "merge_plugin_info_without_outputs", +) +load(":native.bzl", "get_internal_java_common") + +visibility([ + "//java/...", +]) + +def compile( + ctx, + output, + java_toolchain, + source_jars = [], + source_files = [], + output_source_jar = None, + javac_opts = [], + deps = [], + runtime_deps = [], + exports = [], + plugins = [], + exported_plugins = [], + native_libraries = [], + annotation_processor_additional_inputs = [], + annotation_processor_additional_outputs = [], + strict_deps = "ERROR", + bootclasspath = None, + javabuilder_jvm_flags = None, + sourcepath = [], + resources = [], + add_exports = [], + add_opens = [], + neverlink = False, + enable_annotation_processing = True, + # private to @_builtins: + enable_compile_jar_action = True, + enable_jspecify = True, + include_compilation_info = True, + classpath_resources = [], + resource_jars = [], + injecting_rule_kind = None): + """Compiles Java source files/jars from the implementation of a Starlark rule + + The result is a provider that represents the results of the compilation and can be added to the + set of providers emitted by this rule. + + Args: + ctx: (RuleContext) The rule context + output: (File) The output of compilation + java_toolchain: (JavaToolchainInfo) Toolchain to be used for this compilation. Mandatory. + source_jars: ([File]) A list of the jars to be compiled. At least one of source_jars or + source_files should be specified. + source_files: ([File]) A list of the Java source files to be compiled. At least one of + source_jars or source_files should be specified. + output_source_jar: (File) The output source jar. Optional. Defaults to + `{output_jar}-src.jar` if unset. + javac_opts: ([str]|depset[str]) A list of the desired javac options. Optional. + deps: ([JavaInfo]) A list of dependencies. Optional. + runtime_deps: ([JavaInfo]) A list of runtime dependencies. Optional. + exports: ([JavaInfo]) A list of exports. Optional. + plugins: ([JavaPluginInfo|JavaInfo]) A list of plugins. Optional. + exported_plugins: ([JavaPluginInfo|JavaInfo]) A list of exported plugins. Optional. + native_libraries: ([CcInfo]) CC library dependencies that are needed for this library. + annotation_processor_additional_inputs: ([File]) A list of inputs that the Java compilation + action will take in addition to the Java sources for annotation processing. + annotation_processor_additional_outputs: ([File]) A list of outputs that the Java + compilation action will output in addition to the class jar from annotation processing. + strict_deps: (str) A string that specifies how to handle strict deps. Possible values: + 'OFF', 'ERROR', 'WARN' and 'DEFAULT'. + bootclasspath: (BootClassPathInfo) If present, overrides the bootclasspath associated with + the provided java_toolchain. Optional. + javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. + sourcepath: ([File]) + resources: ([File]) + resource_jars: ([File]) + classpath_resources: ([File]) + neverlink: (bool) + enable_annotation_processing: (bool) Disables annotation processing in this compilation, + causing any annotation processors provided in plugins or in exported_plugins of deps to + be ignored. + enable_compile_jar_action: (bool) Enables header compilation or ijar creation. If set to + False, it forces use of the full class jar in the compilation classpaths of any + dependants. Doing so is intended for use by non-library targets such as binaries that + do not have dependants. + enable_jspecify: (bool) + include_compilation_info: (bool) + injecting_rule_kind: (str|None) + add_exports: ([str]) Allow this library to access the given /. Optional. + add_opens: ([str]) Allow this library to reflectively access the given /. + Optional. + + Returns: + (JavaInfo) + """ + get_internal_java_common().check_provider_instances([java_toolchain], "java_toolchain", JavaToolchainInfo) + get_internal_java_common().check_provider_instances(plugins, "plugins", JavaPluginInfo) + + plugin_info = merge_plugin_info_without_outputs(plugins + deps) + + all_javac_opts = [] # [depset[str]] + all_javac_opts.append(java_toolchain._javacopts) + + all_javac_opts.append(ctx.fragments.java.default_javac_flags_depset) + all_javac_opts.append(semantics.compatible_javac_options(ctx, java_toolchain)) + + if ("com.google.devtools.build.runfiles.AutoBazelRepositoryProcessor" in + plugin_info.plugins.processor_classes.to_list()): + all_javac_opts.append(depset( + ["-Abazel.repository=" + ctx.label.workspace_name], + order = "preorder", + )) + system_bootclasspath = None + for package_config in java_toolchain._package_configuration: + if package_config.matches(package_config.package_specs, ctx.label): + all_javac_opts.append(package_config.javac_opts) + if package_config.system: + if system_bootclasspath: + fail("Multiple system package configurations found for %s" % ctx.label) + system_bootclasspath = package_config.system + if not bootclasspath: + bootclasspath = system_bootclasspath + + all_javac_opts.append(depset( + ["--add-exports=%s=ALL-UNNAMED" % x for x in add_exports], + order = "preorder", + )) + + if type(javac_opts) == type([]): + # detokenize target's javacopts, it will be tokenized before compilation + all_javac_opts.append(helper.detokenize_javacopts(helper.tokenize_javacopts(ctx, javac_opts))) + elif type(javac_opts) == type(depset()): + all_javac_opts.append(javac_opts) + else: + fail("Expected javac_opts to be a list or depset, got:", type(javac_opts)) + + # we reverse the list of javacopts depsets, so that we keep the right-most set + # in case it's deduped. When this depset is flattened, we will reverse again, + # and then tokenize before passing to javac. This way, right-most javacopts will + # be retained and "win out". + all_javac_opts = depset(order = "preorder", transitive = reversed(all_javac_opts)) + + # Optimization: skip this if there are no annotation processors, to avoid unnecessarily + # disabling the direct classpath optimization if `enable_annotation_processor = False` + # but there aren't any annotation processors. + enable_direct_classpath = True + if not enable_annotation_processing and plugin_info.plugins.processor_classes: + plugin_info = disable_plugin_info_annotation_processing(plugin_info) + enable_direct_classpath = False + + all_javac_opts_list = helper.tokenize_javacopts(ctx, all_javac_opts) + uses_annotation_processing = False + if "-processor" in all_javac_opts_list or plugin_info.plugins.processor_classes: + uses_annotation_processing = True + + has_sources = source_files or source_jars + has_resources = resources or resource_jars + + is_strict_mode = strict_deps != "OFF" + classpath_mode = ctx.fragments.java.reduce_java_classpath() + + direct_jars = depset() + if is_strict_mode: + direct_jars = depset(order = "preorder", transitive = [dep.compile_jars for dep in deps]) + compilation_classpath = depset( + order = "preorder", + transitive = [direct_jars] + [dep.transitive_compile_time_jars for dep in deps], + ) + compile_time_java_deps = depset() + if is_strict_mode and classpath_mode != "OFF": + compile_time_java_deps = depset(transitive = [dep._compile_time_java_dependencies for dep in deps]) + + # create compile time jar action + if not has_sources: + compile_jar = None + compile_deps_proto = None + elif not enable_compile_jar_action: + compile_jar = output + compile_deps_proto = None + elif _should_use_header_compilation(ctx, java_toolchain): + compile_jar = helper.derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jar") + compile_deps_proto = helper.derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jdeps") + get_internal_java_common().create_header_compilation_action( + ctx, + java_toolchain, + compile_jar, + compile_deps_proto, + plugin_info, + depset(source_files), + source_jars, + compilation_classpath, + direct_jars, + bootclasspath, + compile_time_java_deps, + all_javac_opts, + strict_deps, + ctx.label, + injecting_rule_kind, + enable_direct_classpath, + annotation_processor_additional_inputs, + ) + elif ctx.fragments.java.use_ijars(): + compile_jar = run_ijar( + ctx.actions, + output, + java_toolchain, + target_label = ctx.label, + injecting_rule_kind = injecting_rule_kind, + ) + compile_deps_proto = None + else: + compile_jar = output + compile_deps_proto = None + + native_headers_jar = helper.derive_output_file(ctx, output, name_suffix = "-native-header") + manifest_proto = helper.derive_output_file(ctx, output, extension_suffix = "_manifest_proto") + deps_proto = None + if ctx.fragments.java.generate_java_deps() and has_sources: + deps_proto = helper.derive_output_file(ctx, output, extension = "jdeps") + generated_class_jar = None + generated_source_jar = None + if uses_annotation_processing: + generated_class_jar = helper.derive_output_file(ctx, output, name_suffix = "-gen") + generated_source_jar = helper.derive_output_file(ctx, output, name_suffix = "-gensrc") + get_internal_java_common().create_compilation_action( + ctx, + java_toolchain, + output, + manifest_proto, + plugin_info, + compilation_classpath, + direct_jars, + bootclasspath, + depset(javabuilder_jvm_flags), + compile_time_java_deps, + all_javac_opts, + strict_deps, + ctx.label, + deps_proto, + generated_class_jar, + generated_source_jar, + native_headers_jar, + depset(source_files), + source_jars, + resources, + depset(resource_jars), + classpath_resources, + sourcepath, + injecting_rule_kind, + enable_jspecify, + enable_direct_classpath, + annotation_processor_additional_inputs, + annotation_processor_additional_outputs, + ) + + create_output_source_jar = len(source_files) > 0 or source_jars != [output_source_jar] + if not output_source_jar: + output_source_jar = helper.derive_output_file(ctx, output, name_suffix = "-src", extension = "jar") + if create_output_source_jar: + helper.create_single_jar( + ctx.actions, + toolchain = java_toolchain, + output = output_source_jar, + sources = depset(source_jars + ([generated_source_jar] if generated_source_jar else [])), + resources = depset(source_files), + progress_message = "Building source jar %{output}", + mnemonic = "JavaSourceJar", + ) + + if has_sources or has_resources: + direct_runtime_jars = [output] + else: + direct_runtime_jars = [] + + compilation_info = struct( + javac_options = all_javac_opts, + # needs to be flattened because the public API is a list + boot_classpath = (bootclasspath.bootclasspath if bootclasspath else java_toolchain.bootclasspath).to_list(), + # we only add compile time jars from deps, and not exports + compilation_classpath = compilation_classpath, + runtime_classpath = depset( + order = "preorder", + direct = direct_runtime_jars, + transitive = [dep.transitive_runtime_jars for dep in runtime_deps + deps], + ), + uses_annotation_processing = uses_annotation_processing, + ) if include_compilation_info else None + + return java_info_for_compilation( + output_jar = output, + compile_jar = compile_jar, + source_jar = output_source_jar, + generated_class_jar = generated_class_jar, + generated_source_jar = generated_source_jar, + plugin_info = plugin_info, + deps = deps, + runtime_deps = runtime_deps, + exports = exports, + exported_plugins = exported_plugins, + compile_jdeps = compile_deps_proto if compile_deps_proto else deps_proto, + jdeps = deps_proto if include_compilation_info else None, + native_headers_jar = native_headers_jar, + manifest_proto = manifest_proto, + native_libraries = native_libraries, + neverlink = neverlink, + add_exports = add_exports, + add_opens = add_opens, + direct_runtime_jars = direct_runtime_jars, + compilation_info = compilation_info, + ) + +def _should_use_header_compilation(ctx, toolchain): + if not ctx.fragments.java.use_header_compilation(): + return False + if toolchain._forcibly_disable_header_compilation: + return False + if not toolchain._header_compiler: + fail( + "header compilation was requested but it is not supported by the " + + "current Java toolchain '" + str(toolchain.label) + + "'; see the java_toolchain.header_compiler attribute", + ) + if not toolchain._header_compiler_direct: + fail( + "header compilation was requested but it is not supported by the " + + "current Java toolchain '" + str(toolchain.label) + + "'; see the java_toolchain.header_compiler_direct attribute", + ) + return True + +def run_ijar( + actions, + jar, + java_toolchain, + target_label = None, + # private to @_builtins: + output = None, + injecting_rule_kind = None): + """Runs ijar on a jar, stripping it of its method bodies. + + This helps reduce rebuilding of dependent jars during any recompiles consisting only of simple + changes to method implementations. The return value is typically passed to JavaInfo.compile_jar + + Args: + actions: (actions) ctx.actions + jar: (File) The jar to run ijar on. + java_toolchain: (JavaToolchainInfo) The toolchain to used to find the ijar tool. + target_label: (Label|None) A target label to stamp the jar with. Used for `add_dep` support. + Typically, you would pass `ctx.label` to stamp the jar with the current rule's label. + output: (File) Optional. + injecting_rule_kind: (str) the rule class of the current target + Returns: + (File) The output artifact + """ + if not output: + output = actions.declare_file(paths.replace_extension(jar.basename, "-ijar.jar"), sibling = jar) + args = actions.args() + args.add(jar) + args.add(output) + if target_label != None: + args.add("--target_label", target_label) + if injecting_rule_kind != None: + args.add("--injecting_rule_kind", injecting_rule_kind) + + actions.run( + mnemonic = "JavaIjar", + inputs = [jar], + outputs = [output], + executable = java_toolchain.ijar, + arguments = [args], + progress_message = "Extracting interface for jar %{input}", + toolchain = semantics.JAVA_TOOLCHAIN_TYPE, + use_default_shell_env = True, + ) + return output + +def target_kind(target): + """Get the rule class string for a target + + Args: + target: (Target) + + Returns: + (str) The rule class string of the target + """ + return get_internal_java_common().target_kind(target) + +def collect_native_deps_dirs(libraries): + """Collect the set of root-relative paths containing native libraries + + Args: + libraries: (depset[LibraryToLink]) set of native libraries + + Returns: + ([String]) A set of root-relative paths as a list + """ + return get_internal_java_common().collect_native_deps_dirs(libraries) + +def get_runtime_classpath_for_archive(jars, excluded_jars): + """Filters a classpath to remove certain entries + + Args + jars: (depset[File]) The classpath to filter + excluded_jars: (depset[File]) The files to remove + + Returns: + (depset[File]) The filtered classpath + """ + return get_internal_java_common().get_runtime_classpath_for_archive( + jars, + excluded_jars, + ) diff --git a/java/private/java_info.bzl b/java/private/java_info.bzl index f55020fd..8ba655ed 100644 --- a/java/private/java_info.bzl +++ b/java/private/java_info.bzl @@ -19,14 +19,9 @@ Definition of JavaInfo and JavaPluginInfo provider. load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_semantics.bzl", "semantics") -load(":native.bzl", _native_java_common = "native_java_common") +load(":native.bzl", "get_internal_java_common") -visibility("private") - -# TODO(hvd): remove this when: -# - we have a general provider-type checking API -# - no longer need to check for --experimental_google_legacy_api -_java_common_internal = _native_java_common.internal_DO_NOT_USE() +# copybara: default visibility _JavaOutputInfo = provider( doc = "The outputs of Java compilation.", @@ -175,7 +170,7 @@ def merge( "compilation_info": None, } - if _java_common_internal.google_legacy_api_enabled(): + if get_internal_java_common().google_legacy_api_enabled(): cc_info = semantics.minimize_cc_info(cc_common.merge_cc_infos(cc_infos = [p.cc_link_params_info for p in providers])) result.update( cc_link_params_info = cc_info, @@ -188,7 +183,7 @@ def merge( transitive = [p.transitive_native_libraries for p in providers], ), ) - return _java_common_internal.wrap_java_info(_new_javainfo(**result)) + return get_internal_java_common().wrap_java_info(_new_javainfo(**result)) def to_java_binary_info(java_info, compilation_info): """Get a copy of the given JavaInfo with minimal info returned by a java_binary @@ -496,10 +491,10 @@ def java_info_for_compilation( compilation_info = None, annotation_processing = None, ) - return _java_common_internal.wrap_java_info(_new_javainfo(**result)) + return get_internal_java_common().wrap_java_info(_new_javainfo(**result)) def _validate_provider_list(provider_list, what, expected_provider_type): - _java_common_internal.check_provider_instances(provider_list, what, expected_provider_type) + get_internal_java_common().check_provider_instances(provider_list, what, expected_provider_type) def _compute_concatenated_deps(deps, runtime_deps, exports): deps_exports = [] @@ -627,7 +622,7 @@ def _javainfo_init_base( "_constraints": [], } - if _java_common_internal.google_legacy_api_enabled(): + if get_internal_java_common().google_legacy_api_enabled(): transitive_cc_infos = [dep.cc_link_params_info for dep in concatenated_deps.runtimedeps_exports_deps] transitive_cc_infos.extend(native_libraries) cc_info = semantics.minimize_cc_info(cc_common.merge_cc_infos(cc_infos = transitive_cc_infos)) @@ -737,7 +732,7 @@ def _javainfo_init( # TODO: When this flag is removed, move this logic into _javainfo_init_base # and remove the special case from java_info_for_compilation. module_flags_deps = concatenated_deps.deps_exports - if _java_common_internal._incompatible_java_info_merge_runtime_module_flags(): + if get_internal_java_common().incompatible_java_info_merge_runtime_module_flags(): module_flags_deps = concatenated_deps.runtimedeps_exports_deps result.update( diff --git a/java/private/native.bzl b/java/private/native.bzl index 64a4d5ac..22f84ffb 100644 --- a/java/private/native.bzl +++ b/java/private/native.bzl @@ -21,6 +21,8 @@ """Lovely workaround to be able to expose native constants pretending to be Starlark.""" +# Unused with Bazel@HEAD, used by the compatibility layer for older Bazel versions + # buildifier: disable=native-java native_java_common = java_common @@ -29,3 +31,10 @@ NativeJavaInfo = JavaInfo # buildifier: disable=native-java NativeJavaPluginInfo = JavaPluginInfo + +# Used for some private native APIs that we can't replicate just yet in Starlark +# getattr() for loading this file with Bazel 6, where we won't use this +def get_internal_java_common(): + if hasattr(native_java_common, "internal_DO_NOT_USE"): + return native_java_common.internal_DO_NOT_USE() + return None diff --git a/java/private/proto_support.bzl b/java/private/proto_support.bzl index 8666e5a5..dcb8f09d 100644 --- a/java/private/proto_support.bzl +++ b/java/private/proto_support.bzl @@ -13,13 +13,13 @@ # limitations under the License. """Support for Java compilation of protocol buffer generated code.""" -load("//java/private:native.bzl", "native_java_common") +load("//java/common:java_common.bzl", "java_common") # Partial support, because internal symbols are not available in older Bazel version # TODO: Once Java rules are moved into the rules_java, this should become a full support. def compile(*, injecting_rule_kind, enable_jspecify, include_compilation_info, **kwargs): # buildifier: disable=unused-variable - return native_java_common.compile(**kwargs) + return java_common.compile(**kwargs) def merge(providers, *, merge_java_outputs = True, merge_source_jars = True): # buildifier: disable=unused-variable - return native_java_common.merge(providers) + return java_common.merge(providers) diff --git a/java/repositories.bzl b/java/repositories.bzl index 60f94ef6..f02b0f66 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -362,58 +362,23 @@ def remote_jdk21_repos(): """Imports OpenJDK 21 repositories.""" _remote_jdk_repos_for_version("21") -def protobuf_repo(): - maybe( - http_archive, - name = "com_google_protobuf", - sha256 = "ce5d00b78450a0ca400bf360ac00c0d599cc225f049d986a27e9a4e396c5a84a", - strip_prefix = "protobuf-29.0-rc2", - url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.0-rc2/protobuf-29.0-rc2.tar.gz", - ) - -def rules_cc_repo(): - maybe( - http_archive, - name = "rules_cc", - sha256 = "f4aadd8387f381033a9ad0500443a52a0cea5f8ad1ede4369d3c614eb7b2682e", - strip_prefix = "rules_cc-0.0.15", - urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.15/rules_cc-0.0.15.tar.gz"], - ) - -def bazel_skylib_repo(): - maybe( - http_archive, - name = "bazel_skylib", - sha256 = "bc283cdfcd526a52c3201279cda4bc298652efa898b10b4db0837dc51652756f", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", - "https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", - ], - ) - def rules_java_dependencies(): - """An utility method to load all dependencies of rules_java. + """DEPRECATED: No-op, kept for backwards compatibility""" + print("DEPRECATED: use rules_java_dependencies() from rules_java_deps.bzl") # buildifier: disable=print - Loads the remote repositories used by default in Bazel. - """ +def rules_java_toolchains(name = "toolchains"): + """An utility method to load all Java toolchains. + Args: + name: The name of this macro (not used) + """ local_jdk_repo() remote_jdk8_repos() remote_jdk11_repos() remote_jdk17_repos() remote_jdk21_repos() java_tools_repos() - compatibility_proxy_repo() - protobuf_repo() - rules_cc_repo() - bazel_skylib_repo() -def rules_java_toolchains(name = "toolchains"): - """An utility method to load all Java toolchains. - - Args: - name: The name of this macro (not used) - """ native.register_toolchains( "//toolchains:all", "@local_jdk//:runtime_toolchain_definition", @@ -425,51 +390,3 @@ def rules_java_toolchains(name = "toolchains"): "@" + item.name + "_toolchain_config_repo//:toolchain", "@" + item.name + "_toolchain_config_repo//:bootstrap_runtime_toolchain", ) - -def _compatibility_proxy_repo_impl(rctx): - # TODO: use @bazel_features - bazel = native.bazel_version - rctx.file("BUILD.bazel", "") - if not bazel or bazel >= "8": - rctx.file( - "proxy.bzl", - """ -load("@rules_java//java/bazel/rules:bazel_java_binary_wrapper.bzl", _java_binary = "java_binary") # copybara-use-repo-external-label -load("@rules_java//java/bazel/rules:bazel_java_import.bzl", _java_import = "java_import") # copybara-use-repo-external-label -load("@rules_java//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") # copybara-use-repo-external-label -load("@rules_java//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") # copybara-use-repo-external-label -load("@rules_java//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") # copybara-use-repo-external-label -load("@rules_java//java:http_jar.bzl", _http_jar = "http_jar") # copybara-use-repo-external-label - -java_binary = _java_binary -java_import = _java_import -java_library = _java_library -java_plugin = _java_plugin -java_test = _java_test - -http_jar = _http_jar - """, - ) - else: - rctx.file( - "proxy.bzl", - """ -load("@bazel_tools//tools/build_defs/repo:http.bzl", _http_jar = "http_jar") -java_binary = native.java_binary -java_import = native.java_import -java_library = native.java_library -java_plugin = native.java_plugin -java_test = native.java_test - -http_jar = _http_jar - """, - ) - -_compatibility_proxy_repo_rule = repository_rule( - _compatibility_proxy_repo_impl, - # force reruns on server restarts to use correct native.bazel_version - local = True, -) - -def compatibility_proxy_repo(): - maybe(_compatibility_proxy_repo_rule, name = "compatibility_proxy") diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl new file mode 100644 index 00000000..5520ba17 --- /dev/null +++ b/java/rules_java_deps.bzl @@ -0,0 +1,117 @@ +"""Module extension for compatibility with previous Bazel versions""" + +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") +load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") + +def _compatibility_proxy_repo_impl(rctx): + # TODO: use @bazel_features + bazel = native.bazel_version + rctx.file("BUILD.bazel", "") + if not bazel or bazel >= "8": + rctx.file( + "proxy.bzl", + """ +load("@rules_java//java/bazel/rules:bazel_java_binary_wrapper.bzl", _java_binary = "java_binary") # copybara-use-repo-external-label +load("@rules_java//java/bazel/rules:bazel_java_import.bzl", _java_import = "java_import") # copybara-use-repo-external-label +load("@rules_java//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") # copybara-use-repo-external-label +load("@rules_java//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") # copybara-use-repo-external-label +load("@rules_java//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") # copybara-use-repo-external-label +load("@rules_java//java/common/rules:java_package_configuration.bzl", _java_package_configuration = "java_package_configuration") # copybara-use-repo-external-label +load("@rules_java//java/common/rules:java_runtime.bzl", _java_runtime = "java_runtime") # copybara-use-repo-external-label +load("@rules_java//java/common/rules:java_toolchain.bzl", _java_toolchain = "java_toolchain") # copybara-use-repo-external-label +load("@rules_java//java/private:java_common.bzl", _java_common = "java_common") # copybara-use-repo-external-label +load("@rules_java//java/private:java_info.bzl", _JavaInfo = "JavaInfo", _JavaPluginInfo = "JavaPluginInfo") # copybara-use-repo-external-label +load("@rules_java//java:http_jar.bzl", _http_jar = "http_jar") # copybara-use-repo-external-label + +java_binary = _java_binary +java_import = _java_import +java_library = _java_library +java_plugin = _java_plugin +java_test = _java_test +java_package_configuration = _java_package_configuration +java_runtime = _java_runtime +java_toolchain = _java_toolchain +java_common = _java_common +JavaInfo = _JavaInfo +JavaPluginInfo = _JavaPluginInfo + +http_jar = _http_jar + """, + ) + else: + rctx.file( + "proxy.bzl", + """ +load("@bazel_tools//tools/build_defs/repo:http.bzl", _http_jar = "http_jar") +load("@rules_java//java/private:native.bzl", "native_java_common", "NativeJavaInfo", "NativeJavaPluginInfo") # copybara-use-repo-external-label + +java_binary = native.java_binary +java_import = native.java_import +java_library = native.java_library +java_plugin = native.java_plugin +java_test = native.java_test + +java_package_configuration = native.java_package_configuration +java_runtime = native.java_runtime +java_toolchain = native.java_toolchain + +java_common = native_java_common +JavaInfo = NativeJavaInfo +JavaPluginInfo = NativeJavaPluginInfo + +http_jar = _http_jar + """, + ) + +_compatibility_proxy_repo_rule = repository_rule( + _compatibility_proxy_repo_impl, + # force reruns on server restarts to use correct native.bazel_version + local = True, +) + +def compatibility_proxy_repo(): + maybe(_compatibility_proxy_repo_rule, name = "compatibility_proxy") + +def _compat_proxy_impl(_unused): + compatibility_proxy_repo() + +compatibility_proxy = module_extension(_compat_proxy_impl) + +def protobuf_repo(): + maybe( + http_archive, + name = "com_google_protobuf", + sha256 = "ce5d00b78450a0ca400bf360ac00c0d599cc225f049d986a27e9a4e396c5a84a", + strip_prefix = "protobuf-29.0-rc2", + url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.0-rc2/protobuf-29.0-rc2.tar.gz", + ) + +def rules_cc_repo(): + maybe( + http_archive, + name = "rules_cc", + sha256 = "f4aadd8387f381033a9ad0500443a52a0cea5f8ad1ede4369d3c614eb7b2682e", + strip_prefix = "rules_cc-0.0.15", + urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.15/rules_cc-0.0.15.tar.gz"], + ) + +def bazel_skylib_repo(): + maybe( + http_archive, + name = "bazel_skylib", + sha256 = "bc283cdfcd526a52c3201279cda4bc298652efa898b10b4db0837dc51652756f", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", + "https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", + ], + ) + +def rules_java_dependencies(): + """An utility method to load non-toolchain dependencies of rules_java. + + Loads the remote repositories used by default in Bazel. + """ + compatibility_proxy_repo() + bazel_skylib_repo() + rules_cc_repo() + protobuf_repo() diff --git a/java/toolchains/java_package_configuration.bzl b/java/toolchains/java_package_configuration.bzl index 09d8e1e9..7ef0728b 100644 --- a/java/toolchains/java_package_configuration.bzl +++ b/java/toolchains/java_package_configuration.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_package_configuration rule""" +load("@compatibility_proxy//:proxy.bzl", _java_package_configuration = "java_package_configuration") + def java_package_configuration(**attrs): """Bazel java_package_configuration rule. @@ -22,5 +24,4 @@ def java_package_configuration(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_package_configuration(**attrs) + _java_package_configuration(**attrs) diff --git a/java/toolchains/java_runtime.bzl b/java/toolchains/java_runtime.bzl index 3657a88d..c1d16411 100644 --- a/java/toolchains/java_runtime.bzl +++ b/java/toolchains/java_runtime.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_runtime rule""" +load("@compatibility_proxy//:proxy.bzl", _java_runtime = "java_runtime") + def java_runtime(**attrs): """Bazel java_runtime rule. @@ -22,5 +24,4 @@ def java_runtime(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_runtime(**attrs) + _java_runtime(**attrs) diff --git a/java/toolchains/java_toolchain.bzl b/java/toolchains/java_toolchain.bzl index 5b072928..5207f8c9 100644 --- a/java/toolchains/java_toolchain.bzl +++ b/java/toolchains/java_toolchain.bzl @@ -13,6 +13,8 @@ # limitations under the License. """java_toolchain rule""" +load("@compatibility_proxy//:proxy.bzl", _java_toolchain = "java_toolchain") + def java_toolchain(**attrs): """Bazel java_toolchain rule. @@ -22,5 +24,4 @@ def java_toolchain(**attrs): **attrs: Rule attributes """ - # buildifier: disable=native-java - native.java_toolchain(**attrs) + _java_toolchain(**attrs) diff --git a/test/repo/WORKSPACE b/test/repo/WORKSPACE index c4f22a68..aa3b7cba 100644 --- a/test/repo/WORKSPACE +++ b/test/repo/WORKSPACE @@ -5,7 +5,7 @@ local_repository( path = "../../", ) -load("@rules_java//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchains") +load("@rules_java//java:rules_java_deps.bzl", "rules_java_dependencies") rules_java_dependencies() @@ -13,6 +13,8 @@ load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_baze proto_bazel_features(name = "proto_bazel_features") +load("@rules_java//java:repositories.bzl", "rules_java_toolchains") + rules_java_toolchains() load("@compatibility_proxy//:proxy.bzl", "http_jar") From bc4a03fe5525123c04a9fe879dc2882d31e7d690 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Tue, 19 Nov 2024 08:53:58 -0800 Subject: [PATCH 082/465] Add runfiles library to release archive Copybara Import from https://github.com/bazelbuild/rules_java/pull/242 BEGIN_PUBLIC Add runfiles library to release archive (#242) Closes #242 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/242 from fmeum:fix-runfiles dcc8004733fe5a6257f5ef2fdec5b04cdb62564a PiperOrigin-RevId: 698035007 Change-Id: I069b7f289a40550ac1c8024d013863e3d384d5a6 --- java/BUILD | 1 + java/runfiles/BUILD.bazel | 8 ++++++++ .../google/devtools/build/runfiles/BUILD.bazel | 6 ++++++ test/repo/BUILD.bazel | 8 +++++++- test/repo/MODULE.bazel | 2 +- test/repo/setup.sh | 0 test/repo/src/MyTest.java | 16 +++++++++++++++- test/repo/src/data.txt | 0 8 files changed, 38 insertions(+), 3 deletions(-) mode change 100644 => 100755 test/repo/setup.sh create mode 100644 test/repo/src/data.txt diff --git a/java/BUILD b/java/BUILD index 17101290..caacb07e 100644 --- a/java/BUILD +++ b/java/BUILD @@ -13,6 +13,7 @@ filegroup( "//java/common:srcs", "//java/private:srcs", "//java/proto:srcs", + "//java/runfiles:srcs", "//java/toolchains:srcs", ], visibility = ["//:__pkg__"], diff --git a/java/runfiles/BUILD.bazel b/java/runfiles/BUILD.bazel index 792e45f7..05a8104b 100644 --- a/java/runfiles/BUILD.bazel +++ b/java/runfiles/BUILD.bazel @@ -3,3 +3,11 @@ alias( actual = "//java/runfiles/src/main/java/com/google/devtools/build/runfiles", visibility = ["//visibility:public"], ) + +filegroup( + name = "srcs", + srcs = glob(["**"]) + [ + "//java/runfiles/src/main/java/com/google/devtools/build/runfiles:srcs", + ], + visibility = ["//java:__pkg__"], +) diff --git a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD.bazel b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD.bazel index fd351b73..a2563d9d 100644 --- a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD.bazel +++ b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD.bazel @@ -21,3 +21,9 @@ java_plugin( srcs = ["AutoBazelRepositoryProcessor.java"], processor_class = "com.google.devtools.build.runfiles.AutoBazelRepositoryProcessor", ) + +filegroup( + name = "srcs", + srcs = glob(["**"]), + visibility = ["//java/runfiles:__pkg__"], +) diff --git a/test/repo/BUILD.bazel b/test/repo/BUILD.bazel index 20deeaeb..c1482dac 100644 --- a/test/repo/BUILD.bazel +++ b/test/repo/BUILD.bazel @@ -15,7 +15,13 @@ java_binary( java_test( name = "MyTest", srcs = ["src/MyTest.java"], - deps = ["@my_jar//jar"], + data = [ + "src/data.txt", + ], + deps = [ + "@my_jar//jar", + "@rules_java//java/runfiles", + ], ) default_java_toolchain( diff --git a/test/repo/MODULE.bazel b/test/repo/MODULE.bazel index 5a4d6114..c582bf40 100644 --- a/test/repo/MODULE.bazel +++ b/test/repo/MODULE.bazel @@ -1,4 +1,4 @@ -module(name = "fake_repo_for_testing") +module(name = "integration_test_repo") bazel_dep(name = "rules_java", version = "7.5.0") archive_override( diff --git a/test/repo/setup.sh b/test/repo/setup.sh old mode 100644 new mode 100755 diff --git a/test/repo/src/MyTest.java b/test/repo/src/MyTest.java index 2de08a05..d2c21080 100644 --- a/test/repo/src/MyTest.java +++ b/test/repo/src/MyTest.java @@ -1,15 +1,29 @@ import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import com.google.devtools.build.runfiles.AutoBazelRepository; +import com.google.devtools.build.runfiles.Runfiles; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import mypackage.MyLib; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) +@AutoBazelRepository public class MyTest { @Test public void main() { assertEquals(MyLib.myStr(), "my_string"); } -} + @Test + public void runfiles() throws IOException { + Runfiles runfiles = Runfiles.preload().withSourceRepository(AutoBazelRepository_MyTest.NAME); + Path path = Paths.get(runfiles.rlocation("integration_test_repo/src/data.txt")); + assertTrue(Files.exists(path)); + } +} diff --git a/test/repo/src/data.txt b/test/repo/src/data.txt new file mode 100644 index 00000000..e69de29b From 7170aea8bf52d4323342420b416ddbd994175822 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 19 Nov 2024 08:59:02 -0800 Subject: [PATCH 083/465] Release `rules_java` `v8.5.0-rc1` We now use a custom release notes generator because the one from `@rules_pkg` isn't suitable anymore for the new `WORKSPACE` setup PiperOrigin-RevId: 698036411 Change-Id: I73f6d6464c51abae4bbfc87fbfd71732839993f8 --- MODULE.bazel | 2 +- distro/BUILD.bazel | 8 ++------ distro/relnotes.bzl | 46 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 7 deletions(-) create mode 100644 distro/relnotes.bzl diff --git a/MODULE.bazel b/MODULE.bazel index 648c2b2a..f4354ac3 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.4.0", + version = "8.5.0-rc1", bazel_compatibility = [">=6.3.0"], compatibility_level = 1, ) diff --git a/distro/BUILD.bazel b/distro/BUILD.bazel index 0fa843fc..d8722d4f 100644 --- a/distro/BUILD.bazel +++ b/distro/BUILD.bazel @@ -1,5 +1,5 @@ load("@rules_pkg//pkg:tar.bzl", "pkg_tar") -load("@rules_pkg//pkg/releasing:defs.bzl", "print_rel_notes") +load(":relnotes.bzl", "print_rel_notes") package(default_visibility = ["//visibility:private"]) @@ -18,10 +18,6 @@ pkg_tar( print_rel_notes( name = "relnotes", - outs = ["relnotes.txt"], - deps_method = "rules_java_dependencies", - repo = "rules_java", - setup_file = "java:repositories.bzl", - toolchains_method = "rules_java_toolchains", + archive = ":rules_java-%s" % module_version(), version = module_version(), ) diff --git a/distro/relnotes.bzl b/distro/relnotes.bzl new file mode 100644 index 00000000..6cee2e36 --- /dev/null +++ b/distro/relnotes.bzl @@ -0,0 +1,46 @@ +"""Release notes generator""" + +def print_rel_notes(*, name, version, archive): + native.genrule( + name = name, + outs = [name + ".txt"], + cmd = """ + last_rel=$$(curl -s https://api.github.com/repos/bazelbuild/rules_java/releases/latest | grep 'tag_name' | cut -d: -f2 | tr -cd '[:alnum:].') + changelog=$$(/usr/bin/git log tags/$$last_rel..origin/master --format=oneline --) + sha=$$(/usr/bin/sha256sum $(SRCS) | cut -d ' ' -f1) + cat > $@ < Date: Tue, 19 Nov 2024 09:58:01 -0800 Subject: [PATCH 084/465] Release `rules_java` `v8.5.0-rc2` Fixes missing bzl_library target for generating Bazel docs PiperOrigin-RevId: 698054336 Change-Id: I0ae6fe44adbe5e80744875f97b8c958117a0556a --- MODULE.bazel | 2 +- distro/relnotes.bzl | 2 +- java/common/BUILD | 5 ++++- java/rules_java_deps.bzl | 32 +++++++++++++++++++------------- java/toolchains/BUILD | 5 ++++- 5 files changed, 29 insertions(+), 17 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index f4354ac3..087ca9bd 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.5.0-rc1", + version = "8.5.0-rc2", bazel_compatibility = [">=6.3.0"], compatibility_level = 1, ) diff --git a/distro/relnotes.bzl b/distro/relnotes.bzl index 6cee2e36..4200e040 100644 --- a/distro/relnotes.bzl +++ b/distro/relnotes.bzl @@ -9,7 +9,7 @@ def print_rel_notes(*, name, version, archive): changelog=$$(/usr/bin/git log tags/$$last_rel..origin/master --format=oneline --) sha=$$(/usr/bin/sha256sum $(SRCS) | cut -d ' ' -f1) cat > $@ <= "8": rctx.file( "proxy.bzl", """ -load("@rules_java//java/bazel/rules:bazel_java_binary_wrapper.bzl", _java_binary = "java_binary") # copybara-use-repo-external-label -load("@rules_java//java/bazel/rules:bazel_java_import.bzl", _java_import = "java_import") # copybara-use-repo-external-label -load("@rules_java//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") # copybara-use-repo-external-label -load("@rules_java//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") # copybara-use-repo-external-label -load("@rules_java//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") # copybara-use-repo-external-label -load("@rules_java//java/common/rules:java_package_configuration.bzl", _java_package_configuration = "java_package_configuration") # copybara-use-repo-external-label -load("@rules_java//java/common/rules:java_runtime.bzl", _java_runtime = "java_runtime") # copybara-use-repo-external-label -load("@rules_java//java/common/rules:java_toolchain.bzl", _java_toolchain = "java_toolchain") # copybara-use-repo-external-label -load("@rules_java//java/private:java_common.bzl", _java_common = "java_common") # copybara-use-repo-external-label -load("@rules_java//java/private:java_info.bzl", _JavaInfo = "JavaInfo", _JavaPluginInfo = "JavaPluginInfo") # copybara-use-repo-external-label -load("@rules_java//java:http_jar.bzl", _http_jar = "http_jar") # copybara-use-repo-external-label +load("@rules_java//java/bazel/rules:bazel_java_binary_wrapper.bzl", _java_binary = "java_binary") +load("@rules_java//java/bazel/rules:bazel_java_import.bzl", _java_import = "java_import") +load("@rules_java//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") +load("@rules_java//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") +load("@rules_java//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") +load("@rules_java//java/common/rules:java_package_configuration.bzl", _java_package_configuration = "java_package_configuration") +load("@rules_java//java/common/rules:java_runtime.bzl", _java_runtime = "java_runtime") +load("@rules_java//java/common/rules:java_toolchain.bzl", _java_toolchain = "java_toolchain") +load("@rules_java//java/private:java_common.bzl", _java_common = "java_common") +load("@rules_java//java/private:java_info.bzl", _JavaInfo = "JavaInfo", _JavaPluginInfo = "JavaPluginInfo") +load("@rules_java//java:http_jar.bzl", _http_jar = "http_jar") java_binary = _java_binary java_import = _java_import @@ -43,7 +49,7 @@ http_jar = _http_jar "proxy.bzl", """ load("@bazel_tools//tools/build_defs/repo:http.bzl", _http_jar = "http_jar") -load("@rules_java//java/private:native.bzl", "native_java_common", "NativeJavaInfo", "NativeJavaPluginInfo") # copybara-use-repo-external-label +load("@rules_java//java/private:native.bzl", "native_java_common", "NativeJavaInfo", "NativeJavaPluginInfo") java_binary = native.java_binary java_import = native.java_import diff --git a/java/toolchains/BUILD b/java/toolchains/BUILD index 6b0fa913..adcd09a1 100644 --- a/java/toolchains/BUILD +++ b/java/toolchains/BUILD @@ -14,7 +14,10 @@ bzl_library( name = "toolchain_rules", srcs = glob(["*.bzl"]), visibility = ["//visibility:public"], - deps = ["//java/private:native_bzl"], + deps = [ + "//java/private:native_bzl", + "@compatibility_proxy//:proxy_bzl", + ], ) filegroup( From 97a3dfbd300ace45fd2eaceb620a46ecda9378cb Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 20 Nov 2024 00:05:53 -0800 Subject: [PATCH 085/465] Remove top-level usage of native `java_common` in java_toolchain.bzl PiperOrigin-RevId: 698281701 Change-Id: I8cba5638421b0a0d2ff7c95fce132b8135a90aab --- java/common/rules/java_toolchain.bzl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/java/common/rules/java_toolchain.bzl b/java/common/rules/java_toolchain.bzl index 829386f0..2e4fc67e 100644 --- a/java/common/rules/java_toolchain.bzl +++ b/java/common/rules/java_toolchain.bzl @@ -20,12 +20,12 @@ load("//java/common:java_semantics.bzl", "semantics") load("//java/common/rules/impl:java_helper.bzl", "helper") load("//java/private:boot_class_path_info.bzl", "BootClassPathInfo") load("//java/private:java_info.bzl", "JavaPluginDataInfo") +load("//java/private:native.bzl", "get_internal_java_common") load(":java_package_configuration.bzl", "JavaPackageConfigurationInfo") load(":java_runtime.bzl", "JavaRuntimeInfo") # copybara: default visibility -_java_common_internal = java_common.internal_DO_NOT_USE() ToolchainInfo = platform_common.ToolchainInfo def _java_toolchain_info_init(**_kwargs): @@ -99,7 +99,7 @@ def _java_toolchain_impl(ctx): ijar = ctx.attr.ijar.files_to_run if ctx.attr.ijar else None, jacocorunner = ctx.attr.jacocorunner.files_to_run if ctx.attr.jacocorunner else None, java_runtime = java_runtime, - jvm_opt = depset(_java_common_internal.expand_java_opts(ctx, "jvm_opts", tokenize = False, exec_paths = True)), + jvm_opt = depset(get_internal_java_common().expand_java_opts(ctx, "jvm_opts", tokenize = False, exec_paths = True)), label = ctx.label, proguard_allowlister = ctx.attr.proguard_allowlister.files_to_run if ctx.attr.proguard_allowlister else None, single_jar = ctx.attr.singlejar.files_to_run, @@ -164,8 +164,8 @@ def _get_javac_opts(ctx): opts.extend(["-target", ctx.attr.target_version]) if ctx.attr.xlint: opts.append("-Xlint:" + ",".join(ctx.attr.xlint)) - opts.extend(_java_common_internal.expand_java_opts(ctx, "misc", tokenize = True)) - opts.extend(_java_common_internal.expand_java_opts(ctx, "javacopts", tokenize = True)) + opts.extend(get_internal_java_common().expand_java_opts(ctx, "misc", tokenize = True)) + opts.extend(get_internal_java_common().expand_java_opts(ctx, "javacopts", tokenize = True)) return opts def _get_android_lint_tool(ctx): From 349608c3b0fd0bf3856cd0b6acc9e5fe1136714e Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 20 Nov 2024 00:31:19 -0800 Subject: [PATCH 086/465] Release `rules_java` `v8.5.0` PiperOrigin-RevId: 698287380 Change-Id: Iff3d4ece6a475ad6ca221f21bcb189787c1298d1 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 087ca9bd..8452ff81 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.5.0-rc2", + version = "8.5.0", bazel_compatibility = [">=6.3.0"], compatibility_level = 1, ) From f81734bf507bda1e483a3ab42c6a170bf7aa0986 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 20 Nov 2024 04:31:20 -0800 Subject: [PATCH 087/465] Add links to documentation to the rules_java README Fixes https://github.com/bazelbuild/rules_java/issues/80 PiperOrigin-RevId: 698344251 Change-Id: Ibb5361c9aa7013f9a1eca36e0d4cee09c5c62bd3 --- README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/README.md b/README.md index 8c946de5..e4cfeb0b 100644 --- a/README.md +++ b/README.md @@ -4,3 +4,22 @@ * Postsubmit + Current Bazel Incompatible Flags [![Build status](https://badge.buildkite.com/ef265d270238c02aff65106a0b861abb9265efacdf4af399c3.svg?branch=master)](https://buildkite.com/bazel/rules-java-plus-bazelisk-migrate) Java Rules for Bazel https://bazel.build. + +**Documentation** + +For a quickstart tutorial, see https://bazel.build/start/java + +For slightly more advanced usage, like setting up toolchains +or writing your own java-like rules, +see https://bazel.build/docs/bazel-and-java + + +***Core Java rules*** + +Add a load like: +```build +load("@rules_java//java:java_library.bzl", "java_library") +``` +to your `BUILD` / `BUILD.bazel` / bzl` files + +For detailed docs on the core rules, see https://bazel.build/reference/be/java From a22cec1657b9642ebca8c680f3c9fa7e33a8fd01 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 22 Nov 2024 02:51:25 -0800 Subject: [PATCH 088/465] Update `@rules_java` release notes Adds a clarification for correctly registering protobuf deps in `WORKSPACE` mode PiperOrigin-RevId: 699105038 Change-Id: I767f62f645663c684aa944daa1b67f4fd97542f9 --- distro/relnotes.bzl | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/distro/relnotes.bzl b/distro/relnotes.bzl index 4200e040..ba128833 100644 --- a/distro/relnotes.bzl +++ b/distro/relnotes.bzl @@ -30,8 +30,13 @@ http_archive( load("@rules_java//java:rules_java_deps.bzl", "rules_java_dependencies") rules_java_dependencies() + +# note that the following line is what is minimally required from protobuf for the java rules +# consider using the protobuf_deps() public API from @com_google_protobuf//:protobuf_deps.bzl load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_bazel_features") # buildifier: disable=bzl-visibility proto_bazel_features(name = "proto_bazel_features") + +# register toolchains load("@rules_java//java:repositories.bzl", "rules_java_toolchains") rules_java_toolchains() ~~~ From 4bebd03eb863bdf17f6701677f25888196a06181 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 22 Nov 2024 04:47:06 -0800 Subject: [PATCH 089/465] Overhaul `@rules_java` bzl_library dep graph - Construct an accurate `bzl_library` target for the compatibility proxy - Updates `proto_support.bzl` to use the right `java_common` - Work towards fixing https://github.com/bazelbuild/bazel/issues/24455 PiperOrigin-RevId: 699129931 Change-Id: I55f6e744602e3760f69bc197a8f107fd119feee0 --- .bazelci/presubmit.yml | 1 - java/BUILD | 7 ++++++ java/bazel/rules/BUILD.bazel | 3 ++- java/common/BUILD | 24 +++++++++++++++++--- java/common/rules/BUILD | 3 ++- java/common/rules/impl/BUILD | 1 + java/private/BUILD | 12 +++++++--- java/private/proto_support.bzl | 2 +- java/rules_java_deps.bzl | 41 ++++++++++++++++++++++++++++------ java/toolchains/BUILD | 5 +---- test/BUILD.bazel | 6 +++++ 11 files changed, 84 insertions(+), 21 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index be62c01f..efeeef17 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -4,7 +4,6 @@ build_targets: &build_targets - "@remote_java_tools//java_tools/..." # TODO: Look into broken targets in //toolchains - "-//toolchains/..." - - "-//test/repo/..." # TODO: re-enable docs after protobuf is fixed - "-//java/docs/..." - "-//test:docs_up_to_date_test" diff --git a/java/BUILD b/java/BUILD index caacb07e..2074c388 100644 --- a/java/BUILD +++ b/java/BUILD @@ -65,6 +65,13 @@ bzl_library( deps = ["//java/common"], ) +bzl_library( + name = "http_jar_bzl", + srcs = ["http_jar.bzl"], + visibility = ["//visibility:public"], + deps = ["@bazel_tools//tools:bzl_srcs"], +) + filegroup( name = "for_bazel_tests", testonly = 1, diff --git a/java/bazel/rules/BUILD.bazel b/java/bazel/rules/BUILD.bazel index 1ffd8efc..0ffa9d43 100644 --- a/java/bazel/rules/BUILD.bazel +++ b/java/bazel/rules/BUILD.bazel @@ -24,9 +24,10 @@ bzl_library( srcs = glob(["*.bzl"]), visibility = ["//visibility:public"], # for Bazel docgen deps = [ - "//java/common", + "//java/common:semantics_bzl", "//java/common/rules:core_rules", "//java/common/rules/impl", + "//java/private:internals", "@bazel_skylib//lib:paths", "@rules_cc//cc:find_cc_toolchain_bzl", "@rules_cc//cc/common", diff --git a/java/common/BUILD b/java/common/BUILD index ef669cc6..6850cb49 100644 --- a/java/common/BUILD +++ b/java/common/BUILD @@ -14,14 +14,32 @@ filegroup( bzl_library( name = "common", - srcs = glob(["*.bzl"]), + srcs = glob( + ["*.bzl"], + exclude = [ + "java_semantics.bzl", + "proguard_spec_info.bzl", + ], + ), + visibility = ["//visibility:public"], + deps = ["@compatibility_proxy//:proxy_bzl"], +) + +bzl_library( + name = "semantics_bzl", + srcs = ["java_semantics.bzl"], visibility = ["//visibility:public"], deps = [ - "//java/private:internals", - "@compatibility_proxy//:proxy_bzl", + "@rules_cc//cc/common", ], ) +bzl_library( + name = "proguard_spec_info_bzl", + srcs = ["proguard_spec_info.bzl"], + visibility = ["//visibility:public"], +) + filegroup( name = "for_bazel_tests", testonly = 1, diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD index 4ffe015d..9d0678cd 100644 --- a/java/common/rules/BUILD +++ b/java/common/rules/BUILD @@ -38,7 +38,7 @@ bzl_library( deps = [ ":android_lint_bzl", ":rule_util_bzl", - "//java/common", + "//java/private:internals", "@bazel_skylib//lib:paths", "@rules_cc//cc/common", ], @@ -53,6 +53,7 @@ bzl_library( ], visibility = [ "//java:__subpackages__", + "@compatibility_proxy//:__pkg__", ], ) diff --git a/java/common/rules/impl/BUILD b/java/common/rules/impl/BUILD index fc962030..f50862c4 100644 --- a/java/common/rules/impl/BUILD +++ b/java/common/rules/impl/BUILD @@ -17,6 +17,7 @@ bzl_library( visibility = ["//java:__subpackages__"], deps = [ ":java_helper_bzl", + "//java/common:proguard_spec_info_bzl", "@com_google_protobuf//bazel/common:proto_info_bzl", ], ) diff --git a/java/private/BUILD b/java/private/BUILD index af9edbec..94bae8da 100644 --- a/java/private/BUILD +++ b/java/private/BUILD @@ -7,7 +7,10 @@ bzl_library( srcs = [ "native.bzl", ], - visibility = ["//java:__subpackages__"], + visibility = [ + "//java:__subpackages__", + "@compatibility_proxy//:__pkg__", + ], ) bzl_library( @@ -19,7 +22,10 @@ bzl_library( "java_info.bzl", "message_bundle_info.bzl", ], - visibility = ["//java:__subpackages__"], + visibility = [ + "//java:__subpackages__", + "@compatibility_proxy//:__pkg__", + ], deps = [ ":native_bzl", "//java/common/rules:toolchain_rules", @@ -35,7 +41,7 @@ bzl_library( name = "proto_support", srcs = ["proto_support.bzl"], visibility = ["//visibility:public"], - deps = [":native_bzl"], + deps = ["@compatibility_proxy//:proxy_bzl"], ) filegroup( diff --git a/java/private/proto_support.bzl b/java/private/proto_support.bzl index dcb8f09d..dff978b9 100644 --- a/java/private/proto_support.bzl +++ b/java/private/proto_support.bzl @@ -13,7 +13,7 @@ # limitations under the License. """Support for Java compilation of protocol buffer generated code.""" -load("//java/common:java_common.bzl", "java_common") +load("@compatibility_proxy//:proxy.bzl", "java_common") # Partial support, because internal symbols are not available in older Bazel version # TODO: Once Java rules are moved into the rules_java, this should become a full support. diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl index 8ed58579..026ed4f6 100644 --- a/java/rules_java_deps.bzl +++ b/java/rules_java_deps.bzl @@ -6,14 +6,25 @@ load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") def _compatibility_proxy_repo_impl(rctx): # TODO: use @bazel_features bazel = native.bazel_version - rctx.file( - "BUILD.bazel", - """ -load("@bazel_skylib//:bzl_library.bzl", "bzl_library") -bzl_library(name = "proxy_bzl", srcs = ["proxy.bzl"], visibility = ["//visibility:public"]) - """, - ) if not bazel or bazel >= "8": + rctx.file( + "BUILD.bazel", + """ +load("@bazel_skylib//:bzl_library.bzl", "bzl_library") +exports_files(['proxy.bzl'], visibility = ["@rules_java//test:__pkg__"]) +bzl_library( + name = "proxy_bzl", + srcs = ["proxy.bzl"], + deps = [ + "@rules_java//java/bazel/rules", + "@rules_java//java/common/rules:toolchain_rules", + "@rules_java//java/private:internals", + "@rules_java//java:http_jar_bzl", + ], + visibility = ["//visibility:public"] +) + """, + ) rctx.file( "proxy.bzl", """ @@ -45,6 +56,22 @@ http_jar = _http_jar """, ) else: + rctx.file( + "BUILD.bazel", + """ +load("@bazel_skylib//:bzl_library.bzl", "bzl_library") +exports_files(['proxy.bzl'], visibility = ["@rules_java//test:__pkg__"]) +bzl_library( + name = "proxy_bzl", + srcs = ["proxy.bzl"], + deps = [ + "@rules_java//java/private:native_bzl", + "@bazel_tools//tools:bzl_srcs", + ], + visibility = ["//visibility:public"] +) + """, + ) rctx.file( "proxy.bzl", """ diff --git a/java/toolchains/BUILD b/java/toolchains/BUILD index adcd09a1..29a572a0 100644 --- a/java/toolchains/BUILD +++ b/java/toolchains/BUILD @@ -14,10 +14,7 @@ bzl_library( name = "toolchain_rules", srcs = glob(["*.bzl"]), visibility = ["//visibility:public"], - deps = [ - "//java/private:native_bzl", - "@compatibility_proxy//:proxy_bzl", - ], + deps = ["@compatibility_proxy//:proxy_bzl"], ) filegroup( diff --git a/test/BUILD.bazel b/test/BUILD.bazel index 00506f87..c9dd65b9 100644 --- a/test/BUILD.bazel +++ b/test/BUILD.bazel @@ -60,3 +60,9 @@ diff_test( ) validate_configs() + +starlark_doc_extract( + name = "proxy_bzl_graph", + src = "@compatibility_proxy//:proxy.bzl", + deps = ["@compatibility_proxy//:proxy_bzl"], +) From 5890537bfb4810132c698b4d4fde85e68181b617 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 22 Nov 2024 04:52:24 -0800 Subject: [PATCH 090/465] Release `@rules_java` `v8.5.1` PiperOrigin-RevId: 699131190 Change-Id: I23257dcb7e3e141d6fb2b568e22adda1046a5378 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 8452ff81..706c2775 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.5.0", + version = "8.5.1", bazel_compatibility = [">=6.3.0"], compatibility_level = 1, ) From c81497b5f8a56141edfe499d9bc63391c93f3492 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 25 Nov 2024 04:03:08 -0800 Subject: [PATCH 091/465] Add back `bzl_library` deps to `@rules_java//java/common` for maintaining backwards compatibility This has been worked around in Bazel docgen for now, so another release isn't necessary. PiperOrigin-RevId: 699926443 Change-Id: I471957a2231bd821d470715090ce3ed49f48e1f0 --- java/common/BUILD | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/java/common/BUILD b/java/common/BUILD index 6850cb49..a06a2f37 100644 --- a/java/common/BUILD +++ b/java/common/BUILD @@ -22,7 +22,11 @@ bzl_library( ], ), visibility = ["//visibility:public"], - deps = ["@compatibility_proxy//:proxy_bzl"], + deps = [ + ":proguard_spec_info_bzl", + ":semantics_bzl", + "@compatibility_proxy//:proxy_bzl", + ], ) bzl_library( From 6b37b158868eaf07f0d2b0e0219f8ae87f5aca39 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 26 Nov 2024 06:30:09 -0800 Subject: [PATCH 092/465] Rename `rules_java` runfiles package `BUILD.bazel` -> `BUILD` Work towards https://github.com/bazelbuild/bazel/pull/24394 PiperOrigin-RevId: 700322638 Change-Id: Ic8af8b0bb8ad82f0e89c87b3ccb84d44b89067c5 --- java/runfiles/{BUILD.bazel => BUILD} | 0 .../com/google/devtools/build/runfiles/{BUILD.bazel => BUILD} | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename java/runfiles/{BUILD.bazel => BUILD} (100%) rename java/runfiles/src/main/java/com/google/devtools/build/runfiles/{BUILD.bazel => BUILD} (90%) diff --git a/java/runfiles/BUILD.bazel b/java/runfiles/BUILD similarity index 100% rename from java/runfiles/BUILD.bazel rename to java/runfiles/BUILD diff --git a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD.bazel b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD similarity index 90% rename from java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD.bazel rename to java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD index a2563d9d..ee1bd83a 100644 --- a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD.bazel +++ b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD @@ -1,4 +1,4 @@ -load("@rules_java//java:defs.bzl", "java_library", "java_plugin") +load("//java:defs.bzl", "java_library", "java_plugin") java_library( name = "runfiles", From c22454fadb4773cbd202bfa3e28f1d6a88c4c94a Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Wed, 27 Nov 2024 07:28:44 -0800 Subject: [PATCH 093/465] Build bootclasspath in a UTF-8 environment Copybara Import from https://github.com/bazelbuild/rules_java/pull/243 BEGIN_PUBLIC Build bootclasspath in a UTF-8 environment (#243) `java` and `javac` convert file and classpaths to absolute paths and thus require a UTF-8 locale to work under a path that contains non-ASCII characters. Unblocks https://github.com/bazelbuild/bazel/pull/24457 Closes #243 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/243 from fmeum:utf8-environment 05813e491f73a167bf5c7d5e723d2417649f3867 PiperOrigin-RevId: 700695134 Change-Id: I2f5753720ec3c838a4dd8b6aabf1050c6935ef3d --- MODULE.bazel | 1 + WORKSPACE | 7 ++++ test/analysis/BUILD.bazel | 5 +++ test/analysis/bootclasspath_tests.bzl | 25 ++++++++++++++ toolchains/BUILD | 6 ++++ toolchains/default_java_toolchain.bzl | 8 +++++ toolchains/utf8_environment.bzl | 48 +++++++++++++++++++++++++++ 7 files changed, 100 insertions(+) create mode 100644 test/analysis/BUILD.bazel create mode 100644 test/analysis/bootclasspath_tests.bzl create mode 100644 toolchains/utf8_environment.bzl diff --git a/MODULE.bazel b/MODULE.bazel index 706c2775..b14fcbf3 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -97,6 +97,7 @@ use_repo(compat, "compatibility_proxy") bazel_dep(name = "rules_pkg", version = "0.9.1", dev_dependency = True) bazel_dep(name = "stardoc", version = "0.7.1", dev_dependency = True) bazel_dep(name = "rules_shell", version = "0.2.0", dev_dependency = True) +bazel_dep(name = "rules_testing", version = "0.7.0", dev_dependency = True) test_repositories = use_extension("//test:repositories.bzl", "test_repositories_ext", dev_dependency = True) use_repo(test_repositories, "guava", "truth") diff --git a/WORKSPACE b/WORKSPACE index d5e6a7e7..161fa9cc 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -53,6 +53,13 @@ load("@stardoc//:setup.bzl", "stardoc_repositories") stardoc_repositories() +http_archive( + name = "rules_testing", + sha256 = "28c2d174471b587bf0df1fd3a10313f22c8906caf4050f8b46ec4648a79f90c3", + strip_prefix = "rules_testing-0.7.0", + url = "https://github.com/bazelbuild/rules_testing/releases/download/v0.7.0/rules_testing-v0.7.0.tar.gz", +) + load("//test:repositories.bzl", "test_repositories") test_repositories() diff --git a/test/analysis/BUILD.bazel b/test/analysis/BUILD.bazel new file mode 100644 index 00000000..754e1dd4 --- /dev/null +++ b/test/analysis/BUILD.bazel @@ -0,0 +1,5 @@ +load(":bootclasspath_tests.bzl", "bootclasspath_tests") + +bootclasspath_tests( + name = "bootclasspath_tests", +) diff --git a/test/analysis/bootclasspath_tests.bzl b/test/analysis/bootclasspath_tests.bzl new file mode 100644 index 00000000..c862d836 --- /dev/null +++ b/test/analysis/bootclasspath_tests.bzl @@ -0,0 +1,25 @@ +"""Tests for the bootclasspath rule.""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "subjects") + +def _test_utf_8_environment(name): + analysis_test( + name = name, + impl = _test_utf_8_environment_impl, + target = Label("//toolchains:platformclasspath"), + ) + +def _test_utf_8_environment_impl(env, target): + for action in target.actions: + env_subject = env.expect.where(action = action).that_dict(action.env) + env_subject.keys().contains("LC_CTYPE") + env_subject.get("LC_CTYPE", factory = subjects.str).contains("UTF-8") + +def bootclasspath_tests(name): + test_suite( + name = name, + tests = [ + _test_utf_8_environment, + ], + ) diff --git a/toolchains/BUILD b/toolchains/BUILD index 191c3115..ffbffc47 100644 --- a/toolchains/BUILD +++ b/toolchains/BUILD @@ -15,6 +15,7 @@ load( "java_runtime_version_alias", "java_toolchain_alias", ) +load(":utf8_environment.bzl", "utf8_environment") package(default_visibility = ["//visibility:public"]) @@ -282,6 +283,11 @@ alias( }), ) +utf8_environment( + name = "utf8_environment", + visibility = ["//visibility:private"], +) + bootclasspath( name = "platformclasspath", src = "DumpPlatformClassPath.java", diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl index a6d200b7..75d05f7b 100644 --- a/toolchains/default_java_toolchain.bzl +++ b/toolchains/default_java_toolchain.bzl @@ -16,6 +16,7 @@ load("//java/common:java_common.bzl", "java_common") load("//java/toolchains:java_toolchain.bzl", "java_toolchain") +load(":utf8_environment.bzl", "Utf8EnvironmentInfo") # JVM options, without patching java.compiler and jdk.compiler modules. BASE_JDK9_JVM_OPTS = [ @@ -223,6 +224,7 @@ def _java_home(java_executable): def _bootclasspath_impl(ctx): exec_javabase = ctx.attr.java_runtime_alias[java_common.JavaRuntimeInfo] + env = ctx.attr._utf8_environment[Utf8EnvironmentInfo].environment class_dir = ctx.actions.declare_directory("%s_classes" % ctx.label.name) @@ -243,6 +245,7 @@ def _bootclasspath_impl(ctx): inputs = [ctx.file.src] + ctx.files.java_runtime_alias, outputs = [class_dir], arguments = [args], + env = env, execution_requirements = _SUPPORTS_PATH_MAPPING, ) @@ -281,6 +284,7 @@ def _bootclasspath_impl(ctx): inputs = inputs, outputs = [bootclasspath], arguments = [args], + env = env, execution_requirements = _SUPPORTS_PATH_MAPPING, ) return [ @@ -304,6 +308,10 @@ _bootclasspath = rule( cfg = "exec", allow_single_file = True, ), + "_utf8_environment": attr.label( + default = ":utf8_environment", + cfg = "exec", + ), }, toolchains = [_JAVA_BOOTSTRAP_RUNTIME_TOOLCHAIN_TYPE], ) diff --git a/toolchains/utf8_environment.bzl b/toolchains/utf8_environment.bzl new file mode 100644 index 00000000..5b4d5545 --- /dev/null +++ b/toolchains/utf8_environment.bzl @@ -0,0 +1,48 @@ +# 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. + +""" +Determines the environment required for Java actions to support UTF-8. +""" + +visibility("private") + +Utf8EnvironmentInfo = provider( + doc = "The environment required for Java actions to support UTF-8.", + fields = { + "environment": "The environment to use for Java actions to support UTF-8.", + }, +) + +# The default UTF-8 locale on all recent Linux distributions. It is also available in Cygwin and +# MSYS2, but doesn't matter for determining the JVM's platform encoding on Windows, which always +# uses the active code page. +_DEFAULT_UTF8_ENVIRONMENT = Utf8EnvironmentInfo(environment = {"LC_CTYPE": "C.UTF-8"}) + +# macOS doesn't have the C.UTF-8 locale, but en_US.UTF-8 is available and works the same way. +_MACOS_UTF8_ENVIRONMENT = Utf8EnvironmentInfo(environment = {"LC_CTYPE": "en_US.UTF-8"}) + +def _utf8_environment_impl(ctx): + if ctx.target_platform_has_constraint(ctx.attr._macos_constraint[platform_common.ConstraintValueInfo]): + return _MACOS_UTF8_ENVIRONMENT + else: + return _DEFAULT_UTF8_ENVIRONMENT + +utf8_environment = rule( + _utf8_environment_impl, + attrs = { + "_macos_constraint": attr.label(default = "@platforms//os:macos"), + }, + doc = "Returns a suitable environment for Java actions to support UTF-8.", +) From a04ab3cdf4ea1d114946faf24529c5d0bb03b46a Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 3 Dec 2024 00:45:10 -0800 Subject: [PATCH 094/465] Remove `java_binary.classlist` PiperOrigin-RevId: 702233460 Change-Id: I008dbf4d484b03d484ebc6882634191e7a72461c --- .../common/rules/impl/java_binary_deploy_jar.bzl | 16 ++++------------ java/common/rules/java_runtime.bzl | 6 ++---- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/java/common/rules/impl/java_binary_deploy_jar.bzl b/java/common/rules/impl/java_binary_deploy_jar.bzl index 6df08cbf..8755d959 100644 --- a/java/common/rules/impl/java_binary_deploy_jar.bzl +++ b/java/common/rules/impl/java_binary_deploy_jar.bzl @@ -38,7 +38,6 @@ def create_deploy_archives( hermetic = False, add_exports = depset(), add_opens = depset(), - shared_archive = None, one_version_level = "OFF", one_version_allowlist = None, extra_args = [], @@ -55,7 +54,6 @@ def create_deploy_archives( hermetic: (bool) add_exports: (depset) add_opens: (depset) - shared_archive: (File) Optional .jsa artifact one_version_level: (String) Optional one version check level, default OFF one_version_allowlist: (File) Optional allowlist for one version check extra_args: (list[Args]) Optional arguments for the deploy jar action @@ -87,7 +85,6 @@ def create_deploy_archives( build_info_files, build_target, output = ctx.outputs.deployjar, - shared_archive = shared_archive, one_version_level = one_version_level, one_version_allowlist = one_version_allowlist, multi_release = multi_release, @@ -131,7 +128,6 @@ def create_deploy_archive( build_info_files, build_target, output, - shared_archive = None, one_version_level = "OFF", one_version_allowlist = None, multi_release = False, @@ -156,7 +152,6 @@ def create_deploy_archive( build_info_files: (list[File]) build info files for stamping build_target: (String) the owner build target label name string output: (File) the output jar artifact - shared_archive: (File) Optional .jsa artifact one_version_level: (String) Optional one version check level, default OFF one_version_allowlist: (File) Optional allowlist for one version check multi_release: (bool) @@ -217,18 +212,15 @@ def create_deploy_archive( java_home = runtime.java_home lib_modules = runtime.lib_modules hermetic_files = runtime.hermetic_files + default_cds = runtime.default_cds args.add("--hermetic_java_home", java_home) args.add("--jdk_lib_modules", lib_modules) args.add_all("--resources", hermetic_files) input_files.append(lib_modules) transitive_input_files.append(hermetic_files) - - if shared_archive == None: - shared_archive = runtime.default_cds - - if shared_archive: - input_files.append(shared_archive) - args.add("--cds_archive", shared_archive) + if default_cds: + input_files.append(default_cds) + args.add("--cds_archive", default_cds) args.add_all("--add_exports", add_exports) args.add_all("--add_opens", add_opens) diff --git a/java/common/rules/java_runtime.bzl b/java/common/rules/java_runtime.bzl index fa0bd52b..52b13013 100644 --- a/java/common/rules/java_runtime.bzl +++ b/java/common/rules/java_runtime.bzl @@ -184,10 +184,8 @@ java_runtime( cfg = "target", doc = """ Default CDS archive for hermetic java_runtime. When hermetic -is enabled for a java_binary target and if the target does not -provide its own CDS archive by specifying the -classlist attribute, -the java_runtime default CDS is packaged in the hermetic deploy JAR. +is enabled for a java_binary target the java_runtime +default CDS is packaged in the hermetic deploy JAR. """, ), "hermetic_srcs": attr.label_list( From 4206c536c77c4f1ec9a918987d31a3c528e5c0b4 Mon Sep 17 00:00:00 2001 From: hvadehra Date: Tue, 3 Dec 2024 02:29:13 -0800 Subject: [PATCH 095/465] Revert `bootstrap_runtime_toolchain_type` changes Copybara Import from https://github.com/bazelbuild/rules_java/pull/246 BEGIN_PUBLIC Revert `bootstrap_runtime_toolchain_type` changes (#246) This reverts the relevant bits from bcc506228f3ac2c6a811c3414329d8727883685e and 30ecf3ff. The minimum supported Bazel version is now 6.4.0 which includes the type in `@bazel_tools`. Closes #246 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/246 from bazelbuild:hvd_tests_for_bootclasspath b666dc289edac950f006b81452193a4dcc91592a PiperOrigin-RevId: 702260069 Change-Id: Ie64994873a7b5609d4fb8b12a2472c82eb71493b --- .bazelci/presubmit.yml | 8 ++++---- MODULE.bazel | 2 +- test/repo/BUILD.bazel | 1 + test/repo/WORKSPACE | 2 ++ toolchains/BUILD | 4 ++-- toolchains/default_java_toolchain.bzl | 2 +- toolchains/local_java_repository.bzl | 4 ++-- toolchains/remote_java_repository.bzl | 2 +- 8 files changed, 14 insertions(+), 11 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index efeeef17..0f796c9b 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -120,12 +120,12 @@ tasks: # Bazel 6.x ubuntu2004_bazel6: name: "Bazel 6.x" - bazel: 6.3.0 + bazel: 6.4.0 platform: ubuntu2004 build_targets: *build_targets_bazel6 ubuntu2004_integration_bazel6: name: "Bazel 6.x Integration" - bazel: 6.3.0 + bazel: 6.4.0 platform: ubuntu2004 working_directory: "test/repo" shell_commands: @@ -137,11 +137,11 @@ tasks: - "//:MyTest" macos_bazel6: name: "Bazel 6.x" - bazel: 6.3.0 + bazel: 6.4.0 platform: macos build_targets: *build_targets_bazel6 windows_bazel6: name: "Bazel 6.x" - bazel: 6.3.0 + bazel: 6.4.0 platform: windows build_targets: *build_targets_bazel6 diff --git a/MODULE.bazel b/MODULE.bazel index b14fcbf3..bf7568dd 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,7 +1,7 @@ module( name = "rules_java", version = "8.5.1", - bazel_compatibility = [">=6.3.0"], + bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) diff --git a/test/repo/BUILD.bazel b/test/repo/BUILD.bazel index c1482dac..7f6887a9 100644 --- a/test/repo/BUILD.bazel +++ b/test/repo/BUILD.bazel @@ -26,4 +26,5 @@ java_test( default_java_toolchain( name = "my_funky_toolchain", + bootclasspath = ["@bazel_tools//tools/jdk:platformclasspath"], ) diff --git a/test/repo/WORKSPACE b/test/repo/WORKSPACE index aa3b7cba..1a135b61 100644 --- a/test/repo/WORKSPACE +++ b/test/repo/WORKSPACE @@ -13,6 +13,8 @@ load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_baze proto_bazel_features(name = "proto_bazel_features") +register_toolchains("//:all") + load("@rules_java//java:repositories.bzl", "rules_java_toolchains") rules_java_toolchains() diff --git a/toolchains/BUILD b/toolchains/BUILD index ffbffc47..e7f4d84b 100644 --- a/toolchains/BUILD +++ b/toolchains/BUILD @@ -67,8 +67,8 @@ filegroup( # # Toolchains of this type are only consumed internally by the bootclasspath rule and should not be # accessed from Starlark. - -toolchain_type(name = "bootstrap_runtime_toolchain_type") +# TODO: migrate away from using @bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type ? +# toolchain_type(name = "bootstrap_runtime_toolchain_type") # Points to toolchain[":runtime_toolchain_type"] (was :legacy_current_java_runtime) java_runtime_alias(name = "current_java_runtime") diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl index 75d05f7b..5aaa06bf 100644 --- a/toolchains/default_java_toolchain.bzl +++ b/toolchains/default_java_toolchain.bzl @@ -213,7 +213,7 @@ def java_runtime_files(name, srcs): tags = ["manual"], ) -_JAVA_BOOTSTRAP_RUNTIME_TOOLCHAIN_TYPE = Label("//toolchains:bootstrap_runtime_toolchain_type") +_JAVA_BOOTSTRAP_RUNTIME_TOOLCHAIN_TYPE = Label("@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type") # Opt the Java bootstrap actions into path mapping: # https://github.com/bazelbuild/bazel/commit/a239ea84832f18ee8706682145e9595e71b39680 diff --git a/toolchains/local_java_repository.bzl b/toolchains/local_java_repository.bzl index 17b1a0e7..627f8ab8 100644 --- a/toolchains/local_java_repository.bzl +++ b/toolchains/local_java_repository.bzl @@ -110,7 +110,7 @@ def local_java_runtime(name, java_home, version, runtime_name = None, visibility native.toolchain( name = "bootstrap_runtime_toolchain_definition", target_settings = [":%s_settings_alias" % name], - toolchain_type = Label("//toolchains:bootstrap_runtime_toolchain_type"), + toolchain_type = Label("@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type"), toolchain = runtime_name, ) @@ -268,7 +268,7 @@ toolchain( toolchain( name = "bootstrap_runtime_toolchain_definition", target_settings = [":localjdk_setting"], - toolchain_type = "@rules_java//toolchains:bootstrap_runtime_toolchain_type", + toolchain_type = "@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type", toolchain = ":jdk", ) ''' diff --git a/toolchains/remote_java_repository.bzl b/toolchains/remote_java_repository.bzl index a2535d3c..65bbe482 100644 --- a/toolchains/remote_java_repository.bzl +++ b/toolchains/remote_java_repository.bzl @@ -89,7 +89,7 @@ toolchain( # the same configuration, this constraint will not result in toolchain resolution failures. exec_compatible_with = {target_compatible_with}, target_settings = [":version_or_prefix_version_setting"], - toolchain_type = "@rules_java//toolchains:bootstrap_runtime_toolchain_type", + toolchain_type = "@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type", toolchain = "{toolchain}", ) """.format( From 36a3669567bcc488938ac87055fdca95b6813a7f Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 3 Dec 2024 02:44:58 -0800 Subject: [PATCH 096/465] Release `@rules_java` `v8.6.0` PiperOrigin-RevId: 702263733 Change-Id: I1dfbee5d302ed33eb5d3ea4c3edfb293bf205c00 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index bf7568dd..4f03a735 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.5.1", + version = "8.6.0", bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) From 934c1b27c650ed160d7658c214d0318073ff49c8 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 3 Dec 2024 22:18:50 -0800 Subject: [PATCH 097/465] Fix `proto_support.bzl` for Bazel Work towards https://github.com/bazelbuild/bazel/issues/24543 PiperOrigin-RevId: 702587292 Change-Id: I5feb477d86c059008ed78b58588a7a6fe7976e20 --- java/common/rules/basic_java_library.bzl | 4 +-- .../rules/impl/basic_java_library_impl.bzl | 4 +-- java/private/java_common_internal.bzl | 4 +-- java/private/proto_support.bzl | 28 +++++++++++++------ java/rules_java_deps.bzl | 8 ++++-- 5 files changed, 29 insertions(+), 19 deletions(-) diff --git a/java/common/rules/basic_java_library.bzl b/java/common/rules/basic_java_library.bzl index f55351e1..74b43762 100644 --- a/java/common/rules/basic_java_library.bzl +++ b/java/common/rules/basic_java_library.bzl @@ -21,9 +21,7 @@ load("//java/private:java_common.bzl", "java_common") load("//java/private:java_info.bzl", "JavaPluginInfo") load(":rule_util.bzl", "merge_attrs") -visibility([ - "//java/...", -]) +# copybara: default multiline visibility BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS = merge_attrs( { diff --git a/java/common/rules/impl/basic_java_library_impl.bzl b/java/common/rules/impl/basic_java_library_impl.bzl index da5b2bc7..35b1edd1 100644 --- a/java/common/rules/impl/basic_java_library_impl.bzl +++ b/java/common/rules/impl/basic_java_library_impl.bzl @@ -24,9 +24,7 @@ load("//java/private:java_info.bzl", "JavaInfo", "JavaPluginInfo") load(":compile_action.bzl", "compile_action") load(":proguard_validation.bzl", "validate_proguard_specs") -visibility([ - "//java/...", -]) +# copybara: default multiline visibility def _filter_srcs(srcs, ext): return [f for f in srcs if f.extension == ext] diff --git a/java/private/java_common_internal.bzl b/java/private/java_common_internal.bzl index 78a8ee2c..d7402555 100644 --- a/java/private/java_common_internal.bzl +++ b/java/private/java_common_internal.bzl @@ -27,9 +27,7 @@ load( ) load(":native.bzl", "get_internal_java_common") -visibility([ - "//java/...", -]) +# copybara: default multiline visibility def compile( ctx, diff --git a/java/private/proto_support.bzl b/java/private/proto_support.bzl index dff978b9..957dc31f 100644 --- a/java/private/proto_support.bzl +++ b/java/private/proto_support.bzl @@ -13,13 +13,25 @@ # limitations under the License. """Support for Java compilation of protocol buffer generated code.""" -load("@compatibility_proxy//:proxy.bzl", "java_common") +load("@compatibility_proxy//:proxy.bzl", "java_common", "java_common_internal_compile", "java_info_internal_merge") -# Partial support, because internal symbols are not available in older Bazel version -# TODO: Once Java rules are moved into the rules_java, this should become a full support. +def compile(*, injecting_rule_kind, enable_jspecify, include_compilation_info, **kwargs): + if java_common_internal_compile: + return java_common_internal_compile( + injecting_rule_kind = injecting_rule_kind, + enable_jspecify = enable_jspecify, + include_compilation_info = include_compilation_info, + **kwargs + ) + else: + return java_common.compile(**kwargs) -def compile(*, injecting_rule_kind, enable_jspecify, include_compilation_info, **kwargs): # buildifier: disable=unused-variable - return java_common.compile(**kwargs) - -def merge(providers, *, merge_java_outputs = True, merge_source_jars = True): # buildifier: disable=unused-variable - return java_common.merge(providers) +def merge(providers, *, merge_java_outputs = True, merge_source_jars = True): + if java_info_internal_merge: + return java_info_internal_merge( + providers, + merge_java_outputs = merge_java_outputs, + merge_source_jars = merge_source_jars, + ) + else: + return java_common.merge(providers) diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl index 026ed4f6..9e7fd807 100644 --- a/java/rules_java_deps.bzl +++ b/java/rules_java_deps.bzl @@ -37,7 +37,8 @@ load("@rules_java//java/common/rules:java_package_configuration.bzl", _java_pack load("@rules_java//java/common/rules:java_runtime.bzl", _java_runtime = "java_runtime") load("@rules_java//java/common/rules:java_toolchain.bzl", _java_toolchain = "java_toolchain") load("@rules_java//java/private:java_common.bzl", _java_common = "java_common") -load("@rules_java//java/private:java_info.bzl", _JavaInfo = "JavaInfo", _JavaPluginInfo = "JavaPluginInfo") +load("@rules_java//java/private:java_common_internal.bzl", _java_common_internal_compile = "compile") +load("@rules_java//java/private:java_info.bzl", _JavaInfo = "JavaInfo", _JavaPluginInfo = "JavaPluginInfo", _java_info_internal_merge = "merge") load("@rules_java//java:http_jar.bzl", _http_jar = "http_jar") java_binary = _java_binary @@ -51,7 +52,8 @@ java_toolchain = _java_toolchain java_common = _java_common JavaInfo = _JavaInfo JavaPluginInfo = _JavaPluginInfo - +java_common_internal_compile = _java_common_internal_compile +java_info_internal_merge = _java_info_internal_merge http_jar = _http_jar """, ) @@ -91,6 +93,8 @@ java_toolchain = native.java_toolchain java_common = native_java_common JavaInfo = NativeJavaInfo JavaPluginInfo = NativeJavaPluginInfo +java_common_internal_compile = None +java_info_internal_merge = None http_jar = _http_jar """, From 2847c0e26f1ee9944f3c1645705c6a2e16c43f13 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 4 Dec 2024 01:51:00 -0800 Subject: [PATCH 098/465] Release `@rules_java` `v8.6.1` PiperOrigin-RevId: 702636059 Change-Id: Ie5369ac756e693361236006fa62248f4813f4e71 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 4f03a735..82f05136 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.6.0", + version = "8.6.1", bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) From 084b75a46739eb531aa3da9ab9fe52c8d44b7b34 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 4 Dec 2024 09:50:48 -0800 Subject: [PATCH 099/465] Remove duplication in `@rules_java` presubmit config Brings all configs in sync PiperOrigin-RevId: 702759908 Change-Id: I30848733e3a279a6622a751d4011f08a05bc01f7 --- .bazelci/presubmit.yml | 80 ++++++++++++++++++------------------------ 1 file changed, 35 insertions(+), 45 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 0f796c9b..d61be6c1 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -2,9 +2,9 @@ build_targets: &build_targets - "//..." - "@remote_java_tools//java_tools/..." - # TODO: Look into broken targets in //toolchains + # can't build @remote_java_tools_X repos for other platforms - "-//toolchains/..." - # TODO: re-enable docs after protobuf is fixed + # TODO: re-enable docs after moving them out of https://bazel.build/reference/be/java - "-//java/docs/..." - "-//test:docs_up_to_date_test" @@ -13,9 +13,25 @@ build_targets_bazel6: &build_targets_bazel6 - "@remote_java_tools//java_tools/..." - "//examples/..." +build_targets_integration: &build_targets_integration + - "//..." + - "//:bin_deploy.jar" + test_targets: &test_targets - "//test/..." - "//java/test/..." + # TODO: re-enable docs after moving them out of https://bazel.build/reference/be/java + - "-//test:docs_up_to_date_test" + +test_targets_bazel6: &test_targets_bazel6 + - "//java/test/..." + +test_target_integration: &test_target_integration + - "//:MyTest" + +flags_workspace_integration: &flags_workspace_integration + - "--noenable_bzlmod" + - "--enable_workspace" buildifier: latest @@ -26,10 +42,7 @@ tasks: name: "Bazel 7.x" bazel: "7.4.0" build_targets: *build_targets - test_targets: - - "//test/..." - - "//java/test/..." - - "-//test:docs_up_to_date_test" + test_targets: *test_targets ubuntu2004_integration: name: "Bazel 7.x Integration" bazel: "7.4.0" @@ -37,12 +50,8 @@ tasks: working_directory: "test/repo" shell_commands: - sh setup.sh - build_targets: - - "//..." - - "//:bin_deploy.jar" - - "@rules_java//java/..." - test_targets: - - "//:MyTest" + build_targets: *build_targets_integration + test_targets: *test_target_integration ubuntu2004_integration_workspace: name: "Bazel 7.x Integration (WORKSPACE)" bazel: "7.4.0" @@ -50,17 +59,10 @@ tasks: working_directory: "test/repo" shell_commands: - sh setup.sh - build_targets: - - "//..." - - "//:bin_deploy.jar" - build_flags: - - "--noenable_bzlmod" - - "--enable_workspace" - test_targets: - - "//:MyTest" - test_flags: - - "--noenable_bzlmod" - - "--enable_workspace" + build_targets: *build_targets_integration + build_flags: *flags_workspace_integration + test_targets: *test_target_integration + test_flags: *flags_workspace_integration macos: name: "Bazel 7.x" bazel: "7.4.0" @@ -75,6 +77,7 @@ tasks: bazel: last_green platform: ubuntu2004 build_targets: *build_targets + test_targets: *test_targets ubuntu2004_integration_head: name: "Bazel@HEAD Integration" bazel: last_green @@ -82,12 +85,8 @@ tasks: working_directory: "test/repo" shell_commands: - sh setup.sh - build_targets: - - "//..." - - "//:bin_deploy.jar" - - "@rules_java//java/..." - test_targets: - - "//:MyTest" + build_targets: *build_targets_integration + test_targets: *test_target_integration ubuntu2004_integration_head_workspace: name: "Bazel@HEAD Integration (WORKSPACE)" bazel: "last_green" @@ -95,17 +94,10 @@ tasks: working_directory: "test/repo" shell_commands: - sh setup.sh - build_targets: - - "//..." - - "//:bin_deploy.jar" - build_flags: - - "--noenable_bzlmod" - - "--enable_workspace" - test_targets: - - "//:MyTest" - test_flags: - - "--noenable_bzlmod" - - "--enable_workspace" + build_targets: *build_targets_integration + build_flags: *flags_workspace_integration + test_targets: *test_target_integration + test_flags: *flags_workspace_integration macos_head: name: "Bazel@HEAD" bazel: last_green @@ -123,6 +115,7 @@ tasks: bazel: 6.4.0 platform: ubuntu2004 build_targets: *build_targets_bazel6 + test_targets: *test_targets_bazel6 ubuntu2004_integration_bazel6: name: "Bazel 6.x Integration" bazel: 6.4.0 @@ -130,11 +123,8 @@ tasks: working_directory: "test/repo" shell_commands: - sh setup.sh - build_targets: - - "//..." - - "//:bin_deploy.jar" - test_targets: - - "//:MyTest" + build_targets: *build_targets_integration + test_targets: *test_target_integration macos_bazel6: name: "Bazel 6.x" bazel: 6.4.0 From fd9e39ccf44f249f88452f4f1b6ea7ec0ba3ed21 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 5 Dec 2024 03:37:13 -0800 Subject: [PATCH 100/465] Make `@rules_java//java:http_jar.bzl` compatible with Bazel 6 We achieve this by using a redirect via the `compatibility_proxy` repo, which either invokes the rules-java-local http_jar in java/bazel/http_jar (for Bazel 8), or falls back to the one in `@bazel_tools` (for Bazel < 8). This also allows dropping the workaround in the integration test `WORKSPACE` setup, which proves this is WAI :) PiperOrigin-RevId: 703053887 Change-Id: Ifb7fbb901678f2e37afda10a632348776aa77b53 --- java/BUILD | 2 +- java/bazel/BUILD.bazel | 9 ++ java/bazel/http_jar.bzl | 178 +++++++++++++++++++++++++++++++++++++++ java/http_jar.bzl | 177 +------------------------------------- java/rules_java_deps.bzl | 4 +- test/repo/WORKSPACE | 2 +- 6 files changed, 193 insertions(+), 179 deletions(-) create mode 100644 java/bazel/http_jar.bzl diff --git a/java/BUILD b/java/BUILD index 2074c388..a4363273 100644 --- a/java/BUILD +++ b/java/BUILD @@ -69,7 +69,7 @@ bzl_library( name = "http_jar_bzl", srcs = ["http_jar.bzl"], visibility = ["//visibility:public"], - deps = ["@bazel_tools//tools:bzl_srcs"], + deps = ["@compatibility_proxy//:proxy_bzl"], ) filegroup( diff --git a/java/bazel/BUILD.bazel b/java/bazel/BUILD.bazel index b5ddea9e..2c26d110 100644 --- a/java/bazel/BUILD.bazel +++ b/java/bazel/BUILD.bazel @@ -11,6 +11,8 @@ # 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("@bazel_skylib//:bzl_library.bzl", "bzl_library") load(":repositories_util.bzl", "FLAT_CONFIGS") # build this to generate _REMOTE_JDK_CONFIGS_LIST in repositories.bzl @@ -54,6 +56,13 @@ done <<< '{configs}' >> $@ visibility = ["//visibility:private"], ) +bzl_library( + name = "http_jar_bzl", + srcs = ["http_jar.bzl"], + visibility = ["@compatibility_proxy//:__pkg__"], + deps = ["@bazel_tools//tools:bzl_srcs"], +) + filegroup( name = "for_bazel_tests", testonly = 1, diff --git a/java/bazel/http_jar.bzl b/java/bazel/http_jar.bzl new file mode 100644 index 00000000..6ba729c4 --- /dev/null +++ b/java/bazel/http_jar.bzl @@ -0,0 +1,178 @@ +"""The http_jar repo rule, for downloading jars over HTTP.""" + +load("@bazel_tools//tools/build_defs/repo:cache.bzl", "CANONICAL_ID_DOC", "DEFAULT_CANONICAL_ID_ENV", "get_default_canonical_id") +load("@bazel_tools//tools/build_defs/repo:utils.bzl", "get_auth", "update_attrs") + +_URL_DOC = """A URL to the jar that will be made available to Bazel. + +This must be a file, http or https URL. Redirections are followed. +Authentication is not supported. + +More flexibility can be achieved by the urls parameter that allows +to specify alternative URLs to fetch from.""" + +_URLS_DOC = """A list of URLs to the jar that will be made available to Bazel. + +Each entry must be a file, http or https URL. Redirections are followed. +Authentication is not supported. + +URLs are tried in order until one succeeds, so you should list local mirrors first. +If all downloads fail, the rule will fail.""" + +_AUTH_PATTERN_DOC = """An optional dict mapping host names to custom authorization patterns. + +If a URL's host name is present in this dict the value will be used as a pattern when +generating the authorization header for the http request. This enables the use of custom +authorization schemes used in a lot of common cloud storage providers. + +The pattern currently supports 2 tokens: <login> and +<password>, which are replaced with their equivalent value +in the netrc file for the same host name. After formatting, the result is set +as the value for the Authorization field of the HTTP request. + +Example attribute and netrc for a http download to an oauth2 enabled API using a bearer token: + +

+auth_patterns = {
+    "storage.cloudprovider.com": "Bearer <password>"
+}
+
+ +netrc: + +
+machine storage.cloudprovider.com
+        password RANDOM-TOKEN
+
+ +The final HTTP request would have the following header: + +
+Authorization: Bearer RANDOM-TOKEN
+
+""" + +def _get_source_urls(ctx): + """Returns source urls provided via the url, urls attributes. + + Also checks that at least one url is provided.""" + if not ctx.attr.url and not ctx.attr.urls: + fail("At least one of url and urls must be provided") + + source_urls = [] + if ctx.attr.urls: + source_urls = ctx.attr.urls + if ctx.attr.url: + source_urls = [ctx.attr.url] + source_urls + return source_urls + +def _update_integrity_attr(ctx, attrs, download_info): + # We don't need to override the integrity attribute if sha256 is already specified. + integrity_override = {} if ctx.attr.sha256 else {"integrity": download_info.integrity} + return update_attrs(ctx.attr, attrs.keys(), integrity_override) + +_HTTP_JAR_BUILD = """\ +load("{java_import_bzl}", "java_import") + +java_import( + name = 'jar', + jars = ["{file_name}"], + visibility = ['//visibility:public'], +) + +filegroup( + name = 'file', + srcs = ["{file_name}"], + visibility = ['//visibility:public'], +) + +""" + +def _http_jar_impl(ctx): + """Implementation of the http_jar rule.""" + source_urls = _get_source_urls(ctx) + downloaded_file_name = ctx.attr.downloaded_file_name + download_info = ctx.download( + source_urls, + "jar/" + downloaded_file_name, + ctx.attr.sha256, + canonical_id = ctx.attr.canonical_id or get_default_canonical_id(ctx, source_urls), + auth = get_auth(ctx, source_urls), + integrity = ctx.attr.integrity, + ) + ctx.file("jar/BUILD", _HTTP_JAR_BUILD.format( + java_import_bzl = str(Label("//java:java_import.bzl")), + file_name = downloaded_file_name, + )) + + return _update_integrity_attr(ctx, _http_jar_attrs, download_info) + +_http_jar_attrs = { + "sha256": attr.string( + doc = """The expected SHA-256 of the jar downloaded. + +This must match the SHA-256 of the jar downloaded. _It is a security risk +to omit the SHA-256 as remote files can change._ At best omitting this +field will make your build non-hermetic. It is optional to make development +easier but either this attribute or `integrity` should be set before shipping.""", + ), + "integrity": attr.string( + doc = """Expected checksum in Subresource Integrity format of the jar downloaded. + +This must match the checksum of the file downloaded. _It is a security risk +to omit the checksum as remote files can change._ At best omitting this +field will make your build non-hermetic. It is optional to make development +easier but either this attribute or `sha256` should be set before shipping.""", + ), + "canonical_id": attr.string( + doc = CANONICAL_ID_DOC, + ), + "url": attr.string(doc = _URL_DOC + "\n\nThe URL must end in `.jar`."), + "urls": attr.string_list(doc = _URLS_DOC + "\n\nAll URLs must end in `.jar`."), + "netrc": attr.string( + doc = "Location of the .netrc file to use for authentication", + ), + "auth_patterns": attr.string_dict( + doc = _AUTH_PATTERN_DOC, + ), + "downloaded_file_name": attr.string( + default = "downloaded.jar", + doc = "Filename assigned to the jar downloaded", + ), +} + +http_jar = repository_rule( + implementation = _http_jar_impl, + attrs = _http_jar_attrs, + environ = [DEFAULT_CANONICAL_ID_ENV], + doc = + """Downloads a jar from a URL and makes it available as java_import + +Downloaded files must have a .jar extension. + +Examples: + Suppose the current repository contains the source code for a chat program, rooted at the + directory `~/chat-app`. It needs to depend on an SSL library which is available from + `http://example.com/openssl-0.2.jar`. + + Targets in the `~/chat-app` repository can depend on this target if the following lines are + added to `~/chat-app/MODULE.bazel`: + + ```python + http_jar = use_repo_rule("@rules_java//java:http_jar.bzl", "http_jar") + + http_jar( + name = "my_ssl", + url = "http://example.com/openssl-0.2.jar", + sha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + ) + ``` + + Targets would specify `@my_ssl//jar` as a dependency to depend on this jar. + + You may also reference files on the current system (localhost) by using "file:///path/to/file" + if you are on Unix-based systems. If you're on Windows, use "file:///c:/path/to/file". In both + examples, note the three slashes (`/`) -- the first two slashes belong to `file://` and the third + one belongs to the absolute path to the file. +""", +) diff --git a/java/http_jar.bzl b/java/http_jar.bzl index 88654821..ed3c3317 100644 --- a/java/http_jar.bzl +++ b/java/http_jar.bzl @@ -22,179 +22,6 @@ http_jar(name = "foo", urls = [...]) ``` """ -load("@bazel_tools//tools/build_defs/repo:cache.bzl", "CANONICAL_ID_DOC", "DEFAULT_CANONICAL_ID_ENV", "get_default_canonical_id") -load("@bazel_tools//tools/build_defs/repo:utils.bzl", "get_auth", "update_attrs") +load("@compatibility_proxy//:proxy.bzl", _http_jar = "http_jar") -_URL_DOC = """A URL to the jar that will be made available to Bazel. - -This must be a file, http or https URL. Redirections are followed. -Authentication is not supported. - -More flexibility can be achieved by the urls parameter that allows -to specify alternative URLs to fetch from.""" - -_URLS_DOC = """A list of URLs to the jar that will be made available to Bazel. - -Each entry must be a file, http or https URL. Redirections are followed. -Authentication is not supported. - -URLs are tried in order until one succeeds, so you should list local mirrors first. -If all downloads fail, the rule will fail.""" - -_AUTH_PATTERN_DOC = """An optional dict mapping host names to custom authorization patterns. - -If a URL's host name is present in this dict the value will be used as a pattern when -generating the authorization header for the http request. This enables the use of custom -authorization schemes used in a lot of common cloud storage providers. - -The pattern currently supports 2 tokens: <login> and -<password>, which are replaced with their equivalent value -in the netrc file for the same host name. After formatting, the result is set -as the value for the Authorization field of the HTTP request. - -Example attribute and netrc for a http download to an oauth2 enabled API using a bearer token: - -
-auth_patterns = {
-    "storage.cloudprovider.com": "Bearer <password>"
-}
-
- -netrc: - -
-machine storage.cloudprovider.com
-        password RANDOM-TOKEN
-
- -The final HTTP request would have the following header: - -
-Authorization: Bearer RANDOM-TOKEN
-
-""" - -def _get_source_urls(ctx): - """Returns source urls provided via the url, urls attributes. - - Also checks that at least one url is provided.""" - if not ctx.attr.url and not ctx.attr.urls: - fail("At least one of url and urls must be provided") - - source_urls = [] - if ctx.attr.urls: - source_urls = ctx.attr.urls - if ctx.attr.url: - source_urls = [ctx.attr.url] + source_urls - return source_urls - -def _update_integrity_attr(ctx, attrs, download_info): - # We don't need to override the integrity attribute if sha256 is already specified. - integrity_override = {} if ctx.attr.sha256 else {"integrity": download_info.integrity} - return update_attrs(ctx.attr, attrs.keys(), integrity_override) - -_HTTP_JAR_BUILD = """\ -load("{java_import_bzl}", "java_import") - -java_import( - name = 'jar', - jars = ["{file_name}"], - visibility = ['//visibility:public'], -) - -filegroup( - name = 'file', - srcs = ["{file_name}"], - visibility = ['//visibility:public'], -) - -""" - -def _http_jar_impl(ctx): - """Implementation of the http_jar rule.""" - source_urls = _get_source_urls(ctx) - downloaded_file_name = ctx.attr.downloaded_file_name - download_info = ctx.download( - source_urls, - "jar/" + downloaded_file_name, - ctx.attr.sha256, - canonical_id = ctx.attr.canonical_id or get_default_canonical_id(ctx, source_urls), - auth = get_auth(ctx, source_urls), - integrity = ctx.attr.integrity, - ) - ctx.file("jar/BUILD", _HTTP_JAR_BUILD.format( - java_import_bzl = str(Label("//java:java_import.bzl")), - file_name = downloaded_file_name, - )) - - return _update_integrity_attr(ctx, _http_jar_attrs, download_info) - -_http_jar_attrs = { - "sha256": attr.string( - doc = """The expected SHA-256 of the jar downloaded. - -This must match the SHA-256 of the jar downloaded. _It is a security risk -to omit the SHA-256 as remote files can change._ At best omitting this -field will make your build non-hermetic. It is optional to make development -easier but either this attribute or `integrity` should be set before shipping.""", - ), - "integrity": attr.string( - doc = """Expected checksum in Subresource Integrity format of the jar downloaded. - -This must match the checksum of the file downloaded. _It is a security risk -to omit the checksum as remote files can change._ At best omitting this -field will make your build non-hermetic. It is optional to make development -easier but either this attribute or `sha256` should be set before shipping.""", - ), - "canonical_id": attr.string( - doc = CANONICAL_ID_DOC, - ), - "url": attr.string(doc = _URL_DOC + "\n\nThe URL must end in `.jar`."), - "urls": attr.string_list(doc = _URLS_DOC + "\n\nAll URLs must end in `.jar`."), - "netrc": attr.string( - doc = "Location of the .netrc file to use for authentication", - ), - "auth_patterns": attr.string_dict( - doc = _AUTH_PATTERN_DOC, - ), - "downloaded_file_name": attr.string( - default = "downloaded.jar", - doc = "Filename assigned to the jar downloaded", - ), -} - -http_jar = repository_rule( - implementation = _http_jar_impl, - attrs = _http_jar_attrs, - environ = [DEFAULT_CANONICAL_ID_ENV], - doc = - """Downloads a jar from a URL and makes it available as java_import - -Downloaded files must have a .jar extension. - -Examples: - Suppose the current repository contains the source code for a chat program, rooted at the - directory `~/chat-app`. It needs to depend on an SSL library which is available from - `http://example.com/openssl-0.2.jar`. - - Targets in the `~/chat-app` repository can depend on this target if the following lines are - added to `~/chat-app/MODULE.bazel`: - - ```python - http_jar = use_repo_rule("@rules_java//java:http_jar.bzl", "http_jar") - - http_jar( - name = "my_ssl", - url = "http://example.com/openssl-0.2.jar", - sha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - ) - ``` - - Targets would specify `@my_ssl//jar` as a dependency to depend on this jar. - - You may also reference files on the current system (localhost) by using "file:///path/to/file" - if you are on Unix-based systems. If you're on Windows, use "file:///c:/path/to/file". In both - examples, note the three slashes (`/`) -- the first two slashes belong to `file://` and the third - one belongs to the absolute path to the file. -""", -) +http_jar = _http_jar diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl index 9e7fd807..98a29076 100644 --- a/java/rules_java_deps.bzl +++ b/java/rules_java_deps.bzl @@ -19,7 +19,7 @@ bzl_library( "@rules_java//java/bazel/rules", "@rules_java//java/common/rules:toolchain_rules", "@rules_java//java/private:internals", - "@rules_java//java:http_jar_bzl", + "@rules_java//java/bazel:http_jar_bzl", ], visibility = ["//visibility:public"] ) @@ -33,13 +33,13 @@ load("@rules_java//java/bazel/rules:bazel_java_import.bzl", _java_import = "java load("@rules_java//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") load("@rules_java//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") load("@rules_java//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") +load("@rules_java//java/bazel:http_jar.bzl", _http_jar = "http_jar") load("@rules_java//java/common/rules:java_package_configuration.bzl", _java_package_configuration = "java_package_configuration") load("@rules_java//java/common/rules:java_runtime.bzl", _java_runtime = "java_runtime") load("@rules_java//java/common/rules:java_toolchain.bzl", _java_toolchain = "java_toolchain") load("@rules_java//java/private:java_common.bzl", _java_common = "java_common") load("@rules_java//java/private:java_common_internal.bzl", _java_common_internal_compile = "compile") load("@rules_java//java/private:java_info.bzl", _JavaInfo = "JavaInfo", _JavaPluginInfo = "JavaPluginInfo", _java_info_internal_merge = "merge") -load("@rules_java//java:http_jar.bzl", _http_jar = "http_jar") java_binary = _java_binary java_import = _java_import diff --git a/test/repo/WORKSPACE b/test/repo/WORKSPACE index 1a135b61..872e89a7 100644 --- a/test/repo/WORKSPACE +++ b/test/repo/WORKSPACE @@ -19,7 +19,7 @@ load("@rules_java//java:repositories.bzl", "rules_java_toolchains") rules_java_toolchains() -load("@compatibility_proxy//:proxy.bzl", "http_jar") +load("@rules_java//java:http_jar.bzl", "http_jar") http_jar( name = "my_jar", From 4cb426ed30ff06fad833aab970d50fb3e5c5d088 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 5 Dec 2024 22:25:22 -0800 Subject: [PATCH 101/465] Release `@rules_java` `v8.6.2` PiperOrigin-RevId: 703369227 Change-Id: I7e18f478d3bada30fb426d4dfd8efb0d5bf233d7 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 82f05136..0476b99c 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.6.1", + version = "8.6.2", bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) From 449303e723185a8197794c42711602e66b1a9296 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Fri, 6 Dec 2024 00:33:25 -0800 Subject: [PATCH 102/465] Add `incompatible_language_version_bootclasspath` flag Copybara Import from https://github.com/bazelbuild/rules_java/pull/182 BEGIN_PUBLIC Add `incompatible_language_version_bootclasspath` flag (#182) With `--@rules_java//java:incompatible_language_version_bootclasspath`, the bootclasspath used for Java compilation is now determined based on the numeric version specified in `--java_language_version` and the type specified in `--java_runtime_version` rather than just using the target runtime. For example, with `--java_language_version=8` and `--java_runtime_version=remotejdk_21`, the bootclasspath would be extracted from `remotejdk_8`. For unversioned runtime versions such as `local_jdk`, the behavior doesn't change. If a matching runtime is not available, analysis fails with a customized error message explaining the various options to the user. Work towards https://github.com/bazelbuild/bazel/discussions/21769 Closes #182 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/182 from fmeum:java-language-version de275069b6c98919264f2bfce791dde56eaefcde PiperOrigin-RevId: 703396804 Change-Id: Ieb1def97a5eee59763336eb61deaf584f341a1d4 --- test/analysis/bootclasspath_tests.bzl | 52 ++++++ toolchains/BUILD | 47 ++++- toolchains/bootclasspath.bzl | 246 ++++++++++++++++++++++++++ toolchains/default_java_toolchain.bzl | 113 +----------- 4 files changed, 346 insertions(+), 112 deletions(-) create mode 100644 toolchains/bootclasspath.bzl diff --git a/test/analysis/bootclasspath_tests.bzl b/test/analysis/bootclasspath_tests.bzl index c862d836..5eb436a0 100644 --- a/test/analysis/bootclasspath_tests.bzl +++ b/test/analysis/bootclasspath_tests.bzl @@ -2,6 +2,7 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "subjects") +load("//java/common:java_common.bzl", "java_common") def _test_utf_8_environment(name): analysis_test( @@ -16,10 +17,61 @@ def _test_utf_8_environment_impl(env, target): env_subject.keys().contains("LC_CTYPE") env_subject.get("LC_CTYPE", factory = subjects.str).contains("UTF-8") +def _test_incompatible_language_version_bootclasspath_disabled(name): + analysis_test( + name = name, + impl = _test_incompatible_language_version_bootclasspath_disabled_impl, + target = Label("//toolchains:platformclasspath"), + config_settings = { + "//command_line_option:java_language_version": "11", + "//command_line_option:java_runtime_version": "remotejdk_17", + str(Label("//toolchains:incompatible_language_version_bootclasspath")): False, + }, + ) + +def _test_incompatible_language_version_bootclasspath_disabled_impl(env, target): + system_path = target[java_common.BootClassPathInfo]._system_path + env.expect.that_str(system_path).contains("remotejdk17_") + +def _test_incompatible_language_version_bootclasspath_enabled_versioned(name): + analysis_test( + name = name, + impl = _test_incompatible_language_version_bootclasspath_enabled_versioned_impl, + target = Label("//toolchains:platformclasspath"), + config_settings = { + "//command_line_option:java_language_version": "11", + "//command_line_option:java_runtime_version": "remotejdk_17", + str(Label("//toolchains:incompatible_language_version_bootclasspath")): True, + }, + ) + +def _test_incompatible_language_version_bootclasspath_enabled_versioned_impl(env, target): + system_path = target[java_common.BootClassPathInfo]._system_path + env.expect.that_str(system_path).contains("remotejdk11_") + +def _test_incompatible_language_version_bootclasspath_enabled_unversioned(name): + analysis_test( + name = name, + impl = _test_incompatible_language_version_bootclasspath_enabled_unversioned_impl, + target = Label("//toolchains:platformclasspath"), + config_settings = { + "//command_line_option:java_language_version": "11", + "//command_line_option:java_runtime_version": "local_jdk", + str(Label("//toolchains:incompatible_language_version_bootclasspath")): True, + }, + ) + +def _test_incompatible_language_version_bootclasspath_enabled_unversioned_impl(env, target): + system_path = target[java_common.BootClassPathInfo]._system_path + env.expect.that_str(system_path).contains("local_jdk") + def bootclasspath_tests(name): test_suite( name = name, tests = [ _test_utf_8_environment, + _test_incompatible_language_version_bootclasspath_disabled, + _test_incompatible_language_version_bootclasspath_enabled_versioned, + _test_incompatible_language_version_bootclasspath_enabled_unversioned, ], ) diff --git a/toolchains/BUILD b/toolchains/BUILD index e7f4d84b..99c4456c 100644 --- a/toolchains/BUILD +++ b/toolchains/BUILD @@ -1,10 +1,15 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") +load("@bazel_skylib//rules:common_settings.bzl", "bool_flag", "string_setting") load("@rules_cc//cc:cc_library.bzl", "cc_library") +load( + ":bootclasspath.bzl", + "bootclasspath", + "language_version_bootstrap_runtime", +) load( ":default_java_toolchain.bzl", "DEFAULT_TOOLCHAIN_CONFIGURATION", "PREBUILT_TOOLCHAIN_CONFIGURATION", - "bootclasspath", "default_java_toolchain", "java_runtime_files", ) @@ -31,6 +36,15 @@ filegroup( srcs = glob(["*.bzl"]), ) +# If enabled, the bootclasspath for Java compilation will be extracted from a Java runtime matching +# the version specified with `--java_language_version` rather than the runtime specified with +# `--java_runtime_version`. +bool_flag( + name = "incompatible_language_version_bootclasspath", + build_setting_default = False, + visibility = ["//visibility:private"], +) + # A single binary distribution of a JDK (e.g., OpenJDK 17 for Windows arm64) provides three # different types of toolchains from the perspective of Bazel: @@ -283,15 +297,46 @@ alias( }), ) +string_setting( + name = "java_language_version", + build_setting_default = "", + visibility = ["//visibility:private"], +) + +string_setting( + name = "java_runtime_version", + build_setting_default = "", + visibility = ["//visibility:private"], +) + +language_version_bootstrap_runtime( + name = "language_version_bootstrap_runtime", + java_language_version = ":java_language_version", + java_runtime_version = ":java_runtime_version", + visibility = ["//visibility:private"], +) + utf8_environment( name = "utf8_environment", visibility = ["//visibility:private"], ) +config_setting( + name = "incompatible_language_version_bootclasspath_enabled", + flag_values = { + ":incompatible_language_version_bootclasspath": "True", + }, + visibility = ["//visibility:private"], +) + bootclasspath( name = "platformclasspath", src = "DumpPlatformClassPath.java", java_runtime_alias = ":current_java_runtime", + language_version_bootstrap_runtime = select({ + ":incompatible_language_version_bootclasspath_enabled": ":language_version_bootstrap_runtime", + "//conditions:default": None, + }), ) default_java_toolchain( diff --git a/toolchains/bootclasspath.bzl b/toolchains/bootclasspath.bzl new file mode 100644 index 00000000..b6f57e00 --- /dev/null +++ b/toolchains/bootclasspath.bzl @@ -0,0 +1,246 @@ +# 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. + +"""Rules for extracting a platform classpath from Java runtimes.""" + +load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo") +load("//java/common:java_common.bzl", "java_common") +load(":utf8_environment.bzl", "Utf8EnvironmentInfo") + +visibility("private") + +# TODO: This provider and is only necessary since --java_{language,runtime}_version +# are not available directly to Starlark. +_JavaVersionsInfo = provider( + "Exposes the --java_{language,runtime}_version value as extracted from a transition to a dependant.", + fields = { + "java_language_version": "The value of --java_language_version", + "java_runtime_version": "The value of --java_runtime_version", + }, +) + +def _language_version_bootstrap_runtime(ctx): + providers = [ + _JavaVersionsInfo( + java_language_version = ctx.attr.java_language_version[BuildSettingInfo].value, + java_runtime_version = ctx.attr.java_runtime_version[BuildSettingInfo].value, + ), + ] + + bootstrap_runtime = ctx.toolchains["@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type"] + if bootstrap_runtime: + providers.append(bootstrap_runtime.java_runtime) + + return providers + +language_version_bootstrap_runtime = rule( + implementation = _language_version_bootstrap_runtime, + attrs = { + "java_language_version": attr.label( + providers = [BuildSettingInfo], + ), + "java_runtime_version": attr.label( + providers = [BuildSettingInfo], + ), + }, + toolchains = [ + config_common.toolchain_type("@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type", mandatory = False), + ], +) + +def _get_bootstrap_runtime_version(*, java_language_version, java_runtime_version): + """Returns the runtime version to use for bootstrapping the given language version. + + If the runtime version is not versioned, e.g. "local_jdk", it is used as is. + Otherwise, the language version replaces the numeric part of the runtime version, e.g., + "remotejdk_17" becomes "remotejdk_8". + """ + prefix, separator, version = java_runtime_version.rpartition("_") + if version and version.isdigit(): + new_version = java_language_version + else: + # The runtime version is not versioned, e.g. "local_jdk". Use it as is. + new_version = version + + return prefix + separator + new_version + +def _bootclasspath_transition_impl(settings, _): + java_language_version = settings["//command_line_option:java_language_version"] + java_runtime_version = settings["//command_line_option:java_runtime_version"] + + return { + "//command_line_option:java_runtime_version": _get_bootstrap_runtime_version( + java_language_version = java_language_version, + java_runtime_version = java_runtime_version, + ), + "//toolchains:java_language_version": java_language_version, + "//toolchains:java_runtime_version": java_runtime_version, + } + +_bootclasspath_transition = transition( + implementation = _bootclasspath_transition_impl, + inputs = [ + "//command_line_option:java_language_version", + "//command_line_option:java_runtime_version", + ], + outputs = [ + "//command_line_option:java_runtime_version", + "//toolchains:java_language_version", + "//toolchains:java_runtime_version", + ], +) + +_JAVA_BOOTSTRAP_RUNTIME_TOOLCHAIN_TYPE = Label("@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type") + +# Opt the Java bootstrap actions into path mapping: +# https://github.com/bazelbuild/bazel/commit/a239ea84832f18ee8706682145e9595e71b39680 +_SUPPORTS_PATH_MAPPING = {"supports-path-mapping": "1"} + +def _java_home(java_executable): + return java_executable.dirname[:-len("/bin")] + +def _bootclasspath_impl(ctx): + exec_javabase = ctx.attr.java_runtime_alias[java_common.JavaRuntimeInfo] + env = ctx.attr._utf8_environment[Utf8EnvironmentInfo].environment + + class_dir = ctx.actions.declare_directory("%s_classes" % ctx.label.name) + + args = ctx.actions.args() + args.add("-source") + args.add("8") + args.add("-target") + args.add("8") + args.add("-Xlint:-options") + args.add("-J-XX:-UsePerfData") + args.add("-d") + args.add_all([class_dir], expand_directories = False) + args.add(ctx.file.src) + + ctx.actions.run( + executable = "%s/bin/javac" % exec_javabase.java_home, + mnemonic = "JavaToolchainCompileClasses", + inputs = [ctx.file.src] + ctx.files.java_runtime_alias, + outputs = [class_dir], + arguments = [args], + env = env, + execution_requirements = _SUPPORTS_PATH_MAPPING, + ) + + bootclasspath = ctx.outputs.output_jar + + args = ctx.actions.args() + args.add("-XX:+IgnoreUnrecognizedVMOptions") + args.add("-XX:-UsePerfData") + args.add("--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED") + args.add("--add-exports=jdk.compiler/com.sun.tools.javac.platform=ALL-UNNAMED") + args.add("--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED") + args.add_all("-cp", [class_dir], expand_directories = False) + args.add("DumpPlatformClassPath") + args.add(bootclasspath) + + if ctx.attr.language_version_bootstrap_runtime: + # The attribute is subject to a split transition. + language_version_bootstrap_runtime = ctx.attr.language_version_bootstrap_runtime[0] + if java_common.JavaRuntimeInfo in language_version_bootstrap_runtime: + any_javabase = language_version_bootstrap_runtime[java_common.JavaRuntimeInfo] + else: + java_versions_info = language_version_bootstrap_runtime[_JavaVersionsInfo] + bootstrap_runtime_version = _get_bootstrap_runtime_version( + java_language_version = java_versions_info.java_language_version, + java_runtime_version = java_versions_info.java_runtime_version, + ) + is_exec = "-exec" in ctx.bin_dir.path + tool_prefix = "tool_" if is_exec else "" + fail(""" +No Java runtime found to extract the bootclasspath from for --{tool_prefix}java_language_version={language_version} and --{tool_prefix}java_runtime_version={runtime_version}. +You can: + + * register a Java runtime with name "{bootstrap_runtime_version}" to provide the bootclasspath or + * set --java_language_version to the Java version of an available runtime. + +Rerun with --toolchain_resolution_debug='@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type' to see more details about toolchain resolution. +""".format( + language_version = java_versions_info.java_language_version, + runtime_version = java_versions_info.java_runtime_version, + bootstrap_runtime_version = bootstrap_runtime_version, + tool_prefix = tool_prefix, + )) + else: + any_javabase = ctx.toolchains[_JAVA_BOOTSTRAP_RUNTIME_TOOLCHAIN_TYPE].java_runtime + any_javabase_files = any_javabase.files.to_list() + + # If possible, add the Java executable to the command line as a File so that it can be path + # mapped. + java_executable = [f for f in any_javabase_files if f.path == any_javabase.java_executable_exec_path] + if len(java_executable) == 1: + args.add_all(java_executable, map_each = _java_home) + else: + args.add(any_javabase.java_home) + + system_files = ("release", "modules", "jrt-fs.jar") + system = [f for f in any_javabase_files if f.basename in system_files] + if len(system) != len(system_files): + system = None + + inputs = depset([class_dir] + ctx.files.java_runtime_alias, transitive = [any_javabase.files]) + ctx.actions.run( + executable = str(exec_javabase.java_executable_exec_path), + mnemonic = "JavaToolchainCompileBootClasspath", + inputs = inputs, + outputs = [bootclasspath], + arguments = [args], + env = env, + execution_requirements = _SUPPORTS_PATH_MAPPING, + ) + return [ + DefaultInfo(files = depset([bootclasspath])), + java_common.BootClassPathInfo( + bootclasspath = [bootclasspath], + system = system, + ), + OutputGroupInfo(jar = [bootclasspath]), + ] + +_bootclasspath = rule( + implementation = _bootclasspath_impl, + attrs = { + "java_runtime_alias": attr.label( + cfg = "exec", + providers = [java_common.JavaRuntimeInfo], + ), + "language_version_bootstrap_runtime": attr.label( + cfg = _bootclasspath_transition, + ), + "output_jar": attr.output(mandatory = True), + "src": attr.label( + cfg = "exec", + allow_single_file = True, + ), + "_allowlist_function_transition": attr.label( + default = "@bazel_tools//tools/allowlists/function_transition_allowlist", + ), + "_utf8_environment": attr.label( + default = ":utf8_environment", + cfg = "exec", + ), + }, + toolchains = [_JAVA_BOOTSTRAP_RUNTIME_TOOLCHAIN_TYPE], +) + +def bootclasspath(name, **kwargs): + _bootclasspath( + name = name, + output_jar = name + ".jar", + **kwargs + ) diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl index 5aaa06bf..4ec8961a 100644 --- a/toolchains/default_java_toolchain.bzl +++ b/toolchains/default_java_toolchain.bzl @@ -14,9 +14,8 @@ """Rules for defining default_java_toolchain""" -load("//java/common:java_common.bzl", "java_common") load("//java/toolchains:java_toolchain.bzl", "java_toolchain") -load(":utf8_environment.bzl", "Utf8EnvironmentInfo") +load(":bootclasspath.bzl", _bootclasspath = "bootclasspath") # JVM options, without patching java.compiler and jdk.compiler modules. BASE_JDK9_JVM_OPTS = [ @@ -213,112 +212,4 @@ def java_runtime_files(name, srcs): tags = ["manual"], ) -_JAVA_BOOTSTRAP_RUNTIME_TOOLCHAIN_TYPE = Label("@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type") - -# Opt the Java bootstrap actions into path mapping: -# https://github.com/bazelbuild/bazel/commit/a239ea84832f18ee8706682145e9595e71b39680 -_SUPPORTS_PATH_MAPPING = {"supports-path-mapping": "1"} - -def _java_home(java_executable): - return java_executable.dirname[:-len("/bin")] - -def _bootclasspath_impl(ctx): - exec_javabase = ctx.attr.java_runtime_alias[java_common.JavaRuntimeInfo] - env = ctx.attr._utf8_environment[Utf8EnvironmentInfo].environment - - class_dir = ctx.actions.declare_directory("%s_classes" % ctx.label.name) - - args = ctx.actions.args() - args.add("-source") - args.add("8") - args.add("-target") - args.add("8") - args.add("-Xlint:-options") - args.add("-J-XX:-UsePerfData") - args.add("-d") - args.add_all([class_dir], expand_directories = False) - args.add(ctx.file.src) - - ctx.actions.run( - executable = "%s/bin/javac" % exec_javabase.java_home, - mnemonic = "JavaToolchainCompileClasses", - inputs = [ctx.file.src] + ctx.files.java_runtime_alias, - outputs = [class_dir], - arguments = [args], - env = env, - execution_requirements = _SUPPORTS_PATH_MAPPING, - ) - - bootclasspath = ctx.outputs.output_jar - - args = ctx.actions.args() - args.add("-XX:+IgnoreUnrecognizedVMOptions") - args.add("-XX:-UsePerfData") - args.add("--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED") - args.add("--add-exports=jdk.compiler/com.sun.tools.javac.platform=ALL-UNNAMED") - args.add("--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED") - args.add_all("-cp", [class_dir], expand_directories = False) - args.add("DumpPlatformClassPath") - args.add(bootclasspath) - - any_javabase = ctx.toolchains[_JAVA_BOOTSTRAP_RUNTIME_TOOLCHAIN_TYPE].java_runtime - any_javabase_files = any_javabase.files.to_list() - - # If possible, add the Java executable to the command line as a File so that it can be path - # mapped. - java_executable = [f for f in any_javabase_files if f.path == any_javabase.java_executable_exec_path] - if len(java_executable) == 1: - args.add_all(java_executable, map_each = _java_home) - else: - args.add(any_javabase.java_home) - - system_files = ("release", "modules", "jrt-fs.jar") - system = [f for f in any_javabase_files if f.basename in system_files] - if len(system) != len(system_files): - system = None - - inputs = depset([class_dir] + ctx.files.java_runtime_alias, transitive = [any_javabase.files]) - ctx.actions.run( - executable = str(exec_javabase.java_executable_exec_path), - mnemonic = "JavaToolchainCompileBootClasspath", - inputs = inputs, - outputs = [bootclasspath], - arguments = [args], - env = env, - execution_requirements = _SUPPORTS_PATH_MAPPING, - ) - return [ - DefaultInfo(files = depset([bootclasspath])), - java_common.BootClassPathInfo( - bootclasspath = [bootclasspath], - system = system, - ), - OutputGroupInfo(jar = [bootclasspath]), - ] - -_bootclasspath = rule( - implementation = _bootclasspath_impl, - attrs = { - "java_runtime_alias": attr.label( - cfg = "exec", - providers = [java_common.JavaRuntimeInfo], - ), - "output_jar": attr.output(mandatory = True), - "src": attr.label( - cfg = "exec", - allow_single_file = True, - ), - "_utf8_environment": attr.label( - default = ":utf8_environment", - cfg = "exec", - ), - }, - toolchains = [_JAVA_BOOTSTRAP_RUNTIME_TOOLCHAIN_TYPE], -) - -def bootclasspath(name, **kwargs): - _bootclasspath( - name = name, - output_jar = name + ".jar", - **kwargs - ) +bootclasspath = _bootclasspath From b3a0580e0a9a6b8b28b611c7dd6164c06b279539 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 9 Dec 2024 09:04:53 -0800 Subject: [PATCH 103/465] Don't attempt to enable the Security Manager for jdk >= 24 The Security Manager is being permanently disabled in JDK 24, see https://openjdk.org/jeps/486 PiperOrigin-RevId: 704307132 Change-Id: I95501503206a85b6d9f828c4c6ab8e1fb3313eef --- java/bazel/rules/bazel_java_binary.bzl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl index 06e8421a..46e708c3 100644 --- a/java/bazel/rules/bazel_java_binary.bzl +++ b/java/bazel/rules/bazel_java_binary.bzl @@ -75,7 +75,8 @@ def bazel_base_binary_impl(ctx, is_test_rule_class): ) if ctx.attr.use_testrunner: - if semantics.find_java_runtime_toolchain(ctx).version >= 17: + _java_runtime_version = semantics.find_java_runtime_toolchain(ctx).version + if _java_runtime_version >= 17 and _java_runtime_version < 24: jvm_flags.append("-Djava.security.manager=allow") test_class = ctx.attr.test_class if hasattr(ctx.attr, "test_class") else "" if test_class == "": From 4e38b17af5826a4641d941f7c5ddb2eb15a9aaf0 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 18 Dec 2024 00:25:57 -0800 Subject: [PATCH 104/465] Implement `android_common.enable_implicit_sourceless_deps_exports_compatibility` in rules_java Work towards dropping native `JavaInfo` provider wrappers. PiperOrigin-RevId: 707431633 Change-Id: Iff76922764f76551ff7affea7bfbd3b9d495cf47 --- .bazelci/presubmit.yml | 1 + java/private/BUILD | 9 ++++ java/private/android_support.bzl | 20 +++++++ java/private/java_info.bzl | 27 ++++++++++ java/rules_java_deps.bzl | 6 ++- java/test/private/BUILD | 34 ++++++++++++ java/test/private/Foo.java | 1 + java/test/private/MyPlugin.java | 1 + java/test/private/android_support_tests.bzl | 59 +++++++++++++++++++++ 9 files changed, 157 insertions(+), 1 deletion(-) create mode 100644 java/private/android_support.bzl create mode 100644 java/test/private/BUILD create mode 100644 java/test/private/Foo.java create mode 100644 java/test/private/MyPlugin.java create mode 100644 java/test/private/android_support_tests.bzl diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index d61be6c1..d468b1b0 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -25,6 +25,7 @@ test_targets: &test_targets test_targets_bazel6: &test_targets_bazel6 - "//java/test/..." + - "-//java/test/private/..." test_target_integration: &test_target_integration - "//:MyTest" diff --git a/java/private/BUILD b/java/private/BUILD index 94bae8da..020a4a7b 100644 --- a/java/private/BUILD +++ b/java/private/BUILD @@ -44,6 +44,14 @@ bzl_library( deps = ["@compatibility_proxy//:proxy_bzl"], ) +# Exposed for use by the android rules. +bzl_library( + name = "android_support", + srcs = ["android_support.bzl"], + visibility = ["//visibility:public"], + deps = ["@compatibility_proxy//:proxy_bzl"], +) + filegroup( name = "srcs", srcs = glob(["**"]), @@ -55,6 +63,7 @@ filegroup( testonly = 1, srcs = [ "BUILD", + ":android_support", ":internals", ":native_bzl", ":proto_support", diff --git a/java/private/android_support.bzl b/java/private/android_support.bzl new file mode 100644 index 00000000..fa80a17b --- /dev/null +++ b/java/private/android_support.bzl @@ -0,0 +1,20 @@ +# 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. +"""Legacy support for the android rules.""" + +load("@compatibility_proxy//:proxy.bzl", "java_info_to_implicit_exportable") + +android_support = struct( + enable_implicit_sourceless_deps_exports_compatibility = java_info_to_implicit_exportable, +) diff --git a/java/private/java_info.bzl b/java/private/java_info.bzl index 8ba655ed..3b68e69e 100644 --- a/java/private/java_info.bzl +++ b/java/private/java_info.bzl @@ -248,6 +248,33 @@ def to_java_binary_info(java_info, compilation_info): result.update(_is_binary = True) return _new_javainfo(**result) +def to_implicit_exportable(java_info, neverlink = False): + result = { + "transitive_runtime_jars": depset() if neverlink else java_info.transitive_runtime_jars, + "transitive_compile_time_jars": java_info.transitive_compile_time_jars, + "compile_jars": java_info.compile_jars, + "full_compile_jars": java_info.full_compile_jars, + "_transitive_full_compile_time_jars": java_info._transitive_full_compile_time_jars, + "_compile_time_java_dependencies": java_info._compile_time_java_dependencies, + "_neverlink": neverlink, + # unset defaults + "source_jars": [], + "outputs": _JavaRuleOutputJarsInfo(jars = [], jdeps = None, native_headers = None), + "annotation_processing": None, + "runtime_output_jars": [], + "transitive_source_jars": depset(), + "transitive_native_libraries": depset(), + "cc_link_params_info": CcInfo(), + "module_flags_info": _EMPTY_MODULE_FLAGS_INFO, + "plugins": _EMPTY_PLUGIN_DATA, + "api_generating_plugins": _EMPTY_PLUGIN_DATA, + "java_outputs": [], + "compilation_info": None, + "_constraints": [], + "_is_binary": getattr(java_info, "_is_binary", False), + } + return _new_javainfo(**result) + def _to_mutable_dict(java_info): return { key: getattr(java_info, key) diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl index 98a29076..d97f56db 100644 --- a/java/rules_java_deps.bzl +++ b/java/rules_java_deps.bzl @@ -39,7 +39,8 @@ load("@rules_java//java/common/rules:java_runtime.bzl", _java_runtime = "java_ru load("@rules_java//java/common/rules:java_toolchain.bzl", _java_toolchain = "java_toolchain") load("@rules_java//java/private:java_common.bzl", _java_common = "java_common") load("@rules_java//java/private:java_common_internal.bzl", _java_common_internal_compile = "compile") -load("@rules_java//java/private:java_info.bzl", _JavaInfo = "JavaInfo", _JavaPluginInfo = "JavaPluginInfo", _java_info_internal_merge = "merge") +load("@rules_java//java/private:java_info.bzl", _JavaInfo = "JavaInfo", _JavaPluginInfo = "JavaPluginInfo", + _java_info_internal_merge = "merge", _java_info_to_implicit_exportable = "to_implicit_exportable") java_binary = _java_binary java_import = _java_import @@ -54,6 +55,7 @@ JavaInfo = _JavaInfo JavaPluginInfo = _JavaPluginInfo java_common_internal_compile = _java_common_internal_compile java_info_internal_merge = _java_info_internal_merge +java_info_to_implicit_exportable = _java_info_to_implicit_exportable http_jar = _http_jar """, ) @@ -95,6 +97,8 @@ JavaInfo = NativeJavaInfo JavaPluginInfo = NativeJavaPluginInfo java_common_internal_compile = None java_info_internal_merge = None +# Not available before Bazel 7 +java_info_to_implicit_exportable = getattr(android_common, "enable_implicit_sourceless_deps_exports_compatibility", None) http_jar = _http_jar """, diff --git a/java/test/private/BUILD b/java/test/private/BUILD new file mode 100644 index 00000000..4938f734 --- /dev/null +++ b/java/test/private/BUILD @@ -0,0 +1,34 @@ +# Copyright 2021 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("//java:defs.bzl", "java_library", "java_plugin") +load(":android_support_tests.bzl", "android_support_tests", "my_rule") + +java_plugin( + name = "my_plugin", + srcs = ["MyPlugin.java"], +) + +java_library( + name = "foo", + srcs = ["Foo.java"], + exported_plugins = [":my_plugin"], +) + +my_rule( + name = "bar", + dep = ":foo", +) + +android_support_tests(name = "android_support_tests") diff --git a/java/test/private/Foo.java b/java/test/private/Foo.java new file mode 100644 index 00000000..4a2b44da --- /dev/null +++ b/java/test/private/Foo.java @@ -0,0 +1 @@ +public class Foo {} diff --git a/java/test/private/MyPlugin.java b/java/test/private/MyPlugin.java new file mode 100644 index 00000000..2747e676 --- /dev/null +++ b/java/test/private/MyPlugin.java @@ -0,0 +1 @@ +public class MyPlugin {} diff --git a/java/test/private/android_support_tests.bzl b/java/test/private/android_support_tests.bzl new file mode 100644 index 00000000..91f38c09 --- /dev/null +++ b/java/test/private/android_support_tests.bzl @@ -0,0 +1,59 @@ +# Copyright 2021 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. +"""Tests for //java/private:android_support.bzl""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/private:android_support.bzl", "android_support") + +def _impl(ctx): + return [ + android_support.enable_implicit_sourceless_deps_exports_compatibility(ctx.attr.dep[JavaInfo]), + ] + +my_rule = rule( + implementation = _impl, + attrs = { + "dep": attr.label(), + }, +) + +def _test_enable_implicit_sourceless_deps_exports_compatibility(name): + analysis_test( + name = name, + impl = _test_enable_implicit_sourceless_deps_exports_compatibility_impl, + targets = { + "foo": Label(":foo"), + "bar": Label(":bar"), + }, + ) + +def _test_enable_implicit_sourceless_deps_exports_compatibility_impl(env, targets): + # TODO(hvd): write a ProviderSubject for JavaInfo + foo_javainfo = targets.foo[JavaInfo] + bar_javainfo = targets.bar[JavaInfo] + for attr in ["transitive_runtime_jars", "compile_jars", "transitive_compile_time_jars", "full_compile_jars", "_transitive_full_compile_time_jars", "_compile_time_java_dependencies"]: + env.expect.that_bool(getattr(foo_javainfo, attr) == getattr(bar_javainfo, attr)).equals(True) + env.expect.that_depset_of_files(foo_javainfo.plugins.processor_jars).contains_exactly([ + "java/test/private/libmy_plugin.jar", + ]) + env.expect.that_depset_of_files(bar_javainfo.plugins.processor_jars).contains_exactly([]) + +def android_support_tests(name): + test_suite( + name = name, + tests = [ + _test_enable_implicit_sourceless_deps_exports_compatibility, + ], + ) From 767e4410850453a10ccf89aa1cededf9de05c72e Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 19 Dec 2024 07:05:44 -0800 Subject: [PATCH 105/465] Release `@rules_java` `v8.6.3` PiperOrigin-RevId: 707902033 Change-Id: I021972d014137f56cfdab7f8d7b6cdd7c646f7f3 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 0476b99c..a5853237 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.6.2", + version = "8.6.3", bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) From 97177fbae3e22cb51e2b1a8adb1d3d0509453c0d Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Tue, 7 Jan 2025 08:40:49 -0800 Subject: [PATCH 106/465] Mark `compatibility_proxy` extension as reproducible Copybara Import from https://github.com/bazelbuild/rules_java/pull/259 BEGIN_PUBLIC Mark `compatibility_proxy` extension as reproducible (#259) This avoids an unnecessary lockfile entry. Closes #259 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/259 from fmeum:patch-2 3ce5497f0c647861d6864148f8fc6a6b6c348822 PiperOrigin-RevId: 712925704 Change-Id: Ica006fc3942c32d8b21260e52ce251e24980001a --- java/rules_java_deps.bzl | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl index d97f56db..1929bc85 100644 --- a/java/rules_java_deps.bzl +++ b/java/rules_java_deps.bzl @@ -113,9 +113,18 @@ _compatibility_proxy_repo_rule = repository_rule( def compatibility_proxy_repo(): maybe(_compatibility_proxy_repo_rule, name = "compatibility_proxy") -def _compat_proxy_impl(_unused): +def _compat_proxy_impl(module_ctx): compatibility_proxy_repo() + # module_ctx.extension_metadata has the paramater `reproducible` as of Bazel 7.1.0. We can't + # test for it directly and would ideally use bazel_features to check for it, but don't want + # to add a dependency for as long as WORKSPACE is still around. Thus, test for it by + # checking the availability of another feature introduced in 7.1.0. + if hasattr(module_ctx, "watch"): + return module_ctx.extension_metadata(reproducible = True) + else: + return None + compatibility_proxy = module_extension(_compat_proxy_impl) def protobuf_repo(): From 43ca0432c15acf71c55c604b20b64f49796fce59 Mon Sep 17 00:00:00 2001 From: Jack Wolfard <31635014+JackWolfard@users.noreply.github.com> Date: Thu, 9 Jan 2025 07:40:53 -0800 Subject: [PATCH 107/465] Add JDK 21 toolchain for `linux_riscv64` Copybara Import from https://github.com/bazelbuild/rules_java/pull/258 BEGIN_PUBLIC Add JDK 21 toolchain for `linux_riscv64` (#258) A Googler will need to help add the mirror for Adoptium Temurin's 21.0.4+7 JDK release for `linux_riscv64` * https://bazel.googlesource.com/continuous-integration/+/refs/heads/master/docs/mirror.md Closes #258 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/258 from JackWolfard:jdk21-riscv64 4df051dd531cd3300a52ec366978b465d2fe68e5 PiperOrigin-RevId: 713668463 Change-Id: I2b7f15bcef430654077df27475dedd4453a1d9ce --- MODULE.bazel | 1 + java/bazel/repositories_util.bzl | 2 +- java/repositories.bzl | 8 ++++++++ test/repo/MODULE.bazel | 1 + 4 files changed, 11 insertions(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index a5853237..4c977bf4 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -72,6 +72,7 @@ JDKS = { "linux", "linux_aarch64", "linux_ppc64le", + "linux_riscv64", "linux_s390x", "macos", "macos_aarch64", diff --git a/java/bazel/repositories_util.bzl b/java/bazel/repositories_util.bzl index 7e9efbd2..fce641dc 100644 --- a/java/bazel/repositories_util.bzl +++ b/java/bazel/repositories_util.bzl @@ -82,7 +82,7 @@ _RELEASE_CONFIGS = { "adoptium": { "release": "21.0.4+7", "platforms": { - "linux": ["ppc", "s390x"], + "linux": ["ppc", "riscv64", "s390x"], }, }, }, diff --git a/java/repositories.bzl b/java/repositories.bzl index f02b0f66..cb605439 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -310,6 +310,14 @@ _REMOTE_JDK_CONFIGS_LIST = [ urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.4_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.4_7.tar.gz"], version = "21", ), + struct( + name = "remotejdk21_linux_riscv64", + target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:riscv64"], + sha256 = "b04fd7f52d18268a935f1a7144dae802b25db600ec97156ddd46b3100cbd13da", + strip_prefix = "jdk-21.0.4+7", + urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_riscv64_linux_hotspot_21.0.4_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_riscv64_linux_hotspot_21.0.4_7.tar.gz"], + version = "21", + ), struct( name = "remotejdk21_linux_s390x", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:s390x"], diff --git a/test/repo/MODULE.bazel b/test/repo/MODULE.bazel index c582bf40..1be13d43 100644 --- a/test/repo/MODULE.bazel +++ b/test/repo/MODULE.bazel @@ -37,6 +37,7 @@ use_repo( "remotejdk17_win", "remotejdk17_win_arm64", "remotejdk21_linux", + "remotejdk21_linux_riscv64", "remotejdk21_macos", "remotejdk21_macos_aarch64", "remotejdk21_win", From 4e2b65fb792f61ae10cdc5e2f143d3ac8b942926 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 14 Jan 2025 00:55:39 -0800 Subject: [PATCH 108/465] Fix buildifier warning suppression for `@rules_java` The warning categories were changed in the most recent release. PiperOrigin-RevId: 715273098 Change-Id: I4669296002c661c8515853754c1d718c2e1be248 --- java/private/native.bzl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java/private/native.bzl b/java/private/native.bzl index 22f84ffb..e6be6f74 100644 --- a/java/private/native.bzl +++ b/java/private/native.bzl @@ -23,13 +23,13 @@ # Unused with Bazel@HEAD, used by the compatibility layer for older Bazel versions -# buildifier: disable=native-java +# buildifier: disable=native-java-common native_java_common = java_common -# buildifier: disable=native-java +# buildifier: disable=native-java-info NativeJavaInfo = JavaInfo -# buildifier: disable=native-java +# buildifier: disable=native-java-plugin-info NativeJavaPluginInfo = JavaPluginInfo # Used for some private native APIs that we can't replicate just yet in Starlark From b4b04664be5b75e690e7a75b91b3f9091521d5ab Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 14 Jan 2025 06:31:57 -0800 Subject: [PATCH 109/465] Move `java_stub_template.txt` out of Bazel and into `@rules_java` The copy in Bazel can be deleted once we update Bazel to a `rules_java` version containing this change. PiperOrigin-RevId: 715357586 Change-Id: I14878f635aad7270854d7bcc29c05de9bff8af87 --- java/bazel/rules/bazel_java_binary.bzl | 2 +- java/bazel/rules/java_stub_template.txt | 410 ++++++++++++++++++++++++ java/common/java_semantics.bzl | 2 +- 3 files changed, 412 insertions(+), 2 deletions(-) create mode 100644 java/bazel/rules/java_stub_template.txt diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl index 46e708c3..75bc6eab 100644 --- a/java/bazel/rules/bazel_java_binary.bzl +++ b/java/bazel/rules/bazel_java_binary.bzl @@ -363,7 +363,7 @@ def make_java_binary(executable):

The wrapper script accepts several unique flags. Refer to - //src/main/java/com/google/devtools/build/lib/bazel/rules/java/java_stub_template.txt + java_stub_template.txt for a list of configurable flags and environment variables accepted by the wrapper.

diff --git a/java/bazel/rules/java_stub_template.txt b/java/bazel/rules/java_stub_template.txt new file mode 100644 index 00000000..115b46e6 --- /dev/null +++ b/java/bazel/rules/java_stub_template.txt @@ -0,0 +1,410 @@ +#!/usr/bin/env bash +# Copyright 2014 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. +# +# This script was generated from java_stub_template.txt. Please +# don't edit it directly. +# +# If present, these flags should either be at the beginning of the command +# line, or they should be wrapped in a --wrapper_script_flag=FLAG argument. +# +# --debug Launch the JVM in remote debugging mode listening +# --debug= to the specified port or the port set in the +# DEFAULT_JVM_DEBUG_PORT environment variable (e.g. +# 'export DEFAULT_JVM_DEBUG_PORT=8000') or else the +# default port of 5005. The JVM starts suspended +# unless the DEFAULT_JVM_DEBUG_SUSPEND environment +# variable is set to 'n'. +# --main_advice= Run an alternate main class with the usual main +# program and arguments appended as arguments. +# --main_advice_classpath= +# Prepend additional class path entries. +# --jvm_flag= Pass to the "java" command itself. +# may contain spaces. Can be used multiple times. +# --jvm_flags= Pass space-separated flags to the "java" command +# itself. Can be used multiple times. +# --singlejar Start the program from the packed-up deployment +# jar rather than from the classpath. +# --print_javabin Print the location of java executable binary and exit. +# --classpath_limit= +# Specify the maximum classpath length. If the classpath +# is shorter, this script passes it to Java as a command +# line flag, otherwise it creates a classpath jar. +# +# The remainder of the command line is passed to the program. + +set -o posix + +# Make it easy to insert 'set -x' or similar commands when debugging problems with this script. +eval "$JAVA_STUB_DEBUG" + +# Prevent problems where the caller has exported CLASSPATH, causing our +# computed value to be copied into the environment and double-counted +# against the argv limit. +unset CLASSPATH + +JVM_FLAGS_CMDLINE=() + +# Processes an argument for the wrapper. Returns 0 if the given argument +# was recognized as an argument for this wrapper, and 1 if it was not. +function process_wrapper_argument() { + case "$1" in + --debug) JVM_DEBUG_PORT="${DEFAULT_JVM_DEBUG_PORT:-5005}" ;; + --debug=*) JVM_DEBUG_PORT="${1#--debug=}" ;; + --main_advice=*) MAIN_ADVICE="${1#--main_advice=}" ;; + --main_advice_classpath=*) MAIN_ADVICE_CLASSPATH="${1#--main_advice_classpath=}" ;; + --jvm_flag=*) JVM_FLAGS_CMDLINE+=( "${1#--jvm_flag=}" ) ;; + --jvm_flags=*) JVM_FLAGS_CMDLINE+=( ${1#--jvm_flags=} ) ;; + --singlejar) SINGLEJAR=1 ;; + --print_javabin) PRINT_JAVABIN=1 ;; + --classpath_limit=*) + CLASSPATH_LIMIT="${1#--classpath_limit=}" + echo "$CLASSPATH_LIMIT" | grep -q '^[0-9]\+$' || \ + die "ERROR: $self failed, --classpath_limit is not a number" + ;; + *) + return 1 ;; + esac + return 0 +} + +die() { + printf "%s: $1\n" "$0" "${@:2}" >&2 + exit 1 +} + +# Windows +function is_windows() { + [[ "${OSTYPE}" =~ msys* ]] || [[ "${OSTYPE}" =~ cygwin* ]] +} + +# macOS +function is_macos() { + [[ "${OSTYPE}" =~ darwin* ]] +} + +function available_utf8_locale() { + # Both C.UTF-8 and en_US.UTF-8 do not cause any language-specific effects + # when set as LC_CTYPE, but neither is certain to exist on all systems. + # + # https://github.com/bazelbuild/bazel/pull/17670: Note that the use of "env" + # is important in these calls. Without "env", bash itself seems to pick up + # the LC_CTYPE change as soon as the variable is defined and may emit a + # warning when the locale files are not present. By using "env", bash never + # sees the change and the 2>/dev/null redirection does the right thing. + if [[ "$(env LC_CTYPE=C.UTF-8 locale charmap 2>/dev/null)" == "UTF-8" ]]; then + echo "C.UTF-8" + elif [[ "$(env LC_CTYPE=en_US.UTF-8 locale charmap 2>/dev/null)" == "UTF-8" ]]; then + echo "en_US.UTF-8" + fi +} + +# Parse arguments sequentially until the first unrecognized arg is encountered. +# Scan the remaining args for --wrapper_script_flag=X options and process them. +ARGS=() +for ARG in "$@"; do + if [[ "$ARG" == --wrapper_script_flag=* ]]; then + process_wrapper_argument "${ARG#--wrapper_script_flag=}" \ + || die "invalid wrapper argument '%s'" "$ARG" + elif [[ "${#ARGS}" -gt 0 ]] || ! process_wrapper_argument "$ARG"; then + ARGS+=( "$ARG" ) + fi +done + +# Find our runfiles tree. We need this to construct the classpath +# (unless --singlejar was passed). +# +# Call this program X. X was generated by a java_binary or java_test rule. +# X may be invoked in many ways: +# 1a) directly by a user, with $0 in the output tree +# 1b) via 'bazel run' (similar to case 1a) +# 2) directly by a user, with $0 in X's runfiles tree +# 3) by another program Y which has a data dependency on X, with $0 in Y's runfiles tree +# 4) via 'bazel test' +# 5) by a genrule cmd, with $0 in the output tree +# 6) case 3 in the context of a genrule +# +# For case 1, $0 will be a regular file, and the runfiles tree will be +# at $0.runfiles. +# For case 2, $0 will be a symlink to the file seen in case 1. +# For case 3, we use Y's runfiles tree, which will be a superset of X's. +# For case 4, $JAVA_RUNFILES and $TEST_SRCDIR should already be set. +# Case 5 is handled like case 1. +# Case 6 is handled like case 3. + +# If we are running on Windows, convert the windows style path +# to unix style for detecting runfiles path. +if is_windows; then + self=$(cygpath --unix "$0") +else + self="$0" +fi + +if [[ "$self" != /* ]]; then + self="$PWD/$self" +fi + +if [[ "$SINGLEJAR" != 1 || "%needs_runfiles%" == 1 ]]; then + if [[ -z "$JAVA_RUNFILES" ]]; then + while true; do + if [[ -e "$self.runfiles" ]]; then + JAVA_RUNFILES="$self.runfiles" + break + fi + if [[ $self == *.runfiles/* ]]; then + JAVA_RUNFILES="${self%.runfiles/*}.runfiles" + break + fi + if [[ ! -L "$self" ]]; then + break + fi + readlink="$(readlink "$self")" + if [[ "$readlink" = /* ]]; then + self="$readlink" + else + # resolve relative symlink + self="${self%/*}/$readlink" + fi + done + if [[ -n "$JAVA_RUNFILES" ]]; then + export TEST_SRCDIR=${TEST_SRCDIR:-$JAVA_RUNFILES} + elif [[ -f "${self}_deploy.jar" && "%needs_runfiles%" == 0 ]]; then + SINGLEJAR=1; + else + die 'Cannot locate runfiles directory. (Set $JAVA_RUNFILES to inhibit searching.)' + fi + fi +fi + +# If we are running on Windows, we need a windows style runfiles path for constructing CLASSPATH +if is_windows; then + JAVA_RUNFILES=$(cygpath --windows "$JAVA_RUNFILES") +fi + +export JAVA_RUNFILES +export RUNFILES_MANIFEST_FILE="${JAVA_RUNFILES}/MANIFEST" +export RUNFILES_MANIFEST_ONLY=%runfiles_manifest_only% + +if [ -z "$RUNFILES_MANIFEST_ONLY" ]; then + function rlocation() { + if [[ "$1" = /* ]]; then + echo $1 + else + echo "$(dirname $RUNFILES_MANIFEST_FILE)/$1" + fi + } +else + if ! is_macos; then + # Read file into my_array + oifs=$IFS + IFS=$'\n' + my_array=( $(sed -e 's/\r//g' "$RUNFILES_MANIFEST_FILE") ) + IFS=$oifs + + # Process each runfile line into a [key,value] entry in runfiles_array + # declare -A is not supported on macOS because an old version of bash is used. + declare -A runfiles_array + for line in "${my_array[@]}" + do + line_split=($line) + runfiles_array[${line_split[0]}]=${line_split[@]:1} + done + fi + + function rlocation() { + if [[ "$1" = /* ]]; then + echo $1 + else + if is_macos; then + # Print the rest of line after the first space + # First, set the first column to empty and print rest of the line + # Second, use a trick of awk to remove leading and trailing spaces. + echo $(grep "^$1 " $RUNFILES_MANIFEST_FILE | awk '{ $1=""; print }' | awk '{ $1=$1; print }') + else + echo ${runfiles_array[$1]} + fi + fi + } +fi + +# Set JAVABIN to the path to the JVM launcher. +%javabin% + +if [[ "$PRINT_JAVABIN" == 1 || "%java_start_class%" == "--print_javabin" ]]; then + echo -n "$JAVABIN" + exit 0 +fi + +if [[ "$SINGLEJAR" == 1 ]]; then + CLASSPATH="${self}_deploy.jar" + # Check for the deploy jar now. If it doesn't exist, we can print a + # more helpful error message than the JVM. + [[ -r "$CLASSPATH" ]] \ + || die "Option --singlejar was passed, but %s does not exist.\n (You may need to build it explicitly.)" "$CLASSPATH" +else + # Create the shortest classpath we can, by making it relative if possible. + RUNPATH="${JAVA_RUNFILES}/%workspace_prefix%" + RUNPATH="${RUNPATH#$PWD/}" + CLASSPATH=%classpath% +fi + +# Export the locations which will be used to find the location of the classes from the classpath file. +export SELF_LOCATION="$self" +export CLASSLOADER_PREFIX_PATH="${RUNPATH}" + +# If using Jacoco in offline instrumentation mode, the CLASSPATH contains instrumented files. +# We need to make the metadata jar with uninstrumented classes available for generating +# the lcov-compatible coverage report, and we don't want it on the classpath. +%set_jacoco_metadata% +%set_jacoco_main_class% +%set_jacoco_java_runfiles_root% +# export JACOCO_IS_JAR_WRAPPED for compatibility with older versions of +# JacocoCoverageRunner that check for this and not CLASSPATH_JAR +# TODO(cmita): Remove when this is no longer required +export JACOCO_IS_JAR_WRAPPED=0 +export CLASSPATH_JAR="" + +if [[ -n "$JVM_DEBUG_PORT" ]]; then + JVM_DEBUG_SUSPEND=${DEFAULT_JVM_DEBUG_SUSPEND:-"y"} + JVM_DEBUG_FLAGS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=${JVM_DEBUG_SUSPEND},address=${JVM_DEBUG_PORT}" +fi + +if [[ -n "$MAIN_ADVICE_CLASSPATH" ]]; then + CLASSPATH="${MAIN_ADVICE_CLASSPATH}:${CLASSPATH}" +fi + +# Check if TEST_TMPDIR is available to use for scratch. +if [[ -n "$TEST_TMPDIR" && -d "$TEST_TMPDIR" ]]; then + JVM_FLAGS+=" -Djava.io.tmpdir=$TEST_TMPDIR" +fi + +ARGS=( + ${JVM_DEBUG_FLAGS} + ${JVM_FLAGS} + %jvm_flags% + "${JVM_FLAGS_CMDLINE[@]}" + ${MAIN_ADVICE} + %java_start_class% + "${ARGS[@]}") + + +# Creates a JAR containing the classpath and put the result to stdout +function create_classpath_jar() { + # Build class path. + MANIFEST_CLASSPATH=() + if is_windows; then + CLASSPATH_SEPARATOR=";" + else + CLASSPATH_SEPARATOR=":" + fi + + OLDIFS="$IFS" + IFS="${CLASSPATH_SEPARATOR}" # Use a custom separator for the loop. + current_dir=$(pwd) + for path in ${CLASSPATH}; do + # Loop through the characters of the path and convert characters that are + # not alphanumeric nor -_.~/ to their 2-digit hexadecimal representation + if [[ ! $path =~ ^[-_.~/a-zA-Z0-9]*$ ]]; then + local i c buff + local converted_path="" + + for ((i=0; i<${#path}; i++)); do + c=${path:$i:1} + case ${c} in + [-_.~/a-zA-Z0-9] ) buff=${c} ;; + * ) printf -v buff '%%%02x' "'$c'" + esac + converted_path+="${buff}" + done + path=${converted_path} + fi + + if is_windows; then + path="file:/${path}" # e.g. "file:/C:/temp/foo.jar" + else + # If not absolute, qualify the path + case "${path}" in + /*) ;; # Already an absolute path + *) path="${current_dir}/${path}";; # Now qualified + esac + path="file:${path}" # e.g. "file:/usr/local/foo.jar" + fi + + MANIFEST_CLASSPATH+=("${path}") + done + IFS="$OLDIFS" + + # Create manifest file + MANIFEST_FILE="$(mktemp -t XXXXXXXX.jar_manifest)" + ( + echo "Manifest-Version: 1.0" + + CLASSPATH_LINE="Class-Path: ${MANIFEST_CLASSPATH[*]}" + CLASSPATH_MANIFEST_LINES=$(sed -E $'s/(.{71})/\\1\\\n /g' <<< "${CLASSPATH_LINE}") + + echo "$CLASSPATH_MANIFEST_LINES" + echo "Created-By: Bazel" + ) >$MANIFEST_FILE + + # Create classpath JAR file + MANIFEST_JAR_FILE="$(mktemp -t XXXXXXXX-classpath.jar)" + if is_windows; then + MANIFEST_JAR_FILE="$(cygpath --windows "$MANIFEST_JAR_FILE")" + MANIFEST_FILE="$(cygpath --windows "$MANIFEST_FILE")" + fi + if is_windows; then + JARBIN="${JARBIN:=${JAVABIN%/java.exe}/jar.exe}" + else + JARBIN="${JARBIN:=${JAVABIN%/java}/jar}" + fi + $JARBIN cvfm "$MANIFEST_JAR_FILE" "$MANIFEST_FILE" >/dev/null || \ + die "ERROR: $self failed because $JARBIN failed" + rm -f "$MANIFEST_FILE" + + echo "$MANIFEST_JAR_FILE" +} + +# If the user didn't specify a --classpath_limit, use the default value. +if [ -z "$CLASSPATH_LIMIT" ]; then + # Windows per-arg limit MAX_ARG_STRLEN == 8k + # Linux per-arg limit MAX_ARG_STRLEN == 128k + is_windows && CLASSPATH_LIMIT=7000 || CLASSPATH_LIMIT=120000 +fi + +# On non-macOS Unix, without any locale variable set, the JVM would use +# using ASCII rather than UTF-8 as the encoding for file system paths. +if ! is_macos; then + if [ -z ${LC_CTYPE+x} ] && [ -z ${LC_ALL+x} ] && [ -z ${LANG+x} ]; then + UTF8_LOCALE=$(available_utf8_locale) + if [[ -n "$UTF8_LOCALE" ]]; then + export LC_CTYPE="$UTF8_LOCALE" + fi + fi +fi + +if (("${#CLASSPATH}" > ${CLASSPATH_LIMIT})); then + # TODO(cmtia): Remove JACOCO_IS_JAR_WRAPPED when JacocoCoverageRunner will + # never need it anymore. + export JACOCO_IS_JAR_WRAPPED=1 + CLASSPATH_MANIFEST_JAR=$(create_classpath_jar) + export CLASSPATH_JAR="$(basename $CLASSPATH_MANIFEST_JAR)" + "$JAVABIN" -classpath "$CLASSPATH_MANIFEST_JAR" "${ARGS[@]}" + exit_code=$? + rm -f "$CLASSPATH_MANIFEST_JAR" + exit $exit_code +else + export JACOCO_IS_JAR_WRAPPED=0 + export CLASSPATH_JAR="" + exec "$JAVABIN" -classpath $CLASSPATH "${ARGS[@]}" +fi diff --git a/java/common/java_semantics.bzl b/java/common/java_semantics.bzl index a08717b7..87873938 100644 --- a/java/common/java_semantics.bzl +++ b/java/common/java_semantics.bzl @@ -91,7 +91,7 @@ semantics = struct( ], ALLOWED_RULES_IN_DEPS_WITH_WARNING = [], LINT_PROGRESS_MESSAGE = "Running Android Lint for: %{label}", - JAVA_STUB_TEMPLATE_LABEL = "@bazel_tools//tools/jdk:java_stub_template.txt", + JAVA_STUB_TEMPLATE_LABEL = "@rules_java//java/bazel/rules:java_stub_template.txt", # copybara-use-repo-external-label BUILD_INFO_TRANSLATOR_LABEL = "@bazel_tools//tools/build_defs/build_info:java_build_info", JAVA_TEST_RUNNER_LABEL = "@bazel_tools//tools/jdk:TestRunner", IS_BAZEL = True, From 503773e7aaa9faf8f425bc6efeddefd0d69c60a8 Mon Sep 17 00:00:00 2001 From: "Ian (Hee) Cha" Date: Tue, 14 Jan 2025 11:23:19 -0800 Subject: [PATCH 110/465] Update rules_java to 8.7.0 and java_tools to 13.14 Copybara Import from https://github.com/bazelbuild/rules_java/pull/262 BEGIN_PUBLIC Update rules_java to 8.7.0 and java_tools to 13.14 (#262) Closes #262 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/262 from bazelbuild:java_v13.14 514125f4c2a18d3bf1e8d50171b92dede83287d3 PiperOrigin-RevId: 715457256 Change-Id: I5e1c32de637ba1cfa6333c9665bfc706d94c0d9a --- MODULE.bazel | 2 +- java/repositories.bzl | 33 ++++++++++++++++----------------- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 4c977bf4..b18c7e34 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.6.3", + version = "8.7.0", bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) diff --git a/java/repositories.bzl b/java/repositories.bzl index cb605439..2b95739c 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,34 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.13", + "version": "v13.14", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.13/java_tools_linux-v13.13.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.13/java_tools_linux-v13.13.zip", - "sha": "60c10e91f5900801423f9c5b020cc0c7da16dbaeee9c22891b38e7017306a8e7", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.14/java_tools_linux-v13.14.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.14/java_tools_linux-v13.14.zip", + "sha": "81c7645005cea3e332edf478a7a3a4305bdc50921b0fb865a13e3d82f6ff8288", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.13/java_tools_windows-v13.13.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.13/java_tools_windows-v13.13.zip", - "sha": "f5de3f2afc49d1a457efa63926bcc0ca4cdb5fc4887160bf9163e49f059dd12c", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.14/java_tools_windows-v13.14.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.14/java_tools_windows-v13.14.zip", + "sha": "672ff6b3bd42824cc60b9bf8321be24f20cccf9531022e6f9db445cae16ff30d", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.13/java_tools_darwin_x86_64-v13.13.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.13/java_tools_darwin_x86_64-v13.13.zip", - "sha": "d002ff57bd5e36d6d69a1c282fa571841816a1ccc5d28060cf7fe4c7257e376a", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.14/java_tools_darwin_x86_64-v13.14.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.14/java_tools_darwin_x86_64-v13.14.zip", + "sha": "4e23bc21453aa35fcc3621fab0e4b056d33d7a86e72198f6b7b6d23073299cb1", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.13/java_tools_darwin_arm64-v13.13.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.13/java_tools_darwin_arm64-v13.13.zip", - "sha": "6d4b4e3a12cc5fd9f600b383465d0860afd5c11ba7c7386867bb621a55fa8452", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.14/java_tools_darwin_arm64-v13.14.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.14/java_tools_darwin_arm64-v13.14.zip", + "sha": "709abb61f7a5e4855ab7f875b3ae6ccab168ff61115ced37cab1c8ec70e58408", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.13/java_tools-v13.13.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.13/java_tools-v13.13.zip", - "sha": "df895d5067f2dad4524109ebfddac442d2514d0e2f95f6abc098cfae98b9bbb5", - "build_file": "@rules_java//toolchains:BUILD.java_tools", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.14/java_tools-v13.14.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.14/java_tools-v13.14.zip", + "sha": "6cdab4ced656b1ec0ed3132436b711e9dc983d556f76397bbb79e3125a41b88c", }, }, } From 90aad63ffca68bf14c825ecdbac9d33e9c75c998 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 16 Jan 2025 06:52:26 -0800 Subject: [PATCH 111/465] Make `java_stub_template.txt` visible to Bazel tests PiperOrigin-RevId: 716217901 Change-Id: I8c571d43c9dcfbcb219f8bbe69ab472887a75001 --- java/bazel/rules/BUILD.bazel | 1 + 1 file changed, 1 insertion(+) diff --git a/java/bazel/rules/BUILD.bazel b/java/bazel/rules/BUILD.bazel index 0ffa9d43..65d0637a 100644 --- a/java/bazel/rules/BUILD.bazel +++ b/java/bazel/rules/BUILD.bazel @@ -39,6 +39,7 @@ filegroup( testonly = 1, srcs = [ "BUILD.bazel", + ":java_stub_template.txt", ":rules", ], visibility = ["//java:__pkg__"], From ff22cbad9e1ca2a5d35ffa903398176b1baf1c69 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 16 Jan 2025 07:24:19 -0800 Subject: [PATCH 112/465] Stop wrapping `JavaInfo` into native instances PiperOrigin-RevId: 716226895 Change-Id: I6315595317d4d1c638f610fb91a932231ed8d48b --- java/private/java_info.bzl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java/private/java_info.bzl b/java/private/java_info.bzl index 3b68e69e..8a3b5e42 100644 --- a/java/private/java_info.bzl +++ b/java/private/java_info.bzl @@ -183,7 +183,7 @@ def merge( transitive = [p.transitive_native_libraries for p in providers], ), ) - return get_internal_java_common().wrap_java_info(_new_javainfo(**result)) + return _new_javainfo(**result) def to_java_binary_info(java_info, compilation_info): """Get a copy of the given JavaInfo with minimal info returned by a java_binary @@ -518,7 +518,7 @@ def java_info_for_compilation( compilation_info = None, annotation_processing = None, ) - return get_internal_java_common().wrap_java_info(_new_javainfo(**result)) + return _new_javainfo(**result) def _validate_provider_list(provider_list, what, expected_provider_type): get_internal_java_common().check_provider_instances(provider_list, what, expected_provider_type) From b2a442678e4bbbf5662e057e04396dd2a5aaed00 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 16 Jan 2025 07:31:44 -0800 Subject: [PATCH 113/465] Release `@rules_java` `v8.7.1` PiperOrigin-RevId: 716228887 Change-Id: Ibe946e0bcea3fe81832dff2f43597dc6617772b8 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index b18c7e34..d5375b12 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.7.0", + version = "8.7.1", bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) From 61be667fcfbaa6c1764ac17a19f12a6f31a28cb3 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 21 Jan 2025 00:22:42 -0800 Subject: [PATCH 114/465] Load `CcInfo` from `@rules_cc` Work towards https://github.com/bazelbuild/rules_java/issues/264 PiperOrigin-RevId: 717777242 Change-Id: Id67215cd661b5298eec9f9952dd3de87c7ece8da --- java/common/rules/java_import.bzl | 1 + 1 file changed, 1 insertion(+) diff --git a/java/common/rules/java_import.bzl b/java/common/rules/java_import.bzl index 4a22b2ab..a6e9712f 100644 --- a/java/common/rules/java_import.bzl +++ b/java/common/rules/java_import.bzl @@ -16,6 +16,7 @@ Definition of java_import rule. """ +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_semantics.bzl", "semantics") load("//java/private:java_info.bzl", "JavaInfo") From 5d36db2674d954b0c332656c8e76ddae4df3e64a Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 24 Jan 2025 01:45:17 -0800 Subject: [PATCH 115/465] Make `java_stub_template.txt` visible to `@bazel_tools` Once this is released, `@bazel_tools` can re-export this publicly to preserve the old behavior. This is just temporary to avoid breaking any users for now. The plan is to drop this in the next major version bump. PiperOrigin-RevId: 719206974 Change-Id: Ic99680e46507530f1c485429c291db934b3084f2 --- java/bazel/rules/BUILD.bazel | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/java/bazel/rules/BUILD.bazel b/java/bazel/rules/BUILD.bazel index 65d0637a..00fa30ba 100644 --- a/java/bazel/rules/BUILD.bazel +++ b/java/bazel/rules/BUILD.bazel @@ -44,3 +44,9 @@ filegroup( ], visibility = ["//java:__pkg__"], ) + +# TODO: remove this in the next major version (rules_java 9.x / Bazel 9.x) +exports_files( + ["java_stub_template.txt"], + visibility = ["@bazel_tools//tools/java:__pkg__"], +) From f26a240c3392f0ae45a2ce3244c93713d7539611 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 24 Jan 2025 01:50:14 -0800 Subject: [PATCH 116/465] Release `@rules_java` `v8.7.2` PiperOrigin-RevId: 719208295 Change-Id: I07239a7b669750ab209dfcef31f9ecffd1c86630 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index d5375b12..4a67f3ca 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.7.1", + version = "8.7.2", bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) From ba93bb21e833fd7eb20934e83225f683c9052600 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 29 Jan 2025 06:06:31 -0800 Subject: [PATCH 117/465] Reorganize `@rules_java//java/test` and `@rules_java//test/` to mirror the directory layout of the code paths they exercise PiperOrigin-RevId: 720945024 Change-Id: I9fb37b1a191b8d8be956f99ec47c89ade48600d7 --- java/test/BUILD | 3 --- java/test/common/rules/BUILD | 3 +++ java/test/{ => common/rules}/merge_attrs_tests.bzl | 0 .../test/java/com/google/devtools/build/runfiles/BUILD.bazel | 0 .../java/com/google/devtools/build/runfiles/RunfilesTest.java | 0 .../test/java/com/google/devtools/build/runfiles/UtilTest.java | 0 test/{analysis => toolchains}/BUILD.bazel | 0 test/{analysis => toolchains}/bootclasspath_tests.bzl | 0 8 files changed, 3 insertions(+), 3 deletions(-) create mode 100644 java/test/common/rules/BUILD rename java/test/{ => common/rules}/merge_attrs_tests.bzl (100%) rename {test => java/test}/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel (100%) rename {test => java/test}/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java (100%) rename {test => java/test}/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java (100%) rename test/{analysis => toolchains}/BUILD.bazel (100%) rename test/{analysis => toolchains}/bootclasspath_tests.bzl (100%) diff --git a/java/test/BUILD b/java/test/BUILD index 8a52e410..e69de29b 100644 --- a/java/test/BUILD +++ b/java/test/BUILD @@ -1,3 +0,0 @@ -load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") - -merge_attrs_test_suite(name = "merge_attrs_tests") diff --git a/java/test/common/rules/BUILD b/java/test/common/rules/BUILD new file mode 100644 index 00000000..8a52e410 --- /dev/null +++ b/java/test/common/rules/BUILD @@ -0,0 +1,3 @@ +load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") + +merge_attrs_test_suite(name = "merge_attrs_tests") diff --git a/java/test/merge_attrs_tests.bzl b/java/test/common/rules/merge_attrs_tests.bzl similarity index 100% rename from java/test/merge_attrs_tests.bzl rename to java/test/common/rules/merge_attrs_tests.bzl diff --git a/test/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel b/java/test/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel similarity index 100% rename from test/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel rename to java/test/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel diff --git a/test/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java b/java/test/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java similarity index 100% rename from test/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java rename to java/test/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java diff --git a/test/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java b/java/test/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java similarity index 100% rename from test/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java rename to java/test/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java diff --git a/test/analysis/BUILD.bazel b/test/toolchains/BUILD.bazel similarity index 100% rename from test/analysis/BUILD.bazel rename to test/toolchains/BUILD.bazel diff --git a/test/analysis/bootclasspath_tests.bzl b/test/toolchains/bootclasspath_tests.bzl similarity index 100% rename from test/analysis/bootclasspath_tests.bzl rename to test/toolchains/bootclasspath_tests.bzl From c69bae2345e7f272eea05b6f60b98b056e640087 Mon Sep 17 00:00:00 2001 From: "Ian (Hee) Cha" Date: Thu, 30 Jan 2025 01:21:07 -0800 Subject: [PATCH 118/465] Update rules_java to 8.8.0 and java_tools to 13.15 Copybara Import from https://github.com/bazelbuild/rules_java/pull/269 BEGIN_PUBLIC Update rules_java to 8.8.0 and java_tools to 13.15 (#269) Closes #269 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/269 from bazelbuild:java_v13.15 743ba75029b9c2a2bb7ad9c93e5c566b9a22b118 PiperOrigin-RevId: 721293414 Change-Id: Icd9c9b8c472e3c6b1202e551393d38a3ddc9f103 --- MODULE.bazel | 2 +- java/repositories.bzl | 32 ++++++++++++++++---------------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 4a67f3ca..7394031d 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.7.2", + version = "8.8.0", bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) diff --git a/java/repositories.bzl b/java/repositories.bzl index 2b95739c..c7c0a724 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.14", + "version": "v13.15", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.14/java_tools_linux-v13.14.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.14/java_tools_linux-v13.14.zip", - "sha": "81c7645005cea3e332edf478a7a3a4305bdc50921b0fb865a13e3d82f6ff8288", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.15/java_tools_linux-v13.15.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.15/java_tools_linux-v13.15.zip", + "sha": "74842dd84695133b22407a7eb0969ffdeb34179d0a31428f740c83eee28b8ca7", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.14/java_tools_windows-v13.14.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.14/java_tools_windows-v13.14.zip", - "sha": "672ff6b3bd42824cc60b9bf8321be24f20cccf9531022e6f9db445cae16ff30d", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.15/java_tools_windows-v13.15.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.15/java_tools_windows-v13.15.zip", + "sha": "afcf14d1e24ee22dc37c76c911e0c37bc38ccd09a15f2aad5f692d7b0a6b158c", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.14/java_tools_darwin_x86_64-v13.14.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.14/java_tools_darwin_x86_64-v13.14.zip", - "sha": "4e23bc21453aa35fcc3621fab0e4b056d33d7a86e72198f6b7b6d23073299cb1", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.15/java_tools_darwin_x86_64-v13.15.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.15/java_tools_darwin_x86_64-v13.15.zip", + "sha": "b0d60beb1455e6ec8626e59da556fb0fa757b9732622f5c7615bb7e906922f52", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.14/java_tools_darwin_arm64-v13.14.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.14/java_tools_darwin_arm64-v13.14.zip", - "sha": "709abb61f7a5e4855ab7f875b3ae6ccab168ff61115ced37cab1c8ec70e58408", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.15/java_tools_darwin_arm64-v13.15.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.15/java_tools_darwin_arm64-v13.15.zip", + "sha": "3d3494577a476153cfb1bef33f3156dc7749d491049320248511ee58c7e3a4b6", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.14/java_tools-v13.14.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.14/java_tools-v13.14.zip", - "sha": "6cdab4ced656b1ec0ed3132436b711e9dc983d556f76397bbb79e3125a41b88c", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.15/java_tools-v13.15.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.15/java_tools-v13.15.zip", + "sha": "3d46e272172fe61ceabc324633ce3a06d40df3ab4d79e94ab55ed759369a0b5b", }, }, } From 4aa66735ea294529cb9c5a64b8402365d0f07068 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 30 Jan 2025 04:22:05 -0800 Subject: [PATCH 119/465] Improve `android_support_tests.bzl` Adds a custom provider subject for `JavaInfo` and the test now reads better and reports more helpful failure messages. This will also ease migrating more java rules tests out of the Bazel codebase. PiperOrigin-RevId: 721338635 Change-Id: I36269cf04de67698bbf3be3bec9507d12a55d895 --- java/test/private/BUILD | 20 +----- java/test/private/Foo.java | 1 - java/test/private/MyPlugin.java | 1 - java/test/private/android_support_tests.bzl | 38 ++++++++---- java/test/testutil/BUILD | 0 java/test/testutil/java_info_subject.bzl | 67 +++++++++++++++++++++ 6 files changed, 95 insertions(+), 32 deletions(-) delete mode 100644 java/test/private/Foo.java delete mode 100644 java/test/private/MyPlugin.java create mode 100644 java/test/testutil/BUILD create mode 100644 java/test/testutil/java_info_subject.bzl diff --git a/java/test/private/BUILD b/java/test/private/BUILD index 4938f734..0123c92f 100644 --- a/java/test/private/BUILD +++ b/java/test/private/BUILD @@ -11,24 +11,6 @@ # 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("//java:defs.bzl", "java_library", "java_plugin") -load(":android_support_tests.bzl", "android_support_tests", "my_rule") - -java_plugin( - name = "my_plugin", - srcs = ["MyPlugin.java"], -) - -java_library( - name = "foo", - srcs = ["Foo.java"], - exported_plugins = [":my_plugin"], -) - -my_rule( - name = "bar", - dep = ":foo", -) +load(":android_support_tests.bzl", "android_support_tests") android_support_tests(name = "android_support_tests") diff --git a/java/test/private/Foo.java b/java/test/private/Foo.java deleted file mode 100644 index 4a2b44da..00000000 --- a/java/test/private/Foo.java +++ /dev/null @@ -1 +0,0 @@ -public class Foo {} diff --git a/java/test/private/MyPlugin.java b/java/test/private/MyPlugin.java deleted file mode 100644 index 2747e676..00000000 --- a/java/test/private/MyPlugin.java +++ /dev/null @@ -1 +0,0 @@ -public class MyPlugin {} diff --git a/java/test/private/android_support_tests.bzl b/java/test/private/android_support_tests.bzl index 91f38c09..5bc07d90 100644 --- a/java/test/private/android_support_tests.bzl +++ b/java/test/private/android_support_tests.bzl @@ -14,8 +14,11 @@ """Tests for //java/private:android_support.bzl""" load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java:defs.bzl", "java_library", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") load("//java/private:android_support.bzl", "android_support") +load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") def _impl(ctx): return [ @@ -30,25 +33,38 @@ my_rule = rule( ) def _test_enable_implicit_sourceless_deps_exports_compatibility(name): + util.helper_target( + java_plugin, + name = "my_plugin", + srcs = ["MyPlugin.java"], + ) + util.helper_target( + java_library, + name = "base", + srcs = ["Foo.java"], + exported_plugins = [":my_plugin"], + ) + util.helper_target( + my_rule, + name = "transformed", + dep = ":base", + ) + analysis_test( name = name, impl = _test_enable_implicit_sourceless_deps_exports_compatibility_impl, targets = { - "foo": Label(":foo"), - "bar": Label(":bar"), + "base": Label(":base"), + "transformed": Label(":transformed"), }, ) def _test_enable_implicit_sourceless_deps_exports_compatibility_impl(env, targets): - # TODO(hvd): write a ProviderSubject for JavaInfo - foo_javainfo = targets.foo[JavaInfo] - bar_javainfo = targets.bar[JavaInfo] - for attr in ["transitive_runtime_jars", "compile_jars", "transitive_compile_time_jars", "full_compile_jars", "_transitive_full_compile_time_jars", "_compile_time_java_dependencies"]: - env.expect.that_bool(getattr(foo_javainfo, attr) == getattr(bar_javainfo, attr)).equals(True) - env.expect.that_depset_of_files(foo_javainfo.plugins.processor_jars).contains_exactly([ - "java/test/private/libmy_plugin.jar", - ]) - env.expect.that_depset_of_files(bar_javainfo.plugins.processor_jars).contains_exactly([]) + base_info = java_info_subject.from_target(env, targets.base) + transformed_info = java_info_subject.from_target(env, targets.transformed) + transformed_info.compilation_args().equals(base_info.compilation_args()) + base_info.plugins().processor_jars().contains_exactly(["{package}/libmy_plugin.jar"]) + transformed_info.plugins().processor_jars().contains_exactly([]) def android_support_tests(name): test_suite( diff --git a/java/test/testutil/BUILD b/java/test/testutil/BUILD new file mode 100644 index 00000000..e69de29b diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl new file mode 100644 index 00000000..f759172d --- /dev/null +++ b/java/test/testutil/java_info_subject.bzl @@ -0,0 +1,67 @@ +"""A custom @rules_testing subject for the JavaInfo provider""" + +load("@rules_testing//lib:truth.bzl", "subjects", "truth") +load("//java/common:java_info.bzl", "JavaInfo") + +def _new_java_info_subject(java_info, meta): + self = struct(actual = java_info, meta = meta.derive("JavaInfo")) + public = struct( + compilation_args = lambda: _new_java_compilation_args_subject(self.actual, self.meta), + plugins = lambda: _new_java_info_plugins_subject(self.actual, self.meta), + ) + return public + +def _java_info_subject_from_target(env, target): + return _new_java_info_subject(target[JavaInfo], meta = truth.expect(env).meta.derive( + format_str_kwargs = { + "name": target.label.name, + "package": target.label.package, + }, + )) + +def _new_java_compilation_args_subject(java_info, meta): + actual = struct( + transitive_runtime_jars = java_info.transitive_runtime_jars, + compile_jars = java_info.compile_jars, + transitive_compile_time_jars = java_info.transitive_compile_time_jars, + full_compile_jars = java_info.full_compile_jars, + _transitive_full_compile_time_jars = java_info._transitive_full_compile_time_jars, + _compile_time_java_dependencies = java_info._compile_time_java_dependencies, + _is_binary = getattr(java_info, "_is_binary", False), + ) + self = struct( + actual = actual, + meta = meta, + ) + return struct( + equals = lambda other: _java_compilation_args_equals(self, other), + self = self, + actual = actual, + ) + +def _java_compilation_args_equals(self, other): + if self.actual == other.actual: + return + for attr in dir(other.actual): + other_attr = getattr(other.actual, attr) + this_attr = getattr(self.actual, attr) + if this_attr != other_attr: + self.meta.derive(attr).add_failure( + "expected: {}".format(other_attr), + "actual: {}".format(this_attr), + ) + +def _new_java_info_plugins_subject(java_info, meta): + self = struct( + actual = java_info.plugins, + meta = meta.derive("plugins"), + ) + public = struct( + processor_jars = lambda: subjects.depset_file(self.actual.processor_jars, meta = self.meta.derive("processor_jars")), + ) + return public + +java_info_subject = struct( + new = _new_java_info_subject, + from_target = _java_info_subject_from_target, +) From 93fdd8af3a1087866425a9f162892cc521642698 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 30 Jan 2025 10:07:22 -0800 Subject: [PATCH 120/465] Add a test asseting that the JavaInfo returned by java_binary targets are marked as such. PiperOrigin-RevId: 721430757 Change-Id: Ia90863e31ef83407abbacc1c3f3b23907c59b46e --- .bazelci/presubmit.yml | 4 +++ java/test/common/rules/BUILD | 3 ++ java/test/common/rules/java_binary_tests.bzl | 30 ++++++++++++++++++++ java/test/private/android_support_tests.bzl | 2 +- java/test/testutil/java_info_subject.bzl | 12 ++++---- 5 files changed, 45 insertions(+), 6 deletions(-) create mode 100644 java/test/common/rules/java_binary_tests.bzl diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index d468b1b0..79f2e937 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -44,6 +44,8 @@ tasks: bazel: "7.4.0" build_targets: *build_targets test_targets: *test_targets + test_flags: + - "--test_tag_filters=-min_bazel_8" ubuntu2004_integration: name: "Bazel 7.x Integration" bazel: "7.4.0" @@ -117,6 +119,8 @@ tasks: platform: ubuntu2004 build_targets: *build_targets_bazel6 test_targets: *test_targets_bazel6 + test_flags: + - "--test_tag_filters=-min_bazel_7,-min_bazel_8" ubuntu2004_integration_bazel6: name: "Bazel 6.x Integration" bazel: 6.4.0 diff --git a/java/test/common/rules/BUILD b/java/test/common/rules/BUILD index 8a52e410..1045061a 100644 --- a/java/test/common/rules/BUILD +++ b/java/test/common/rules/BUILD @@ -1,3 +1,6 @@ +load(":java_binary_tests.bzl", "java_binary_tests") load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") merge_attrs_test_suite(name = "merge_attrs_tests") + +java_binary_tests(name = "java_binary_tests") diff --git a/java/test/common/rules/java_binary_tests.bzl b/java/test/common/rules/java_binary_tests.bzl new file mode 100644 index 00000000..2a20572a --- /dev/null +++ b/java/test/common/rules/java_binary_tests.bzl @@ -0,0 +1,30 @@ +"""Tests for the java_binary rule""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_binary.bzl", "java_binary") +load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") + +def _test_java_binary_provides_binary_java_info(name): + util.helper_target(java_binary, name = "bin", srcs = ["Main.java"]) + + analysis_test( + name = name, + impl = _test_java_binary_provides_binary_java_info_impl, + target = Label(":bin"), + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_java_binary_provides_binary_java_info_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.compilation_args().equals(None) + assert_java_info.is_binary().equals(True) + +def java_binary_tests(name): + test_suite( + name = name, + tests = [ + _test_java_binary_provides_binary_java_info, + ], + ) diff --git a/java/test/private/android_support_tests.bzl b/java/test/private/android_support_tests.bzl index 5bc07d90..13227f75 100644 --- a/java/test/private/android_support_tests.bzl +++ b/java/test/private/android_support_tests.bzl @@ -62,7 +62,7 @@ def _test_enable_implicit_sourceless_deps_exports_compatibility(name): def _test_enable_implicit_sourceless_deps_exports_compatibility_impl(env, targets): base_info = java_info_subject.from_target(env, targets.base) transformed_info = java_info_subject.from_target(env, targets.transformed) - transformed_info.compilation_args().equals(base_info.compilation_args()) + transformed_info.compilation_args().equals_subject(base_info.compilation_args()) base_info.plugins().processor_jars().contains_exactly(["{package}/libmy_plugin.jar"]) transformed_info.plugins().processor_jars().contains_exactly([]) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index f759172d..04d0b65d 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -8,6 +8,7 @@ def _new_java_info_subject(java_info, meta): public = struct( compilation_args = lambda: _new_java_compilation_args_subject(self.actual, self.meta), plugins = lambda: _new_java_info_plugins_subject(self.actual, self.meta), + is_binary = lambda: subjects.bool(getattr(java_info, "_is_binary", False), self.meta.derive("_is_binary")), ) return public @@ -20,6 +21,7 @@ def _java_info_subject_from_target(env, target): )) def _new_java_compilation_args_subject(java_info, meta): + is_binary = getattr(java_info, "_is_binary", False) actual = struct( transitive_runtime_jars = java_info.transitive_runtime_jars, compile_jars = java_info.compile_jars, @@ -27,23 +29,23 @@ def _new_java_compilation_args_subject(java_info, meta): full_compile_jars = java_info.full_compile_jars, _transitive_full_compile_time_jars = java_info._transitive_full_compile_time_jars, _compile_time_java_dependencies = java_info._compile_time_java_dependencies, - _is_binary = getattr(java_info, "_is_binary", False), - ) + ) if not is_binary else None self = struct( actual = actual, meta = meta, ) return struct( equals = lambda other: _java_compilation_args_equals(self, other), + equals_subject = lambda other: _java_compilation_args_equals(self, other.actual), self = self, actual = actual, ) def _java_compilation_args_equals(self, other): - if self.actual == other.actual: + if self.actual == other: return - for attr in dir(other.actual): - other_attr = getattr(other.actual, attr) + for attr in dir(other): + other_attr = getattr(other, attr) this_attr = getattr(self.actual, attr) if this_attr != other_attr: self.meta.derive(attr).add_failure( From 9d2f73e658e03a61cdfb864ec38a8a4a7e56cd9d Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 3 Feb 2025 04:15:09 -0800 Subject: [PATCH 121/465] Ignore the `exec_group_compatible_with` attribute in `java_binary` transitive validation collection PiperOrigin-RevId: 722600572 Change-Id: If9b64f65308c16a6d71b8f9cde268f406cdae245 --- java/common/rules/impl/java_binary_impl.bzl | 3 +++ 1 file changed, 3 insertions(+) diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl index 7de9d306..93114300 100644 --- a/java/common/rules/impl/java_binary_impl.bzl +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -392,10 +392,13 @@ def _filter_validation_output_group(ctx, output_group): "plugins", "translations", # special ignored attributes + # LINT.IfChange(validation_ignored_attrs) "compatible_with", "restricted_to", "exec_compatible_with", + "exec_group_compatible_with", "target_compatible_with", + # LINT.ThenChange(//jtcg/devtools/build/lib/rules/java/AbstractJavaBinaryConfiguredTargetTest.java:validation_ignored_attrs) ] ]) if not ctx.attr.create_executable: From 34d7e1bd22b31594c5de10c2d87c3dc6ab8efa74 Mon Sep 17 00:00:00 2001 From: "Ian (Hee) Cha" Date: Thu, 6 Feb 2025 03:12:29 -0800 Subject: [PATCH 122/465] Update rules_java to 8.9.0 and java_tools to 13.16 Copybara Import from https://github.com/bazelbuild/rules_java/pull/271 BEGIN_PUBLIC Update rules_java to 8.9.0 and java_tools to 13.16 (#271) Closes #271 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/271 from bazelbuild:java_v13.16 a075c194385b9543e38133dcbaff1a9ad606a89e PiperOrigin-RevId: 723864770 Change-Id: Ide0c37fde1a65488119cf2eb6949998fa387b77f --- MODULE.bazel | 2 +- java/repositories.bzl | 32 ++++++++++++++++---------------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 7394031d..4e9bdf20 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.8.0", + version = "8.9.0", bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) diff --git a/java/repositories.bzl b/java/repositories.bzl index c7c0a724..b17057a1 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.15", + "version": "v13.16", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.15/java_tools_linux-v13.15.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.15/java_tools_linux-v13.15.zip", - "sha": "74842dd84695133b22407a7eb0969ffdeb34179d0a31428f740c83eee28b8ca7", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.16/java_tools_linux-v13.16.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.16/java_tools_linux-v13.16.zip", + "sha": "cc78efd792e99b4ad5d3d031853da655aca375dbda50bd03ab94e8e2dbf2801a", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.15/java_tools_windows-v13.15.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.15/java_tools_windows-v13.15.zip", - "sha": "afcf14d1e24ee22dc37c76c911e0c37bc38ccd09a15f2aad5f692d7b0a6b158c", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.16/java_tools_windows-v13.16.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.16/java_tools_windows-v13.16.zip", + "sha": "726706173a9580ece6f9b64d7fe4986a46d98ff0bb18341bc93d0c013fa214d2", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.15/java_tools_darwin_x86_64-v13.15.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.15/java_tools_darwin_x86_64-v13.15.zip", - "sha": "b0d60beb1455e6ec8626e59da556fb0fa757b9732622f5c7615bb7e906922f52", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.16/java_tools_darwin_x86_64-v13.16.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.16/java_tools_darwin_x86_64-v13.16.zip", + "sha": "62a1785a446cd6a69db5d4207820d0e5db89ba72666be0def6990209f44b3900", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.15/java_tools_darwin_arm64-v13.15.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.15/java_tools_darwin_arm64-v13.15.zip", - "sha": "3d3494577a476153cfb1bef33f3156dc7749d491049320248511ee58c7e3a4b6", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.16/java_tools_darwin_arm64-v13.16.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.16/java_tools_darwin_arm64-v13.16.zip", + "sha": "20b35e87a2d430eabab7d6d1de821e5e9670aef2f5ef1ac788c72b4b00dbb8bf", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.15/java_tools-v13.15.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.15/java_tools-v13.15.zip", - "sha": "3d46e272172fe61ceabc324633ce3a06d40df3ab4d79e94ab55ed759369a0b5b", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.16/java_tools-v13.16.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.16/java_tools-v13.16.zip", + "sha": "11242f40a18aa4a766caa02e3f165c9d2ac7dba3fbfae1e7871a3916c98bddbf", }, }, } From 6f2db13f96fe160a4ec5da0fe2c230bb05e8e38a Mon Sep 17 00:00:00 2001 From: Donald Duo Zhao Date: Thu, 6 Feb 2025 18:27:47 -0800 Subject: [PATCH 123/465] Enforce `checkLegalityOfPluginOptions` check on `-AgeneratesKotlin` javacopts. - This attribute has been forfeited from the clients. PiperOrigin-RevId: 724151779 Change-Id: I55e03b1bb33273b5cefdc022026c8c24e45dbbce --- java/private/java_info.bzl | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/java/private/java_info.bzl b/java/private/java_info.bzl index 8a3b5e42..c5dbbb83 100644 --- a/java/private/java_info.bzl +++ b/java/private/java_info.bzl @@ -934,7 +934,8 @@ def _javaplugininfo_init( runtime_deps, processor_class, data = [], - generates_api = False): + generates_api = False, + extra_processor_classes = []): """ Constructs JavaPluginInfo Args: @@ -951,6 +952,9 @@ def _javaplugininfo_init( generated from the sources, reducing the critical path. WARNING: This parameter affects build performance, use it only if necessary. + extra_processor_classes: ([String]) Additional fully qualified class + names that the Java compiler uses as an entry point to the + annotation processor. Returns: (JavaPluginInfo) @@ -958,8 +962,9 @@ def _javaplugininfo_init( java_infos = merge(runtime_deps) processor_data = data if type(data) == "depset" else depset(data) + processor_classes = ([processor_class] if processor_class else []) + extra_processor_classes plugins = _create_plugin_data_info( - processor_classes = depset([processor_class]) if processor_class else depset(), + processor_classes = depset(processor_classes), processor_jars = java_infos.transitive_runtime_jars, processor_data = processor_data, ) From af504cff01d441676f2d3e3b64c92d010f85d835 Mon Sep 17 00:00:00 2001 From: Donald Duo Zhao Date: Thu, 6 Feb 2025 23:01:45 -0800 Subject: [PATCH 124/465] Rename `extra_processor_classes` to `processor_classes` for processor bundle support - Better support the inter-op between `JavaPluginInfo` and `KtCodegenPluginInfo` PiperOrigin-RevId: 724216672 Change-Id: Iab6a345faff2f0ca84bd9a4da5518b98aa922ed9 --- java/bazel/rules/bazel_java_plugin.bzl | 2 +- java/private/java_info.bzl | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/java/bazel/rules/bazel_java_plugin.bzl b/java/bazel/rules/bazel_java_plugin.bzl index f2619ede..d6fc7edc 100644 --- a/java/bazel/rules/bazel_java_plugin.bzl +++ b/java/bazel/rules/bazel_java_plugin.bzl @@ -84,7 +84,7 @@ def bazel_java_plugin_rule( # Replace JavaInfo with JavaPluginInfo target["JavaPluginInfo"] = JavaPluginInfo( runtime_deps = [java_info], - processor_class = processor_class if processor_class else None, # ignore empty string (default) + processor_classes = [processor_class] if processor_class else [], # ignore empty string (default) data = data, generates_api = generates_api, ) diff --git a/java/private/java_info.bzl b/java/private/java_info.bzl index c5dbbb83..083eef09 100644 --- a/java/private/java_info.bzl +++ b/java/private/java_info.bzl @@ -932,10 +932,10 @@ def _merge_plugin_data(datas): def _javaplugininfo_init( runtime_deps, - processor_class, + processor_class = None, + processor_classes = [], data = [], - generates_api = False, - extra_processor_classes = []): + generates_api = False): """ Constructs JavaPluginInfo Args: @@ -943,6 +943,8 @@ def _javaplugininfo_init( processor. processor_class: (String) The fully qualified class name that the Java compiler uses as an entry point to the annotation processor. + processor_classes: ([String]) Fully qualified class names that the + Java compiler uses as an entry point to the annotation processor. data: (depset[File]) The files needed by this annotation processor during execution. generates_api: (boolean) Set to true when this annotation processor @@ -952,9 +954,6 @@ def _javaplugininfo_init( generated from the sources, reducing the critical path. WARNING: This parameter affects build performance, use it only if necessary. - extra_processor_classes: ([String]) Additional fully qualified class - names that the Java compiler uses as an entry point to the - annotation processor. Returns: (JavaPluginInfo) @@ -962,9 +961,8 @@ def _javaplugininfo_init( java_infos = merge(runtime_deps) processor_data = data if type(data) == "depset" else depset(data) - processor_classes = ([processor_class] if processor_class else []) + extra_processor_classes plugins = _create_plugin_data_info( - processor_classes = depset(processor_classes), + processor_classes = depset([processor_class] + processor_classes) if processor_class else depset(processor_classes), processor_jars = java_infos.transitive_runtime_jars, processor_data = processor_data, ) From b57046afd14f9df9c016e6e937351c52fedc5551 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Feb 2025 08:57:38 -0800 Subject: [PATCH 125/465] Migrate the `javaInfo_exposesCcLinkingInformation` test to Starlark PiperOrigin-RevId: 724362780 Change-Id: I05454db4d9a23f2cd1101a64c5b8679759835c70 --- java/test/testutil/java_info_subject.bzl | 1 + 1 file changed, 1 insertion(+) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 04d0b65d..676cc743 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -9,6 +9,7 @@ def _new_java_info_subject(java_info, meta): compilation_args = lambda: _new_java_compilation_args_subject(self.actual, self.meta), plugins = lambda: _new_java_info_plugins_subject(self.actual, self.meta), is_binary = lambda: subjects.bool(getattr(java_info, "_is_binary", False), self.meta.derive("_is_binary")), + has_attr = lambda a: subjects.bool(getattr(java_info, a, None) != None, meta = self.meta.derive("{} != None".format(a))).equals(True), ) return public From 290ffee0dda03531eadaa7f6c0e0c652388c3c57 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 10 Feb 2025 02:38:46 -0800 Subject: [PATCH 126/465] Migrate `javaLibrary_propagatesDirectCcLinkingInformation` to Starlark PiperOrigin-RevId: 725133803 Change-Id: I6983422273cbd5a809de19be9be2d6e31bf79e55 --- java/test/testutil/cc_info_subject.bzl | 57 ++++++++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 2 + 2 files changed, 59 insertions(+) create mode 100644 java/test/testutil/cc_info_subject.bzl diff --git a/java/test/testutil/cc_info_subject.bzl b/java/test/testutil/cc_info_subject.bzl new file mode 100644 index 00000000..32c80a96 --- /dev/null +++ b/java/test/testutil/cc_info_subject.bzl @@ -0,0 +1,57 @@ +"""A custom @rules_testing subject for the CcInfo provider""" + +load("@rules_testing//lib:truth.bzl", "subjects") + +def _new_cc_info_subject(cc_info, meta): + self = struct( + actual = cc_info, + meta = meta, + ) + public = struct( + linking_context = lambda: _new_cc_info_linking_context_subject(self.actual, self.meta), + native_libraries = lambda: subjects.collection(self.actual.transitive_native_libraries(), self.meta.derive("transitive_native_libraries()")), + ) + return public + +def _new_cc_info_linking_context_subject(cc_info, meta): + self = struct( + actual = cc_info.linking_context, + meta = meta.derive("linking_context"), + ) + public = struct( + equals = lambda other: _cc_info_linking_context_equals(self.actual, other, self.meta), + libraries_to_link = lambda: _new_cc_info_libraries_to_link_subject(self.actual, self.meta), + ) + return public + +def _cc_info_linking_context_equals(actual, expected, meta): + if actual == expected: + return + meta.add_failure( + "expected: {}".format(expected), + "actual: {}".format(actual), + ) + +def _new_cc_info_libraries_to_link_subject(linking_context, meta): + self = struct( + actual = linking_context.libraries_to_link, + meta = meta.derive("libraries_to_link"), + ) + public = struct( + identifiers = lambda: _new_library_to_link_identifiers_subject(self.actual, self.meta), + ) + return public + +def _new_library_to_link_identifiers_subject(libraries_to_link, meta): + self = subjects.collection( + [lib.library_identifier() for lib in libraries_to_link], + meta = meta.derive("library_identifier()"), + ) + public = struct( + contains_exactly = lambda expected: self.contains_exactly([meta.format_str(e) for e in expected]), + ) + return public + +cc_info_subject = struct( + new_from_java_info = lambda java_info, meta: _new_cc_info_subject(java_info.cc_link_params_info, meta.derive("cc_link_params_info")), +) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 676cc743..7c31f2bf 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -2,6 +2,7 @@ load("@rules_testing//lib:truth.bzl", "subjects", "truth") load("//java/common:java_info.bzl", "JavaInfo") +load(":cc_info_subject.bzl", "cc_info_subject") def _new_java_info_subject(java_info, meta): self = struct(actual = java_info, meta = meta.derive("JavaInfo")) @@ -10,6 +11,7 @@ def _new_java_info_subject(java_info, meta): plugins = lambda: _new_java_info_plugins_subject(self.actual, self.meta), is_binary = lambda: subjects.bool(getattr(java_info, "_is_binary", False), self.meta.derive("_is_binary")), has_attr = lambda a: subjects.bool(getattr(java_info, a, None) != None, meta = self.meta.derive("{} != None".format(a))).equals(True), + cc_link_params_info = lambda: cc_info_subject.new_from_java_info(java_info, meta), ) return public From 609086687610bb3c13aa76c2bce33a8f85c6e9ff Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 12 Feb 2025 06:43:31 -0800 Subject: [PATCH 127/465] Extract legacy native symbols to a separate bzl file `legacy_native.bzl` will only be used by the compatibility proxy for Bazel versions < 8, and will thus allow removing these symbols from Bazel@HEAD. `native.bzl` now only exposes the `java_common` private APIs. PiperOrigin-RevId: 726035093 Change-Id: I8c78164b2b7ce9b647b2a7d195850213a85a8b86 --- java/private/BUILD | 11 ++++++++--- java/private/legacy_native.bzl | 29 +++++++++++++++++++++++++++++ java/private/native.bzl | 25 ++----------------------- java/rules_java_deps.bzl | 4 ++-- 4 files changed, 41 insertions(+), 28 deletions(-) create mode 100644 java/private/legacy_native.bzl diff --git a/java/private/BUILD b/java/private/BUILD index 020a4a7b..27be00de 100644 --- a/java/private/BUILD +++ b/java/private/BUILD @@ -7,10 +7,15 @@ bzl_library( srcs = [ "native.bzl", ], - visibility = [ - "//java:__subpackages__", - "@compatibility_proxy//:__pkg__", + visibility = ["//java:__subpackages__"], +) + +bzl_library( + name = "legacy_native_bzl", + srcs = [ + "legacy_native.bzl", ], + visibility = ["@compatibility_proxy//:__pkg__"], ) bzl_library( diff --git a/java/private/legacy_native.bzl b/java/private/legacy_native.bzl new file mode 100644 index 00000000..7a9e62fc --- /dev/null +++ b/java/private/legacy_native.bzl @@ -0,0 +1,29 @@ +# 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. + +# Redefine native symbols with a new name as a workaround for +# exporting them in @compatibility_proxy//:proxy.bzl with their original name. + +"""Lovely workaround to be able to expose native constants pretending to be Starlark.""" + +# Unused with Bazel@HEAD, only used by the compatibility layer for older Bazel versions + +# buildifier: disable=native-java-common +native_java_common = java_common + +# buildifier: disable=native-java-info +NativeJavaInfo = JavaInfo + +# buildifier: disable=native-java-plugin-info +NativeJavaPluginInfo = JavaPluginInfo diff --git a/java/private/native.bzl b/java/private/native.bzl index e6be6f74..be7ae686 100644 --- a/java/private/native.bzl +++ b/java/private/native.bzl @@ -12,29 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Redefine native symbols with a new name as a workaround for -# exporting them in `//third_party/bazel_rules/rules_proto/proto:defs.bzl` with their original name. -# -# While we cannot force users to load these symbol due to the lack of a -# allowlisting mechanism, we can still export them and tell users to -# load it to make a future migration to pure Starlark easier. - -"""Lovely workaround to be able to expose native constants pretending to be Starlark.""" - -# Unused with Bazel@HEAD, used by the compatibility layer for older Bazel versions - -# buildifier: disable=native-java-common -native_java_common = java_common - -# buildifier: disable=native-java-info -NativeJavaInfo = JavaInfo - -# buildifier: disable=native-java-plugin-info -NativeJavaPluginInfo = JavaPluginInfo +"""Redirects for private native APIs""" # Used for some private native APIs that we can't replicate just yet in Starlark -# getattr() for loading this file with Bazel 6, where we won't use this def get_internal_java_common(): - if hasattr(native_java_common, "internal_DO_NOT_USE"): - return native_java_common.internal_DO_NOT_USE() - return None + return java_common.internal_DO_NOT_USE() # buildifier: disable=native-java-common diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl index 1929bc85..b088f4de 100644 --- a/java/rules_java_deps.bzl +++ b/java/rules_java_deps.bzl @@ -69,7 +69,7 @@ bzl_library( name = "proxy_bzl", srcs = ["proxy.bzl"], deps = [ - "@rules_java//java/private:native_bzl", + "@rules_java//java/private:legacy_native_bzl", "@bazel_tools//tools:bzl_srcs", ], visibility = ["//visibility:public"] @@ -80,7 +80,7 @@ bzl_library( "proxy.bzl", """ load("@bazel_tools//tools/build_defs/repo:http.bzl", _http_jar = "http_jar") -load("@rules_java//java/private:native.bzl", "native_java_common", "NativeJavaInfo", "NativeJavaPluginInfo") +load("@rules_java//java/private:legacy_native.bzl", "native_java_common", "NativeJavaInfo", "NativeJavaPluginInfo") java_binary = native.java_binary java_import = native.java_import From ea19ca450c4f32c813575a2b6041551ebc875dc4 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 12 Feb 2025 09:00:46 -0800 Subject: [PATCH 128/465] Add a test for `java_common.compile(sourcepath = ...)` PiperOrigin-RevId: 726076270 Change-Id: I1c58dde4a30e964e7570c3d6367fb069b8314e5f --- java/test/common/BUILD | 3 ++ java/test/common/java_common_tests.bzl | 34 +++++++++++++++++++ .../rules/custom_library_with_sourcepaths.bzl | 25 ++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 java/test/common/BUILD create mode 100644 java/test/common/java_common_tests.bzl create mode 100644 java/test/testutil/rules/custom_library_with_sourcepaths.bzl diff --git a/java/test/common/BUILD b/java/test/common/BUILD new file mode 100644 index 00000000..18ab4f84 --- /dev/null +++ b/java/test/common/BUILD @@ -0,0 +1,3 @@ +load(":java_common_tests.bzl", "java_common_tests") + +java_common_tests(name = "java_common_tests") diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl new file mode 100644 index 00000000..4cc21ed5 --- /dev/null +++ b/java/test/common/java_common_tests.bzl @@ -0,0 +1,34 @@ +"""Tests for java_common APIs""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java/test/testutil:rules/custom_library_with_sourcepaths.bzl", "custom_library_with_sourcepaths") + +def _test_compile_sourcepath(name): + util.helper_target( + custom_library_with_sourcepaths, + name = "custom", + srcs = ["Main.java"], + sourcepath = [":B.jar"], + ) + + analysis_test( + name = name, + impl = _test_compile_sourcepath_impl, + target = ":custom", + ) + +def _test_compile_sourcepath_impl(env, target): + assert_compile_action = env.expect.that_target(target).action_generating("{package}/libcustom.jar") + + assert_compile_action.contains_flag_values([ + ("--sourcepath", "{package}/B.jar".format(package = target.label.package)), + ]) + +def java_common_tests(name): + test_suite( + name = name, + tests = [ + _test_compile_sourcepath, + ], + ) diff --git a/java/test/testutil/rules/custom_library_with_sourcepaths.bzl b/java/test/testutil/rules/custom_library_with_sourcepaths.bzl new file mode 100644 index 00000000..05768c4d --- /dev/null +++ b/java/test/testutil/rules/custom_library_with_sourcepaths.bzl @@ -0,0 +1,25 @@ +"""Helper rule for testing compilation with `sourcepath`s""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_semantics.bzl", "semantics") + +def _custom_library_with_sourcepaths_impl(ctx): + output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") + compilation_provider = java_common.compile( + ctx, + source_files = ctx.files.srcs, + output = output_jar, + sourcepath = ctx.files.sourcepath, + java_toolchain = semantics.find_java_toolchain(ctx), + ) + return [DefaultInfo(files = depset([output_jar])), compilation_provider] + +custom_library_with_sourcepaths = rule( + _custom_library_with_sourcepaths_impl, + attrs = { + "srcs": attr.label_list(allow_files = [".java"]), + "sourcepath": attr.label_list(allow_files = [".jar"]), + }, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], + fragments = ["java"], +) From 02ab5e6c9bc0310510761b21f951112d81a4eef0 Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Thu, 13 Feb 2025 03:13:53 -0800 Subject: [PATCH 129/465] Delete toolchains/BUILD.java_tools. Copybara Import from https://github.com/bazelbuild/rules_java/pull/273 BEGIN_PUBLIC Delete toolchains/BUILD.java_tools. (#273) This file was orphaned by 503773e7aaa9faf8f425bc6efeddefd0d69c60a8. Closes #273 END_PUBLIC COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/273 from benjaminp:java_tools-BUILD 0b351d0266a04e4dd065610293199803a07cb451 PiperOrigin-RevId: 726401668 Change-Id: I65a2755f6c541846ba1241a66c6d0f7428815ba3 --- toolchains/BUILD.java_tools | 669 ------------------------------------ 1 file changed, 669 deletions(-) delete mode 100644 toolchains/BUILD.java_tools diff --git a/toolchains/BUILD.java_tools b/toolchains/BUILD.java_tools deleted file mode 100644 index 9c68b758..00000000 --- a/toolchains/BUILD.java_tools +++ /dev/null @@ -1,669 +0,0 @@ -load("@com_google_protobuf//bazel:cc_proto_library.bzl", "cc_proto_library") -load("@com_google_protobuf//bazel:proto_library.bzl", "proto_library") -load("@rules_cc//cc:cc_binary.bzl", "cc_binary") -load("@rules_cc//cc:cc_library.bzl", "cc_library") -load("@rules_java//java:java_binary.bzl", "java_binary") -load("@rules_java//java:java_import.bzl", "java_import") - -package(default_visibility = ["//visibility:public"]) - -exports_files(glob(["**/*.jar"])) - -licenses(["notice"]) # Apache 2.0 - -SUPRESSED_WARNINGS = select({ - ":windows": [], - "//conditions:default": [ - "-Wno-error", - "-Wno-old-style-cast", - ], -}) - -filegroup( - name = "GenClass", - srcs = ["java_tools/GenClass_deploy.jar"], -) - -filegroup( - name = "jacoco_coverage_runner_filegroup", - srcs = ["java_tools/JacocoCoverage_jarjar_deploy.jar"], -) - -java_import( - name = "jacoco_coverage_runner", - jars = ["java_tools/JacocoCoverage_jarjar_deploy.jar"], -) - -filegroup( - name = "JacocoCoverage", - srcs = ["java_tools/JacocoCoverage_jarjar_deploy.jar"], -) - -filegroup( - name = "JavaBuilder", - srcs = ["java_tools/JavaBuilder_deploy.jar"], -) - -filegroup( - name = "Runner", - srcs = ["java_tools/Runner_deploy.jar"], -) - -filegroup( - name = "VanillaJavaBuilder", - srcs = ["java_tools/VanillaJavaBuilder_deploy.jar"], -) - -filegroup( - name = "TurbineDirect", - srcs = ["java_tools/turbine_direct_binary_deploy.jar"], -) - -java_import( - name = "jacoco-agent", - jars = ["java_tools/third_party/java/jacoco/org.jacoco.agent-0.8.11.jar"], - srcjar = "java_tools/third_party/java/jacoco/org.jacoco.agent-0.8.11-sources.jar", -) - -java_import( - name = "jacoco-core", - jars = ["java_tools/third_party/java/jacoco/org.jacoco.core-0.8.11.jar"], - srcjar = "java_tools/third_party/java/jacoco/org.jacoco.core-0.8.11-sources.jar", - exports = [ - ":asm", - ":asm-commons", - ":asm-tree", - ], -) - -filegroup( - name = "jacoco-core-jars", - srcs = ["java_tools/third_party/java/jacoco/org.jacoco.core-0.8.11.jar"], -) - -java_import( - name = "jacoco-report", - jars = ["java_tools/third_party/java/jacoco/org.jacoco.report-0.8.11.jar"], - srcjar = "java_tools/third_party/java/jacoco/org.jacoco.report-0.8.11-sources.jar", - exports = [ - ":asm", - ":jacoco-core", - ], -) - -java_import( - name = "bazel-jacoco-agent", - jars = ["java_tools/third_party/java/jacoco/jacocoagent-0.8.11.jar"], -) - -java_import( - name = "bazel-jacoco-agent-neverlink", - jars = ["java_tools/third_party/java/jacoco/jacocoagent-0.8.11.jar"], - neverlink = 1, -) - -java_import( - name = "asm", - jars = ["java_tools/third_party/java/jacoco/asm-9.6.jar"], - srcjar = "java_tools/third_party/java/jacoco/asm-9.6-sources.jar", -) - -java_import( - name = "asm-commons", - jars = ["java_tools/third_party/java/jacoco/asm-commons-9.6.jar"], - srcjar = "java_tools/third_party/java/jacoco/asm-commons-9.6-sources.jar", - runtime_deps = [":asm-tree"], -) - -java_import( - name = "asm-tree", - jars = ["java_tools/third_party/java/jacoco/asm-tree-9.6.jar"], - srcjar = "java_tools/third_party/java/jacoco/asm-tree-9.6-sources.jar", - runtime_deps = [":asm"], -) - -config_setting( - name = "windows", - constraint_values = ["@platforms//os:windows"], -) - -config_setting( - name = "freebsd", - constraint_values = ["@platforms//os:freebsd"], - visibility = ["//visibility:public"], -) - -config_setting( - name = "openbsd", - constraint_values = ["@platforms//os:openbsd"], - visibility = ["//visibility:public"], -) - -# Create intermediate cc_library, which does not implicitly depend on "malloc" -# and "link_extra_lib" in @bazel_tools//tools/cpp, and thereby avoids include -# path /Iexternal/tools being used in compiling actions which would result in -# the wrong headers being picked up. -cc_library( - name = "ijar_cc_binary_main", - srcs = [ - "java_tools/ijar/classfile.cc", - "java_tools/ijar/ijar.cc", - ], - copts = SUPRESSED_WARNINGS, - linkstatic = 1, # provides main() - deps = [":zip"], - alwayslink = 1, -) - -cc_binary( - name = "ijar_cc_binary", - deps = [":ijar_cc_binary_main"], -) - -cc_library( - name = "zip", - srcs = [ - "java_tools/ijar/zip.cc", - ] + select({ - ":windows": [ - "java_tools/ijar/mapped_file_windows.cc", - ], - "//conditions:default": [ - "java_tools/ijar/mapped_file_unix.cc", - ], - }), - hdrs = [ - "java_tools/ijar/common.h", - "java_tools/ijar/mapped_file.h", - "java_tools/ijar/zip.h", - ], - copts = SUPRESSED_WARNINGS, - include_prefix = "third_party", - strip_include_prefix = "java_tools", - deps = [ - ":platform_utils", - ":zlib_client", - ] + select({ - ":windows": [ - ":errors", - ":filesystem", - ":logging", - ":strings", - ], - "//conditions:default": [ - ], - }), -) - -cc_library( - name = "platform_utils", - srcs = ["java_tools/ijar/platform_utils.cc"], - hdrs = [ - "java_tools/ijar/common.h", - "java_tools/ijar/platform_utils.h", - ], - copts = SUPRESSED_WARNINGS, - include_prefix = "third_party", - strip_include_prefix = "java_tools", - visibility = ["//visibility:private"], - deps = [ - ":errors", - ":filesystem", - ":logging", - ], -) - -cc_library( - name = "cpp_util", - hdrs = [ - "java_tools/src/main/cpp/util/errors.h", - "java_tools/src/main/cpp/util/file.h", - "java_tools/src/main/cpp/util/file_platform.h", - "java_tools/src/main/cpp/util/md5.h", - "java_tools/src/main/cpp/util/numbers.h", - "java_tools/src/main/cpp/util/path.h", - "java_tools/src/main/cpp/util/path_platform.h", - "java_tools/src/main/cpp/util/port.h", - ], - strip_include_prefix = "java_tools", - visibility = ["//visibility:public"], - deps = [ - ":blaze_exit_code", - ":errors", - ":filesystem", - ":md5", - ":numbers", - ":port", - ":strings", - ], -) - -cc_library( - name = "md5", - srcs = ["java_tools/src/main/cpp/util/md5.cc"], - hdrs = ["java_tools/src/main/cpp/util/md5.h"], - strip_include_prefix = "java_tools", -) - -cc_library( - name = "numbers", - srcs = ["java_tools/src/main/cpp/util/numbers.cc"], - hdrs = ["java_tools/src/main/cpp/util/numbers.h"], - strip_include_prefix = "java_tools", - deps = [":strings"], -) - -cc_library( - name = "filesystem", - srcs = [ - "java_tools/src/main/cpp/util/file.cc", - "java_tools/src/main/cpp/util/path.cc", - ] + select({ - ":windows": [ - "java_tools/src/main/cpp/util/file_windows.cc", - "java_tools/src/main/cpp/util/path_windows.cc", - ], - "//conditions:default": [ - "java_tools/src/main/cpp/util/file_posix.cc", - "java_tools/src/main/cpp/util/path_posix.cc", - ], - }), - hdrs = [ - "java_tools/src/main/cpp/util/file.h", - "java_tools/src/main/cpp/util/file_platform.h", - "java_tools/src/main/cpp/util/path.h", - "java_tools/src/main/cpp/util/path_platform.h", - ], - strip_include_prefix = "java_tools", - deps = [ - ":blaze_exit_code", - ":errors", - ":logging", - ":strings", - ] + select({ - ":windows": [":lib-file"], - "//conditions:default": [], - }), -) - -cc_library( - name = "lib-file", - srcs = [ - "java_tools/src/main/native/windows/file.cc", - "java_tools/src/main/native/windows/util.cc", - ], - hdrs = [ - "java_tools/src/main/native/windows/file.h", - "java_tools/src/main/native/windows/util.h", - ], - linkopts = [ - "-DEFAULTLIB:advapi32.lib", - ], - strip_include_prefix = "java_tools", -) - -cc_library( - name = "errors", - srcs = select({ - ":windows": ["java_tools/src/main/cpp/util/errors_windows.cc"], - "//conditions:default": ["java_tools/src/main/cpp/util/errors_posix.cc"], - }), - hdrs = ["java_tools/src/main/cpp/util/errors.h"], - strip_include_prefix = "java_tools", - deps = [ - ":logging", - ":port", - ":strings", - ], -) - -cc_library( - name = "strings", - srcs = ["java_tools/src/main/cpp/util/strings.cc"], - hdrs = ["java_tools/src/main/cpp/util/strings.h"], - copts = SUPRESSED_WARNINGS, - # Automatically propagate the symbol definition to rules depending on this. - defines = [ - "BLAZE_OPENSOURCE", - ], - strip_include_prefix = "java_tools", - deps = [":blaze_exit_code"], -) - -cc_library( - name = "blaze_exit_code", - hdrs = ["java_tools/src/main/cpp/util/exit_code.h"], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", -) - -cc_library( - name = "port", - srcs = ["java_tools/src/main/cpp/util/port.cc"], - hdrs = ["java_tools/src/main/cpp/util/port.h"], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", -) - -cc_library( - name = "logging", - srcs = ["java_tools/src/main/cpp/util/logging.cc"], - hdrs = ["java_tools/src/main/cpp/util/logging.h"], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - deps = [ - ":blaze_exit_code", - ":strings", - ], -) - -cc_library( - name = "zlib_client", - srcs = ["java_tools/ijar/zlib_client.cc"], - hdrs = [ - "java_tools/ijar/common.h", - "java_tools/ijar/zlib_client.h", - ], - copts = SUPRESSED_WARNINGS, - include_prefix = "third_party", - strip_include_prefix = "java_tools", - deps = ["//java_tools/zlib"], -) - -##################### singlejar - -# See comment for ":ijar_cc_binary_main". -cc_library( - name = "singlejar_cc_bin_main", - srcs = [ - "java_tools/src/tools/singlejar/singlejar_main.cc", - ], - copts = SUPRESSED_WARNINGS, - linkopts = select({ - ":freebsd": ["-lm"], - ":openbsd": ["-lm"], - "//conditions:default": [], - }), - linkstatic = 1, # provides main() - deps = [ - ":combiners", - ":diag", - ":options", - ":output_jar", - "//java_tools/zlib", - ], - alwayslink = 1, -) - -cc_binary( - name = "singlejar_cc_bin", - linkstatic = 1, - visibility = ["//visibility:public"], - deps = [":singlejar_cc_bin_main"], -) - -cc_binary( - name = "singlejar_local", - srcs = [ - "java_tools/src/tools/singlejar/singlejar_local_main.cc", - ], - copts = SUPRESSED_WARNINGS, - linkopts = select({ - ":freebsd": ["-lm"], - ":openbsd": ["-lm"], - "//conditions:default": [], - }), - linkstatic = 1, - visibility = ["//visibility:public"], - deps = [ - ":combiners", - ":desugar_checking", - ":options", - ":output_jar", - "//java_tools/zlib", - ], -) - -cc_library( - name = "combiners", - srcs = [ - "java_tools/src/tools/singlejar/combiners.cc", - ], - hdrs = [ - "java_tools/src/tools/singlejar/combiners.h", - ":transient_bytes", - ], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - deps = [ - "//java_tools/zlib", - ], -) - -proto_library( - name = "desugar_deps_proto", - srcs = ["java_tools/src/main/protobuf/desugar_deps.proto"], -) - -cc_proto_library( - name = "desugar_deps_cc_proto", - deps = [":desugar_deps_proto"], -) - -cc_library( - name = "desugar_checking", - srcs = ["java_tools/src/tools/singlejar/desugar_checking.cc"], - hdrs = ["java_tools/src/tools/singlejar/desugar_checking.h"], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - deps = [ - ":combiners", - ":desugar_deps_cc_proto", - ], -) - -cc_library( - name = "diag", - hdrs = ["java_tools/src/tools/singlejar/diag.h"], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - visibility = ["//visibility:private"], -) - -cc_library( - name = "singlejar_port", - hdrs = ["java_tools/src/tools/singlejar/port.h"], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - visibility = ["//visibility:private"], -) - -cc_library( - name = "mapped_file", - srcs = ["java_tools/src/tools/singlejar/mapped_file.cc"], - hdrs = ["java_tools/src/tools/singlejar/mapped_file.h"] + - select({ - ":windows": ["java_tools/src/tools/singlejar/mapped_file_windows.inc"], - "//conditions:default": ["java_tools/src/tools/singlejar/mapped_file_posix.inc"], - }), - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - visibility = ["//visibility:private"], - deps = [ - ":cpp_util", - ":diag", - ":singlejar_port", - ], -) - -cc_library( - name = "input_jar", - srcs = [ - "java_tools/src/tools/singlejar/input_jar.cc", - ], - hdrs = [ - "java_tools/src/tools/singlejar/input_jar.h", - "java_tools/src/tools/singlejar/zip_headers.h", - ], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - deps = [ - ":diag", - ":mapped_file", - ], -) - -cc_library( - name = "options", - srcs = [ - "java_tools/src/tools/singlejar/options.cc", - "java_tools/src/tools/singlejar/options.h", - ], - hdrs = ["java_tools/src/tools/singlejar/options.h"], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - deps = [ - ":diag", - ":token_stream", - ], -) - -cc_library( - name = "output_jar", - srcs = [ - "java_tools/src/tools/singlejar/output_jar.cc", - "java_tools/src/tools/singlejar/output_jar.h", - ":zip_headers", - ], - hdrs = ["java_tools/src/tools/singlejar/output_jar.h"], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - deps = [ - ":combiners", - ":cpp_util", - ":diag", - ":input_jar", - ":mapped_file", - ":options", - ":singlejar_port", - "//java_tools/zlib", - ], -) - -cc_library( - name = "token_stream", - hdrs = ["java_tools/src/tools/singlejar/token_stream.h"], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - deps = [ - ":diag", - ":filesystem", - ], -) - -filegroup( - name = "transient_bytes", - srcs = [ - "java_tools/src/tools/singlejar/diag.h", - "java_tools/src/tools/singlejar/transient_bytes.h", - "java_tools/src/tools/singlejar/zlib_interface.h", - ":zip_headers", - ], -) - -filegroup( - name = "zip_headers", - srcs = ["java_tools/src/tools/singlejar/zip_headers.h"], -) - -################### Proguard ################### -java_import( - name = "proguard_import", - jars = ["java_tools/third_party/java/proguard/proguard.jar"], -) - -java_binary( - name = "proguard", - main_class = "proguard.ProGuard", - visibility = ["//visibility:public"], - runtime_deps = [":proguard_import"], -) - -##################### one_version - -# See comment for ":ijar_cc_binary_main". -cc_library( - name = "one_version_cc_bin_main", - srcs = [ - "java_tools/src/tools/one_version/one_version_main.cc", - ], - copts = SUPRESSED_WARNINGS, - linkopts = select({ - ":freebsd": ["-lm"], - ":openbsd": ["-lm"], - "//conditions:default": [], - }), - linkstatic = 1, # provides main() - deps = [ - ":allowlist", - ":duplicate_class_collector", - ":input_jar", - ":one_version", - ":token_stream", - "@com_google_absl//absl/container:flat_hash_map", - "@com_google_absl//absl/container:flat_hash_set", - "@com_google_absl//absl/log:die_if_null", - "@com_google_absl//absl/strings", - ], - alwayslink = 1, -) - -cc_binary( - name = "one_version_cc_bin", - linkstatic = 1, - visibility = ["//visibility:public"], - deps = [":one_version_cc_bin_main"], -) - -cc_library( - name = "duplicate_class_collector", - srcs = ["java_tools/src/tools/one_version/duplicate_class_collector.cc"], - hdrs = ["java_tools/src/tools/one_version/duplicate_class_collector.h"], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - deps = [ - "@com_google_absl//absl/container:flat_hash_map", - "@com_google_absl//absl/strings", - ], -) - -cc_library( - name = "allowlist", - srcs = ["java_tools/src/tools/one_version/allowlist.cc"], - hdrs = ["java_tools/src/tools/one_version/allowlist.h"], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - deps = [ - ":duplicate_class_collector", - "@com_google_absl//absl/container:flat_hash_map", - "@com_google_absl//absl/container:flat_hash_set", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/types:span", - ], -) - -cc_library( - name = "one_version", - srcs = ["java_tools/src/tools/one_version/one_version.cc"], - hdrs = ["java_tools/src/tools/one_version/one_version.h"], - copts = SUPRESSED_WARNINGS, - strip_include_prefix = "java_tools", - deps = [ - ":allowlist", - ":duplicate_class_collector", - ":input_jar", - "@com_google_absl//absl/log:die_if_null", - "@com_google_absl//absl/memory", - "@com_google_absl//absl/strings", - ], -) From 31edc44e0901b06ddb0f9c96984c69ea77bc8326 Mon Sep 17 00:00:00 2001 From: Ted Kaplan Date: Thu, 13 Feb 2025 05:16:58 -0800 Subject: [PATCH 130/465] Add make variables for runfiles location of $(JAVABASE) to support --no_legacy_external_runfiles. (#272) Add make variables for runfiles locations of `$(JAVA)` and `$(JAVABASE)`. These are needed to access these paths when passing them to test rules via `env` when using `--no_legacy_external_runfiles`. The original make variables still work in exec contexts such as genrules. Closes #272 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/272 from thirtyseven:patch-2 438b659093cb8bc4a1d0b1560a6a22dee463405f PiperOrigin-RevId: 726438570 Change-Id: I74e0815e1e71547c653a7b53bff801c62392f075 --- java/common/rules/java_runtime.bzl | 2 ++ test/repo/BUILD.bazel | 23 +++++++++++++++++++++++ test/repo/MODULE.bazel | 2 ++ test/repo/WORKSPACE | 15 +++++++++++++++ test/repo/src/MakeVarTest.sh | 10 ++++++++++ toolchains/java_toolchain_alias.bzl | 2 ++ 6 files changed, 54 insertions(+) create mode 100755 test/repo/src/MakeVarTest.sh diff --git a/java/common/rules/java_runtime.bzl b/java/common/rules/java_runtime.bzl index 52b13013..85acb22d 100644 --- a/java/common/rules/java_runtime.bzl +++ b/java/common/rules/java_runtime.bzl @@ -152,6 +152,8 @@ def _java_runtime_rule_impl(ctx): platform_common.TemplateVariableInfo({ "JAVA": java_binary_exec_path, "JAVABASE": java_home, + "JAVA_ROOTPATH": java_binary_runfiles_path, + "JAVABASE_ROOTPATH": java_home_runfiles_path, }), ToolchainInfo(java_runtime = java_runtime_info), ] diff --git a/test/repo/BUILD.bazel b/test/repo/BUILD.bazel index 7f6887a9..6522f971 100644 --- a/test/repo/BUILD.bazel +++ b/test/repo/BUILD.bazel @@ -1,5 +1,6 @@ load("@rules_java//java:defs.bzl", "java_binary", "java_library", "java_test") # copybara-use-repo-external-label load("@rules_java//toolchains:default_java_toolchain.bzl", "default_java_toolchain") # copybara-use-repo-external-label +load("@rules_shell//shell:sh_test.bzl", "sh_test") java_library( name = "lib", @@ -24,6 +25,28 @@ java_test( ], ) +genrule( + name = "MakeVarGenruleTest", + outs = ["MakeVarGenruleTestSuccess"], + cmd = "test -f $(JAVA) && test -d $(JAVABASE) && touch $@", + toolchains = ["@rules_java//toolchains:current_java_runtime"], + tools = ["@rules_java//toolchains:current_java_runtime"], +) + +sh_test( + name = "MakeVarTest", + srcs = ["src/MakeVarTest.sh"], + data = [ + "MakeVarGenruleTestSuccess", + "@rules_java//toolchains:current_java_runtime", + ], + env = { + "JAVA_ROOTPATH": "$(JAVA_ROOTPATH)", + "JAVABASE_ROOTPATH": "$(JAVABASE_ROOTPATH)", + }, + toolchains = ["@rules_java//toolchains:current_java_runtime"], +) + default_java_toolchain( name = "my_funky_toolchain", bootclasspath = ["@bazel_tools//tools/jdk:platformclasspath"], diff --git a/test/repo/MODULE.bazel b/test/repo/MODULE.bazel index 1be13d43..85f99283 100644 --- a/test/repo/MODULE.bazel +++ b/test/repo/MODULE.bazel @@ -44,3 +44,5 @@ use_repo( ) register_toolchains("//:all") + +bazel_dep(name = "rules_shell", version = "0.4.0", dev_dependency = True) diff --git a/test/repo/WORKSPACE b/test/repo/WORKSPACE index 872e89a7..08589c20 100644 --- a/test/repo/WORKSPACE +++ b/test/repo/WORKSPACE @@ -25,3 +25,18 @@ http_jar( name = "my_jar", urls = ["file:///tmp/my_jar.jar"], ) + +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "rules_shell", + sha256 = "3e114424a5c7e4fd43e0133cc6ecdfe54e45ae8affa14fadd839f29901424043", + strip_prefix = "rules_shell-0.4.0", + url = "https://github.com/bazelbuild/rules_shell/releases/download/v0.4.0/rules_shell-v0.4.0.tar.gz", +) + +load("@rules_shell//shell:repositories.bzl", "rules_shell_dependencies", "rules_shell_toolchains") + +rules_shell_dependencies() + +rules_shell_toolchains() diff --git a/test/repo/src/MakeVarTest.sh b/test/repo/src/MakeVarTest.sh new file mode 100755 index 00000000..7307dfdf --- /dev/null +++ b/test/repo/src/MakeVarTest.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +if [ ! -x "$JAVABASE_ROOTPATH/bin/java" ]; then + echo '$JAVABASE_RUNFILES does not point to a working JRE' && exit 1 +fi + +echo $JAVA_ROOTPATH +if [ ! -x "$JAVA_ROOTPATH" ]; then + echo '$JAVA_ROOTPATH does not exist' && exit 1 +fi \ No newline at end of file diff --git a/toolchains/java_toolchain_alias.bzl b/toolchains/java_toolchain_alias.bzl index 34889258..54973c0f 100644 --- a/toolchains/java_toolchain_alias.bzl +++ b/toolchains/java_toolchain_alias.bzl @@ -26,6 +26,8 @@ def _java_runtime_alias(ctx): platform_common.TemplateVariableInfo({ "JAVA": str(toolchain.java_executable_exec_path), "JAVABASE": str(toolchain.java_home), + "JAVA_ROOTPATH": str(toolchain.java_executable_runfiles_path), + "JAVABASE_ROOTPATH": str(toolchain.java_home_runfiles_path), }), # See b/65239471 for related discussion of handling toolchain runfiles/data. DefaultInfo( From 250bbdc8e9287d2cdffbeadd2c3485c4b9817ea2 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 18 Feb 2025 00:56:24 -0800 Subject: [PATCH 131/465] Switch rules_java back to more named params (quasi-rollback of unknown commit) PiperOrigin-RevId: 728089692 Change-Id: I76cbe64fbcb422c67db62e87f0bc5eba675191ee --- .../rules/impl/basic_java_library_impl.bzl | 34 +++++++++---------- .../rules/impl/bazel_java_library_impl.bzl | 22 ++++++------ java/private/java_common.bzl | 4 +-- 3 files changed, 30 insertions(+), 30 deletions(-) diff --git a/java/common/rules/impl/basic_java_library_impl.bzl b/java/common/rules/impl/basic_java_library_impl.bzl index 35b1edd1..a43b4517 100644 --- a/java/common/rules/impl/basic_java_library_impl.bzl +++ b/java/common/rules/impl/basic_java_library_impl.bzl @@ -126,23 +126,23 @@ def basic_java_library( java_info, compilation_info = compile_action( ctx, - ctx.outputs.classjar, - ctx.outputs.sourcejar, - source_files, - source_jars, - collect_deps(deps) + ([coverage_config.runner] if coverage_config and coverage_config.runner else []), - collect_deps(runtime_deps), - plugins_javaplugininfo, - collect_deps(exports), - _collect_plugins(exported_plugins), - resources, - resource_jars, - classpath_resources, - _collect_native_libraries(deps, runtime_deps, exports), - javacopts, - neverlink, - ctx.fragments.java.strict_java_deps, - enable_compile_jar_action, + output_class_jar = ctx.outputs.classjar, + output_source_jar = ctx.outputs.sourcejar, + source_files = source_files, + source_jars = source_jars, + deps = collect_deps(deps) + ([coverage_config.runner] if coverage_config and coverage_config.runner else []), + runtime_deps = collect_deps(runtime_deps), + plugins = plugins_javaplugininfo, + exports = collect_deps(exports), + exported_plugins = _collect_plugins(exported_plugins), + resources = resources, + resource_jars = resource_jars, + classpath_resources = classpath_resources, + native_libraries = _collect_native_libraries(deps, runtime_deps, exports), + javacopts = javacopts, + neverlink = neverlink, + strict_deps = ctx.fragments.java.strict_java_deps, + enable_compile_jar_action = enable_compile_jar_action, add_exports = add_exports, add_opens = add_opens, bootclasspath = bootclasspath[BootClassPathInfo] if bootclasspath else None, diff --git a/java/common/rules/impl/bazel_java_library_impl.bzl b/java/common/rules/impl/bazel_java_library_impl.bzl index 04a020e4..5c7fc5cb 100644 --- a/java/common/rules/impl/bazel_java_library_impl.bzl +++ b/java/common/rules/impl/bazel_java_library_impl.bzl @@ -67,17 +67,17 @@ def bazel_java_library_rule( target, base_info = basic_java_library( ctx, - srcs, - deps, - runtime_deps, - plugins, - exports, - exported_plugins, - resources, - [], # resource_jars - [], # class_pathresources - javacopts, - neverlink, + srcs = srcs, + deps = deps, + runtime_deps = runtime_deps, + plugins = plugins, + exports = exports, + exported_plugins = exported_plugins, + resources = resources, + resource_jars = [], + classpath_resources = [], + javacopts = javacopts, + neverlink = neverlink, proguard_specs = proguard_specs, add_exports = add_exports, add_opens = add_opens, diff --git a/java/private/java_common.bzl b/java/private/java_common.bzl index ebaa35d5..70461632 100644 --- a/java/private/java_common.bzl +++ b/java/private/java_common.bzl @@ -70,8 +70,8 @@ def _compile( add_opens = []): return _compile_internal( ctx, - output, - java_toolchain, + output = output, + java_toolchain = java_toolchain, source_jars = source_jars, source_files = source_files, output_source_jar = output_source_jar, From eb4d15ae6ffec1a88bb60c005f6c2323d97849cd Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Feb 2025 05:27:18 -0800 Subject: [PATCH 132/465] Add a test for `java_common.compile` with exports and no sources PiperOrigin-RevId: 729492763 Change-Id: I314232cf954763d68a1402be69c9f548170d6883 --- java/test/common/java_common_tests.bzl | 21 +++++++++++++++++ java/test/testutil/java_info_subject.bzl | 5 ++-- .../rules/custom_library_with_exports.bzl | 23 +++++++++++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 java/test/testutil/rules/custom_library_with_exports.bzl diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 4cc21ed5..235f1350 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -2,6 +2,9 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") +load("//java:java_library.bzl", "java_library") +load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//java/test/testutil:rules/custom_library_with_exports.bzl", "custom_library_with_exports") load("//java/test/testutil:rules/custom_library_with_sourcepaths.bzl", "custom_library_with_sourcepaths") def _test_compile_sourcepath(name): @@ -25,10 +28,28 @@ def _test_compile_sourcepath_impl(env, target): ("--sourcepath", "{package}/B.jar".format(package = target.label.package)), ]) +def _test_compile_exports_no_sources(name): + util.helper_target(java_library, name = "jl", srcs = ["Main.java"]) + util.helper_target(custom_library_with_exports, name = "custom2", exports = [":jl"]) + + analysis_test( + name = name, + impl = _test_compile_exports_no_sources_impl, + target = ":custom2", + ) + +def _test_compile_exports_no_sources_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.compilation_args().transitive_runtime_jars().contains_exactly( + ["{package}/libjl.jar"], + ) + def java_common_tests(name): test_suite( name = name, tests = [ _test_compile_sourcepath, + _test_compile_exports_no_sources, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 7c31f2bf..9128cc9a 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -30,8 +30,8 @@ def _new_java_compilation_args_subject(java_info, meta): compile_jars = java_info.compile_jars, transitive_compile_time_jars = java_info.transitive_compile_time_jars, full_compile_jars = java_info.full_compile_jars, - _transitive_full_compile_time_jars = java_info._transitive_full_compile_time_jars, - _compile_time_java_dependencies = java_info._compile_time_java_dependencies, + _transitive_full_compile_time_jars = getattr(java_info, "_transitive_full_compile_time_jars", None), # not in Bazel 6 + _compile_time_java_dependencies = getattr(java_info, "_compile_time_java_dependencies", None), # not in Bazel 6 ) if not is_binary else None self = struct( actual = actual, @@ -40,6 +40,7 @@ def _new_java_compilation_args_subject(java_info, meta): return struct( equals = lambda other: _java_compilation_args_equals(self, other), equals_subject = lambda other: _java_compilation_args_equals(self, other.actual), + transitive_runtime_jars = lambda: subjects.depset_file(actual.transitive_runtime_jars, self.meta.derive("transitive_runtime_jars")), self = self, actual = actual, ) diff --git a/java/test/testutil/rules/custom_library_with_exports.bzl b/java/test/testutil/rules/custom_library_with_exports.bzl new file mode 100644 index 00000000..5ba6793c --- /dev/null +++ b/java/test/testutil/rules/custom_library_with_exports.bzl @@ -0,0 +1,23 @@ +"""Helper rule for testing compilation with `exports`""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_semantics.bzl", "semantics") + +def _custom_library_with_exports_impl(ctx): + output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") + compilation_provider = java_common.compile( + ctx, + exports = [export[java_common.provider] for export in ctx.attr.exports], + output = output_jar, + java_toolchain = semantics.find_java_toolchain(ctx), + ) + return [DefaultInfo(files = depset([output_jar])), compilation_provider] + +custom_library_with_exports = rule( + _custom_library_with_exports_impl, + attrs = { + "exports": attr.label_list(), + }, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], + fragments = ["java"], +) From 832cf12302488fb946c223f31668109fdc286e0d Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Feb 2025 05:33:45 -0800 Subject: [PATCH 133/465] Internal change PiperOrigin-RevId: 729494365 Change-Id: I816a0d3ea621baca1b14d72b462e3ba6161b9584 --- java/test/testutil/java_info_subject.bzl | 2 ++ 1 file changed, 2 insertions(+) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 9128cc9a..dde7e89c 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -1,6 +1,7 @@ """A custom @rules_testing subject for the JavaInfo provider""" load("@rules_testing//lib:truth.bzl", "subjects", "truth") +load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load(":cc_info_subject.bzl", "cc_info_subject") @@ -12,6 +13,7 @@ def _new_java_info_subject(java_info, meta): is_binary = lambda: subjects.bool(getattr(java_info, "_is_binary", False), self.meta.derive("_is_binary")), has_attr = lambda a: subjects.bool(getattr(java_info, a, None) != None, meta = self.meta.derive("{} != None".format(a))).equals(True), cc_link_params_info = lambda: cc_info_subject.new_from_java_info(java_info, meta), + constraints = lambda: subjects.collection(java_common.get_constraints(java_info), self.meta.derive("constraints")), ) return public From f5748b3893c3930d76647689d3050a6694a5656e Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Feb 2025 05:58:18 -0800 Subject: [PATCH 134/465] Add a test for `java_common.compile()` PiperOrigin-RevId: 729500270 Change-Id: I161bbdbc510c14468bb83ed3fe45aee5daa7299e --- java/test/common/java_common_tests.bzl | 14 +++++++++++++ java/test/testutil/rules/custom_library.bzl | 23 +++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 java/test/testutil/rules/custom_library.bzl diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 235f1350..07c615f5 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -4,9 +4,22 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//java/test/testutil:rules/custom_library.bzl", "custom_library") load("//java/test/testutil:rules/custom_library_with_exports.bzl", "custom_library_with_exports") load("//java/test/testutil:rules/custom_library_with_sourcepaths.bzl", "custom_library_with_sourcepaths") +def _test_compile_default_values(name): + util.helper_target(custom_library, name = name + "/custom", srcs = ["Main.java"]) + + analysis_test(name = name, impl = _test_compile_default_values_impl, target = name + "/custom") + +def _test_compile_default_values_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.compilation_args().transitive_runtime_jars().contains_exactly([ + "{}/lib{}.jar".format(target.label.package, target.label.name), + ]) + def _test_compile_sourcepath(name): util.helper_target( custom_library_with_sourcepaths, @@ -49,6 +62,7 @@ def java_common_tests(name): test_suite( name = name, tests = [ + _test_compile_default_values, _test_compile_sourcepath, _test_compile_exports_no_sources, ], diff --git a/java/test/testutil/rules/custom_library.bzl b/java/test/testutil/rules/custom_library.bzl new file mode 100644 index 00000000..58307b60 --- /dev/null +++ b/java/test/testutil/rules/custom_library.bzl @@ -0,0 +1,23 @@ +"""Helper rule for testing compilation with default parameter values""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_semantics.bzl", "semantics") + +def _custom_library_impl(ctx): + output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") + compilation_provider = java_common.compile( + ctx, + source_files = ctx.files.srcs, + output = output_jar, + java_toolchain = semantics.find_java_toolchain(ctx), + ) + return [DefaultInfo(files = depset([output_jar])), compilation_provider] + +custom_library = rule( + _custom_library_impl, + attrs = { + "srcs": attr.label_list(allow_files = [".java"]), + }, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], + fragments = ["java"], +) From 31566a6f426215dbd86fc60fdab5486dedbdc4ef Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Feb 2025 06:09:09 -0800 Subject: [PATCH 135/465] Internal change PiperOrigin-RevId: 729503136 Change-Id: I9c3f33136e76ae08722c88e7e5a8b9a4deeda4f4 --- java/test/testutil/java_info_subject.bzl | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index dde7e89c..5d407f01 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -14,6 +14,7 @@ def _new_java_info_subject(java_info, meta): has_attr = lambda a: subjects.bool(getattr(java_info, a, None) != None, meta = self.meta.derive("{} != None".format(a))).equals(True), cc_link_params_info = lambda: cc_info_subject.new_from_java_info(java_info, meta), constraints = lambda: subjects.collection(java_common.get_constraints(java_info), self.meta.derive("constraints")), + annotation_processing = lambda: _new_annotation_processing_subject(self.actual, self.meta), ) return public @@ -69,6 +70,26 @@ def _new_java_info_plugins_subject(java_info, meta): ) return public +def _new_annotation_processing_subject(java_info, meta): + actual = java_info.annotation_processing + meta = meta.derive("annotation_processing") + self = struct( + actual = actual, + meta = meta, + ) + public = struct( + is_enabled = lambda: subjects.bool(actual.enabled, meta = meta.derive("is_enabled")), + processor_classnames = lambda: subjects.collection(actual.processor_classnames, meta = meta.derive("processor_classnames")), + processor_classpath = lambda: subjects.depset_file(actual.processor_classpath, meta = meta.derive("processor_classpath")), + class_jar = lambda: subjects.file(actual.class_jar, meta = meta.derive("class_jar")), + source_jar = lambda: subjects.file(actual.source_jar, meta = meta.derive("source_jar")), + transitive_class_jars = lambda: subjects.depset_file(actual.transitive_class_jars, meta = meta.derive("transitive_class_jars")), + transitive_source_jars = lambda: subjects.depset_file(actual.transitive_source_jars, meta = meta.derive("transitive_source_jars")), + actual = actual, + self = self, + ) + return public + java_info_subject = struct( new = _new_java_info_subject, from_target = _java_info_subject_from_target, From 5d4442ee1c0adc3db015f218cc9fa9e973d91c0f Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Feb 2025 06:47:24 -0800 Subject: [PATCH 136/465] Add a test for `java_common.JavaPluginInfo` PiperOrigin-RevId: 729512644 Change-Id: Ie2319bec47dea26abdf12e853843f8b70f4d4357 --- java/test/common/java_common_tests.bzl | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 07c615f5..30eeb911 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -3,6 +3,8 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") load("//java/test/testutil:rules/custom_library.bzl", "custom_library") load("//java/test/testutil:rules/custom_library_with_exports.bzl", "custom_library_with_exports") @@ -58,6 +60,20 @@ def _test_compile_exports_no_sources_impl(env, target): ["{package}/libjl.jar"], ) +def _test_java_plugin_info(name): + util.helper_target(native.filegroup, name = name + "/dummy") + analysis_test( + name = name, + impl = _test_java_plugin_info_impl, + target = name + "/dummy", # analysis_test always expects a target + ) + +def _test_java_plugin_info_impl(env, _target): + env.expect.that_bool( + java_common.JavaPluginInfo == JavaPluginInfo, + "java_common.JavaPluginInfo == JavaPluginInfo", + ).equals(True) + def java_common_tests(name): test_suite( name = name, @@ -65,5 +81,6 @@ def java_common_tests(name): _test_compile_default_values, _test_compile_sourcepath, _test_compile_exports_no_sources, + _test_java_plugin_info, ], ) From 3bed9dc56ba246dd7936a24b37d0e167d5e8c6a5 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Feb 2025 07:05:45 -0800 Subject: [PATCH 137/465] Add a test for extending compile time jdeps PiperOrigin-RevId: 729517655 Change-Id: I6eb39583a60cd964621b2499925e4d2bcca5c158 --- java/test/common/java_common_tests.bzl | 29 ++++++++++++ .../custom_library_extended_compile_jdeps.bzl | 45 +++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 java/test/testutil/rules/custom_library_extended_compile_jdeps.bzl diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 30eeb911..6f5b1f38 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -4,9 +4,11 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") load("//java/test/testutil:rules/custom_library.bzl", "custom_library") +load("//java/test/testutil:rules/custom_library_extended_compile_jdeps.bzl", "CompileJdepsInfo", "custom_library_extended_jdeps") load("//java/test/testutil:rules/custom_library_with_exports.bzl", "custom_library_with_exports") load("//java/test/testutil:rules/custom_library_with_sourcepaths.bzl", "custom_library_with_sourcepaths") @@ -74,6 +76,32 @@ def _test_java_plugin_info_impl(env, _target): "java_common.JavaPluginInfo == JavaPluginInfo", ).equals(True) +# Tests that extended 'compile time jdeps' are consistently updated. +def _test_compile_extend_compile_time_jdeps(name): + util.helper_target( + custom_library_extended_jdeps, + name = name + "/foo", + srcs = ["Foo.java"], + extra_jdeps = "Foo.jdeps", + ) + + analysis_test( + name = name, + impl = _test_compile_extend_compile_time_jdeps_impl, + target = name + "/foo", + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_compile_extend_compile_time_jdeps_impl(env, target): + before = target[CompileJdepsInfo].before.to_list() + assert_that_before = env.expect.that_collection(before) + assert_that_after = env.expect.that_collection(target[CompileJdepsInfo].after.to_list()) + + assert_that_before.has_size(1) + assert_that_after.has_size(2) + assert_that_after.contains_at_least(before) + assert_that_after.contains_exactly(target[JavaInfo]._compile_time_java_dependencies) + def java_common_tests(name): test_suite( name = name, @@ -82,5 +110,6 @@ def java_common_tests(name): _test_compile_sourcepath, _test_compile_exports_no_sources, _test_java_plugin_info, + _test_compile_extend_compile_time_jdeps, ], ) diff --git a/java/test/testutil/rules/custom_library_extended_compile_jdeps.bzl b/java/test/testutil/rules/custom_library_extended_compile_jdeps.bzl new file mode 100644 index 00000000..a3e9ec18 --- /dev/null +++ b/java/test/testutil/rules/custom_library_extended_compile_jdeps.bzl @@ -0,0 +1,45 @@ +"""Helper rule to test extending compile time jdeps""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_semantics.bzl", "semantics") + +CompileJdepsInfo = provider("Provider to testing compile jdeps", fields = ["before", "after"]) + +def _compile_time_jdeps(info): + return depset([outputs.compile_jdeps for outputs in info.java_outputs if outputs.compile_jdeps != None]) + +def _impl(ctx): + output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") + info = java_common.compile( + ctx, + source_files = ctx.files.srcs, + output = output_jar, + java_toolchain = semantics.find_java_toolchain(ctx), + ) + jdeps_info = JavaInfo( + output_jar = output_jar, + compile_jar = None, + compile_jdeps = ctx.file.extra_jdeps, + ) + extra_info = java_common.merge([info, jdeps_info]) + return [ + extra_info, + CompileJdepsInfo( + before = _compile_time_jdeps(info), + after = _compile_time_jdeps(extra_info), + ), + ] + +custom_library_extended_jdeps = rule( + implementation = _impl, + outputs = { + "my_output": "lib%{name}.jar", + }, + attrs = { + "srcs": attr.label_list(allow_files = [".java"]), + "extra_jdeps": attr.label(allow_single_file = True), + }, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], + fragments = ["java"], +) From 2ffef4ad52fe82efc5ffba64388595b03e73afcc Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Feb 2025 07:12:08 -0800 Subject: [PATCH 138/465] Add another test for extending compile time jdeps PiperOrigin-RevId: 729519090 Change-Id: I210dfb4cb0300eb0b4a42359f4c952a1d16cf248 --- java/test/common/java_common_tests.bzl | 60 +++++++++++++++++++ .../custom_library_extended_compile_jdeps.bzl | 4 ++ 2 files changed, 64 insertions(+) diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 6f5b1f38..b5c406b6 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -102,6 +102,65 @@ def _test_compile_extend_compile_time_jdeps_impl(env, target): assert_that_after.contains_at_least(before) assert_that_after.contains_exactly(target[JavaInfo]._compile_time_java_dependencies) +def _test_compile_extend_compile_time_jdeps_rule_outputs(name): + util.helper_target( + custom_library_extended_jdeps, + name = name + "/foo", + srcs = ["Foo.java"], + extra_jdeps = "Foo.jdeps", + ) + util.helper_target( + custom_library_extended_jdeps, + name = name + "/bar", + srcs = ["Bar.java"], + extra_jdeps = "Bar.jdeps", + deps = [name + "/foo"], + ) + util.helper_target( + custom_library_extended_jdeps, + name = name + "/baz", + srcs = ["Baz.java"], + extra_jdeps = "Baz.jdeps", + exports = [name + "/foo"], + ) + + analysis_test( + name = name, + impl = _test_compile_extend_compile_time_jdeps_rule_outputs_impl, + targets = { + "foo": name + "/foo", + "bar": name + "/bar", + "baz": name + "/baz", + }, + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_compile_extend_compile_time_jdeps_rule_outputs_impl(env, targets): + foo = targets.foo + compile_time_jdeps = foo[JavaInfo]._compile_time_java_dependencies + env.expect.that_depset_of_files(compile_time_jdeps).contains_exactly([ + "{}/lib{}-hjar.jdeps".format(foo.label.package, foo.label.name), + "{}/Foo.jdeps".format(foo.label.package), + ]) + + # foo's jdeps shouldn't appear in bar's + bar = targets.bar + compile_time_jdeps = bar[JavaInfo]._compile_time_java_dependencies + env.expect.that_depset_of_files(compile_time_jdeps).contains_exactly([ + "{}/lib{}-hjar.jdeps".format(bar.label.package, bar.label.name), + "{}/Bar.jdeps".format(bar.label.package), + ]) + + # baz exports foo, so we expect jdeps from both targets + baz = targets.baz + compile_time_jdeps = baz[JavaInfo]._compile_time_java_dependencies + env.expect.that_depset_of_files(compile_time_jdeps).contains_exactly([ + "{}/lib{}-hjar.jdeps".format(foo.label.package, foo.label.name), + "{}/Foo.jdeps".format(foo.label.package), + "{}/lib{}-hjar.jdeps".format(baz.label.package, baz.label.name), + "{}/Baz.jdeps".format(baz.label.package), + ]) + def java_common_tests(name): test_suite( name = name, @@ -111,5 +170,6 @@ def java_common_tests(name): _test_compile_exports_no_sources, _test_java_plugin_info, _test_compile_extend_compile_time_jdeps, + _test_compile_extend_compile_time_jdeps_rule_outputs, ], ) diff --git a/java/test/testutil/rules/custom_library_extended_compile_jdeps.bzl b/java/test/testutil/rules/custom_library_extended_compile_jdeps.bzl index a3e9ec18..6cc8284a 100644 --- a/java/test/testutil/rules/custom_library_extended_compile_jdeps.bzl +++ b/java/test/testutil/rules/custom_library_extended_compile_jdeps.bzl @@ -15,6 +15,8 @@ def _impl(ctx): ctx, source_files = ctx.files.srcs, output = output_jar, + deps = [d[JavaInfo] for d in ctx.attr.deps], + exports = [e[JavaInfo] for e in ctx.attr.exports], java_toolchain = semantics.find_java_toolchain(ctx), ) jdeps_info = JavaInfo( @@ -39,6 +41,8 @@ custom_library_extended_jdeps = rule( attrs = { "srcs": attr.label_list(allow_files = [".java"]), "extra_jdeps": attr.label(allow_single_file = True), + "deps": attr.label_list(providers = [JavaInfo]), + "exports": attr.label_list(providers = [JavaInfo]), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], fragments = ["java"], From 8b950284b900af7aab13697ad3275cead6c6486f Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Feb 2025 07:14:10 -0800 Subject: [PATCH 139/465] Add a test for java_common.compile() with a custom bootclasspath PiperOrigin-RevId: 729519483 Change-Id: I75af66009265c26624a4846974807c279f576c8d --- java/test/common/java_common_tests.bzl | 37 +++++++++++++++ .../custom_library_with_bootclasspath.bzl | 46 +++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 java/test/testutil/rules/custom_library_with_bootclasspath.bzl diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index b5c406b6..e84999d7 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -9,6 +9,7 @@ load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") load("//java/test/testutil:rules/custom_library.bzl", "custom_library") load("//java/test/testutil:rules/custom_library_extended_compile_jdeps.bzl", "CompileJdepsInfo", "custom_library_extended_jdeps") +load("//java/test/testutil:rules/custom_library_with_bootclasspath.bzl", "custom_bootclasspath", "custom_library_with_bootclasspath") load("//java/test/testutil:rules/custom_library_with_exports.bzl", "custom_library_with_exports") load("//java/test/testutil:rules/custom_library_with_sourcepaths.bzl", "custom_library_with_sourcepaths") @@ -161,6 +162,41 @@ def _test_compile_extend_compile_time_jdeps_rule_outputs_impl(env, targets): "{}/Baz.jdeps".format(baz.label.package), ]) +def _test_compile_bootclasspath(name): + util.helper_target( + custom_bootclasspath, + name = name + "/bootclasspath", + srcs = [ + "custom-system/lib/jrt-fs.jar", + "custom-system/lib/modules", + "custom-system/release", + ], + ) + util.helper_target( + custom_library_with_bootclasspath, + name = name + "/custom", + srcs = ["Main.java"], + bootclasspath = name + "/bootclasspath", + sourcepath = [":B.jar"], + ) + + analysis_test( + name = name, + impl = _test_compile_bootclasspath_impl, + target = name + "/custom", + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_compile_bootclasspath_impl(env, target): + assert_that_javac = env.expect.that_target(target).action_generating( + target[JavaInfo].java_outputs[0].class_jar.short_path, + ) + + assert_that_javac.contains_flag_values([( + "--system", + "{}/custom-system".format(target.label.package), + )]) + def java_common_tests(name): test_suite( name = name, @@ -171,5 +207,6 @@ def java_common_tests(name): _test_java_plugin_info, _test_compile_extend_compile_time_jdeps, _test_compile_extend_compile_time_jdeps_rule_outputs, + _test_compile_bootclasspath, ], ) diff --git a/java/test/testutil/rules/custom_library_with_bootclasspath.bzl b/java/test/testutil/rules/custom_library_with_bootclasspath.bzl new file mode 100644 index 00000000..666fd582 --- /dev/null +++ b/java/test/testutil/rules/custom_library_with_bootclasspath.bzl @@ -0,0 +1,46 @@ +"""Helper rule to test custom bootclasspaths in java_common.compile()""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_semantics.bzl", "semantics") + +def _bootclasspath(ctx): + files = ctx.files.srcs + return [java_common.BootClassPathInfo(bootclasspath = files, system = files)] + +custom_bootclasspath = rule( + implementation = _bootclasspath, + attrs = { + "srcs": attr.label_list(allow_files = True), + }, +) + +def _impl(ctx): + output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") + compilation_provider = java_common.compile( + ctx, + source_files = ctx.files.srcs, + output = output_jar, + deps = [], + sourcepath = ctx.files.sourcepath, + strict_deps = "ERROR", + java_toolchain = semantics.find_java_toolchain(ctx), + bootclasspath = ctx.attr.bootclasspath[java_common.BootClassPathInfo], + ) + return [ + DefaultInfo(files = depset([output_jar])), + compilation_provider, + ] + +custom_library_with_bootclasspath = rule( + implementation = _impl, + outputs = { + "my_output": "lib%{name}.jar", + }, + attrs = { + "srcs": attr.label_list(allow_files = [".java"]), + "sourcepath": attr.label_list(allow_files = [".jar"]), + "bootclasspath": attr.label(), + }, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], + fragments = ["java"], +) From fe2e139b2ca521b070a01160197cb506f57ba612 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Feb 2025 07:27:08 -0800 Subject: [PATCH 140/465] Add a test for java_common.compile() with a custom bootclasspathinfo and empty bootclasspath PiperOrigin-RevId: 729522132 Change-Id: Ib49f848211c8b2f83f42c5cd9e82ffdb1505c85d --- java/test/common/java_common_tests.bzl | 46 +++++++++++++++++-- .../custom_library_with_bootclasspath.bzl | 6 +-- 2 files changed, 44 insertions(+), 8 deletions(-) diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index e84999d7..a3580ff9 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -163,14 +163,16 @@ def _test_compile_extend_compile_time_jdeps_rule_outputs_impl(env, targets): ]) def _test_compile_bootclasspath(name): + files = [ + "custom-system/lib/jrt-fs.jar", + "custom-system/lib/modules", + "custom-system/release", + ] util.helper_target( custom_bootclasspath, name = name + "/bootclasspath", - srcs = [ - "custom-system/lib/jrt-fs.jar", - "custom-system/lib/modules", - "custom-system/release", - ], + bootclasspath = files, + system = files, ) util.helper_target( custom_library_with_bootclasspath, @@ -197,6 +199,39 @@ def _test_compile_bootclasspath_impl(env, target): "{}/custom-system".format(target.label.package), )]) +def _test_compile_override_with_empty_bootclasspath(name): + util.helper_target( + custom_bootclasspath, + name = name + "/bootclasspath", + bootclasspath = [], + system = [ + "custom-system/lib/jrt-fs.jar", + "custom-system/lib/modules", + "custom-system/release", + ], + ) + util.helper_target( + custom_library_with_bootclasspath, + name = name + "/custom", + srcs = ["Main.java"], + bootclasspath = name + "/bootclasspath", + ) + + analysis_test( + name = name, + impl = _test_compile_override_with_empty_bootclasspath_impl, + target = name + "/custom", + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_compile_override_with_empty_bootclasspath_impl(env, target): + assert_that_javac = env.expect.that_target(target).action_named("Javac") + + assert_that_javac.contains_flag_values([( + "--system", + "{}/custom-system".format(target.label.package), + )]) + def java_common_tests(name): test_suite( name = name, @@ -208,5 +243,6 @@ def java_common_tests(name): _test_compile_extend_compile_time_jdeps, _test_compile_extend_compile_time_jdeps_rule_outputs, _test_compile_bootclasspath, + _test_compile_override_with_empty_bootclasspath, ], ) diff --git a/java/test/testutil/rules/custom_library_with_bootclasspath.bzl b/java/test/testutil/rules/custom_library_with_bootclasspath.bzl index 666fd582..69289da2 100644 --- a/java/test/testutil/rules/custom_library_with_bootclasspath.bzl +++ b/java/test/testutil/rules/custom_library_with_bootclasspath.bzl @@ -4,13 +4,13 @@ load("//java/common:java_common.bzl", "java_common") load("//java/common:java_semantics.bzl", "semantics") def _bootclasspath(ctx): - files = ctx.files.srcs - return [java_common.BootClassPathInfo(bootclasspath = files, system = files)] + return [java_common.BootClassPathInfo(bootclasspath = ctx.files.bootclasspath, system = ctx.files.system)] custom_bootclasspath = rule( implementation = _bootclasspath, attrs = { - "srcs": attr.label_list(allow_files = True), + "bootclasspath": attr.label_list(allow_files = True), + "system": attr.label_list(allow_files = True), }, ) From fca8eb92832025ad3b840244c31037701d7b3893 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Feb 2025 08:29:46 -0800 Subject: [PATCH 141/465] Add a test that `java_binary(stamp = -1)` does not override default stamping PiperOrigin-RevId: 729539384 Change-Id: I2afaaef0d486fb3740871883a701502e1ff04d7a --- .bazelci/presubmit.yml | 2 ++ java/test/common/rules/java_binary_tests.bzl | 33 ++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 79f2e937..fff8cfd2 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -1,6 +1,8 @@ --- build_targets: &build_targets - "//..." + # can't build some analysis tests on older Bazel versions + - "-//java/test/..." - "@remote_java_tools//java_tools/..." # can't build @remote_java_tools_X repos for other platforms - "-//toolchains/..." diff --git a/java/test/common/rules/java_binary_tests.bzl b/java/test/common/rules/java_binary_tests.bzl index 2a20572a..2a8f0343 100644 --- a/java/test/common/rules/java_binary_tests.bzl +++ b/java/test/common/rules/java_binary_tests.bzl @@ -1,6 +1,7 @@ """Tests for the java_binary rule""" load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") @@ -21,10 +22,42 @@ def _test_java_binary_provides_binary_java_info_impl(env, target): assert_java_info.compilation_args().equals(None) assert_java_info.is_binary().equals(True) +def _test_stamp_conversion_does_not_override_int(name): + util.helper_target( + java_binary, + name = name + "/bin", + srcs = ["Main.java"], + stamp = -1, + ) + + analysis_test( + name = name, + impl = _test_stamp_conversion_does_not_override_int_impl, + target = name + "/bin", + config_settings = { + "//command_line_option:stamp": False, + }, + # deploy jars are in a separate rule in Bazel 7, Bazel 6 generated build-info differently + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _test_stamp_conversion_does_not_override_int_impl(env, target): + assert_deploy_jar_action = env.expect.that_target(target).action_generating( + "{package}/{name}_deploy.jar", + ) + + assert_deploy_jar_action.inputs().not_contains_predicate( + matching.file_basename_equals("non_volatile_file.properties"), + ) + assert_deploy_jar_action.inputs().contains_predicate( + matching.file_basename_equals("redacted_file.properties"), + ) + def java_binary_tests(name): test_suite( name = name, tests = [ _test_java_binary_provides_binary_java_info, + _test_stamp_conversion_does_not_override_int, ], ) From e8296038885518d7eceedffec552150bb9b0fa45 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Feb 2025 08:36:32 -0800 Subject: [PATCH 142/465] Add a separate config for Bazel 8 to rules_java CI PiperOrigin-RevId: 729541202 Change-Id: Ife01d73c2a82ebd1c74af91c5e1e0c317a0823a8 --- .bazelci/presubmit.yml | 51 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 6 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index fff8cfd2..2bf1a1fc 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -39,16 +39,16 @@ flags_workspace_integration: &flags_workspace_integration buildifier: latest tasks: -# TODO: add config for 8.0.0 once released # Bazel 7.x - ubuntu2004: + ubuntu2004_bazel7: name: "Bazel 7.x" bazel: "7.4.0" + platform: ubuntu2004 build_targets: *build_targets test_targets: *test_targets test_flags: - "--test_tag_filters=-min_bazel_8" - ubuntu2004_integration: + ubuntu2004_integration_bazel7: name: "Bazel 7.x Integration" bazel: "7.4.0" platform: ubuntu2004 @@ -57,7 +57,7 @@ tasks: - sh setup.sh build_targets: *build_targets_integration test_targets: *test_target_integration - ubuntu2004_integration_workspace: + ubuntu2004_integration_workspace_bazel7: name: "Bazel 7.x Integration (WORKSPACE)" bazel: "7.4.0" platform: ubuntu2004 @@ -68,13 +68,52 @@ tasks: build_flags: *flags_workspace_integration test_targets: *test_target_integration test_flags: *flags_workspace_integration - macos: + macos_bazel7: name: "Bazel 7.x" bazel: "7.4.0" + platform: macos build_targets: *build_targets - windows: + windows_bazel7: name: "Bazel 7.x" bazel: "7.4.0" + platform: windows + build_targets: *build_targets +# Bazel 8.x + ubuntu2004_bazel8: + name: "Bazel 8.x" + bazel: "8.1.0" + platform: ubuntu2004 + build_targets: *build_targets + test_targets: *test_targets + ubuntu2004_integration_bazel8: + name: "Bazel 8.x Integration" + bazel: "8.1.0" + platform: ubuntu2004 + working_directory: "test/repo" + shell_commands: + - sh setup.sh + build_targets: *build_targets_integration + test_targets: *test_target_integration + ubuntu2004_integration_workspace_bazel8: + name: "Bazel 8.x Integration (WORKSPACE)" + bazel: "8.1.0" + platform: ubuntu2004 + working_directory: "test/repo" + shell_commands: + - sh setup.sh + build_targets: *build_targets_integration + build_flags: *flags_workspace_integration + test_targets: *test_target_integration + test_flags: *flags_workspace_integration + macos_bazel8: + name: "Bazel 8.x" + bazel: "8.1.0" + platform: macos + build_targets: *build_targets + windows_bazel8: + name: "Bazel 8.x" + bazel: "8.1.0" + platform: windows build_targets: *build_targets # Bazel@HEAD ubuntu2004_head: From 3d757492427c10c73e48cbd0aa0623f12bfb769a Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Feb 2025 09:37:09 -0800 Subject: [PATCH 143/465] Internal change PiperOrigin-RevId: 729559095 Change-Id: I0ba256938ba3b1259d94de5b64397291e8471690 --- java/test/testutil/cc_info_subject.bzl | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/java/test/testutil/cc_info_subject.bzl b/java/test/testutil/cc_info_subject.bzl index 32c80a96..9d82be29 100644 --- a/java/test/testutil/cc_info_subject.bzl +++ b/java/test/testutil/cc_info_subject.bzl @@ -21,9 +21,28 @@ def _new_cc_info_linking_context_subject(cc_info, meta): public = struct( equals = lambda other: _cc_info_linking_context_equals(self.actual, other, self.meta), libraries_to_link = lambda: _new_cc_info_libraries_to_link_subject(self.actual, self.meta), + static_mode_params_for_dynamic_library_libs = lambda: _new_static_mode_params_for_dynamic_library_libs_subject(self.actual, self.meta), ) return public +def _new_static_mode_params_for_dynamic_library_libs_subject(linking_context, meta): + libs = [] + for input in linking_context.linker_inputs.to_list(): + for lib in input.libraries: + if lib.pic_static_library: + libs.append(lib.pic_static_library) + elif lib.static_library: + libs.append(lib.static_library) + elif lib.interface_library: + libs.append(lib.interface_library) + else: + libs.append(lib.dynamic_library) + + return subjects.collection( + libs, + meta = meta.derive("static_mode_params_for_dynamic_library_libs"), + ) + def _cc_info_linking_context_equals(actual, expected, meta): if actual == expected: return From 784f519719ecfce201624fad8e39cb13f67b70cb Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 4 Mar 2025 01:35:12 -0800 Subject: [PATCH 144/465] Update `java_tools` `v13.17` Built at https://github.com/bazelbuild/bazel/commit/0c47b6116d9eb1ec052f29d199356aee45b83a2b PiperOrigin-RevId: 733231656 Change-Id: I28a36a2e2363a8b26f20be6897bea5fd07c98db6 --- java/repositories.bzl | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/java/repositories.bzl b/java/repositories.bzl index b17057a1..d755c2ba 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.16", + "version": "v13.17", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.16/java_tools_linux-v13.16.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.16/java_tools_linux-v13.16.zip", - "sha": "cc78efd792e99b4ad5d3d031853da655aca375dbda50bd03ab94e8e2dbf2801a", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.17/java_tools_linux-v13.17.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.17/java_tools_linux-v13.17.zip", + "sha": "acae69407bbc7c240eb2e5fae7af787d22c98e4f7446be535bfa92bacaf42bde", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.16/java_tools_windows-v13.16.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.16/java_tools_windows-v13.16.zip", - "sha": "726706173a9580ece6f9b64d7fe4986a46d98ff0bb18341bc93d0c013fa214d2", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.17/java_tools_windows-v13.17.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.17/java_tools_windows-v13.17.zip", + "sha": "de2c5b9da64c6a759f026d0afcab6d44af1b5aafcf9ade07506da02b3255e014", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.16/java_tools_darwin_x86_64-v13.16.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.16/java_tools_darwin_x86_64-v13.16.zip", - "sha": "62a1785a446cd6a69db5d4207820d0e5db89ba72666be0def6990209f44b3900", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.17/java_tools_darwin_x86_64-v13.17.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.17/java_tools_darwin_x86_64-v13.17.zip", + "sha": "f9aa10b78a8b1d15f1036f44307171bf05dde4e9906bd74e282ddcba0687cee5", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.16/java_tools_darwin_arm64-v13.16.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.16/java_tools_darwin_arm64-v13.16.zip", - "sha": "20b35e87a2d430eabab7d6d1de821e5e9670aef2f5ef1ac788c72b4b00dbb8bf", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.17/java_tools_darwin_arm64-v13.17.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.17/java_tools_darwin_arm64-v13.17.zip", + "sha": "4bb3f1950a3db214f788035efce711c5b35a7fd884dffa66b1fb045d33889b14", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.16/java_tools-v13.16.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.16/java_tools-v13.16.zip", - "sha": "11242f40a18aa4a766caa02e3f165c9d2ac7dba3fbfae1e7871a3916c98bddbf", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.17/java_tools-v13.17.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.17/java_tools-v13.17.zip", + "sha": "a5e1c740690399ec0d5dacff59a2aa0cb13fbb904efa5cdf6e7fda4e030515ef", }, }, } From 8b3a998cc3e043a2048681e5259766a8ab71f52a Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 4 Mar 2025 01:53:14 -0800 Subject: [PATCH 145/465] Release `@rules_java` `v8.10.0` PiperOrigin-RevId: 733236234 Change-Id: I96b24071ac1fcec6865169ff9282ed234c33651f --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 4e9bdf20..adcf1c0c 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.9.0", + version = "8.10.0", bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) From 20175c775df64012140434b643f2a13e5213a650 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 02:21:07 -0800 Subject: [PATCH 146/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithOutputJarOnly` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734474416 Change-Id: I0e059b8941cf0f5ce8cf0ed5b9800314ca413e8e --- java/test/common/BUILD | 3 ++ java/test/common/java_info_tests.bzl | 37 +++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 3 ++ .../testutil/rules/custom_java_info_rule.bzl | 24 ++++++++++++ 4 files changed, 67 insertions(+) create mode 100644 java/test/common/java_info_tests.bzl create mode 100644 java/test/testutil/rules/custom_java_info_rule.bzl diff --git a/java/test/common/BUILD b/java/test/common/BUILD index 18ab4f84..c9cd0668 100644 --- a/java/test/common/BUILD +++ b/java/test/common/BUILD @@ -1,3 +1,6 @@ load(":java_common_tests.bzl", "java_common_tests") +load(":java_info_tests.bzl", "java_info_tests") java_common_tests(name = "java_common_tests") + +java_info_tests(name = "java_info_tests") diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl new file mode 100644 index 00000000..af5ff91d --- /dev/null +++ b/java/test/common/java_info_tests.bzl @@ -0,0 +1,37 @@ +"""Tests for the JavaInfo provider""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") + +def _with_output_jar_only_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + ) + + analysis_test( + name = name, + impl = _with_output_jar_only_test_impl, + target = target_name, + ) + +def _with_output_jar_only_test_impl(env, target): + assert_compilation_args = java_info_subject.from_target(env, target).compilation_args() + + assert_compilation_args.compile_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.full_compile_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.transitive_runtime_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.transitive_compile_time_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + +def java_info_tests(name): + test_suite( + name = name, + tests = [ + _with_output_jar_only_test, + ], + ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 5d407f01..71a82c1f 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -43,7 +43,10 @@ def _new_java_compilation_args_subject(java_info, meta): return struct( equals = lambda other: _java_compilation_args_equals(self, other), equals_subject = lambda other: _java_compilation_args_equals(self, other.actual), + compile_jars = lambda: subjects.depset_file(actual.compile_jars, self.meta.derive("compile_jars")), + full_compile_jars = lambda: subjects.depset_file(actual.full_compile_jars, self.meta.derive("full_compile_jars")), transitive_runtime_jars = lambda: subjects.depset_file(actual.transitive_runtime_jars, self.meta.derive("transitive_runtime_jars")), + transitive_compile_time_jars = lambda: subjects.depset_file(actual.transitive_compile_time_jars, self.meta.derive("transitive_compile_time_jars")), self = self, actual = actual, ) diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl new file mode 100644 index 00000000..7aa7453a --- /dev/null +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -0,0 +1,24 @@ +"""Helper rule for creating JavaInfo instances""" + +load("//java/common:java_info.bzl", "JavaInfo") + +def _impl(ctx): + ctx.actions.write(ctx.outputs.output_jar, "JavaInfo API Test", is_executable = False) + source_jar = ctx.files.source_jars[0] if ctx.files.source_jars else None + compile_jar = ctx.outputs.output_jar + + return [ + JavaInfo( + output_jar = ctx.outputs.output_jar, + compile_jar = compile_jar, + source_jar = source_jar, + ), + ] + +custom_java_info_rule = rule( + _impl, + attrs = { + "output_jar": attr.output(mandatory = True), + "source_jars": attr.label_list(allow_files = [".jar"]), + }, +) From b8f15979dd1be66b38fc05e431de5c864cbd3b9a Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 02:34:32 -0800 Subject: [PATCH 147/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithOutputJarAndUseIJar` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734478007 Change-Id: I9f63e6c24193e547b6e83806e224ad01c12ef77a --- java/test/common/java_info_tests.bzl | 25 +++++++++++++++++++ .../testutil/rules/custom_java_info_rule.bzl | 10 +++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index af5ff91d..88222d77 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -28,10 +28,35 @@ def _with_output_jar_only_test_impl(env, target): assert_compilation_args.transitive_runtime_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) assert_compilation_args.transitive_compile_time_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) +def _with_output_jar_and_use_ijar_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + use_ijar = True, + ) + + analysis_test( + name = name, + impl = _with_output_jar_and_use_ijar_test_impl, + target = target_name, + ) + +def _with_output_jar_and_use_ijar_test_impl(env, target): + assert_compilation_args = java_info_subject.from_target(env, target).compilation_args() + + assert_compilation_args.compile_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib-ijar.jar"]) + assert_compilation_args.full_compile_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.transitive_runtime_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.transitive_compile_time_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib-ijar.jar"]) + def java_info_tests(name): test_suite( name = name, tests = [ _with_output_jar_only_test, + _with_output_jar_and_use_ijar_test, ], ) diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index 7aa7453a..30728857 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -1,11 +1,17 @@ """Helper rule for creating JavaInfo instances""" +load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_semantics.bzl", "semantics") def _impl(ctx): ctx.actions.write(ctx.outputs.output_jar, "JavaInfo API Test", is_executable = False) source_jar = ctx.files.source_jars[0] if ctx.files.source_jars else None - compile_jar = ctx.outputs.output_jar + compile_jar = java_common.run_ijar( + ctx.actions, + jar = ctx.outputs.output_jar, + java_toolchain = semantics.find_java_toolchain(ctx), + ) if ctx.attr.use_ijar else ctx.outputs.output_jar return [ JavaInfo( @@ -20,5 +26,7 @@ custom_java_info_rule = rule( attrs = { "output_jar": attr.output(mandatory = True), "source_jars": attr.label_list(allow_files = [".jar"]), + "use_ijar": attr.bool(default = False), }, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], ) From 63e326ff010514240a1aeabbc4c57cad784a8bee Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 03:02:13 -0800 Subject: [PATCH 148/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoJavaRuleOutputJarsProviderSourceJarOutputJarAndUseIJar` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734485250 Change-Id: I935d0f5a53c7e13463f496ae8d64af99e029c9f5 --- java/test/common/java_info_tests.bzl | 24 +++++++++++++++++ java/test/testutil/java_info_subject.bzl | 34 ++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 88222d77..ce09321e 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -52,11 +52,35 @@ def _with_output_jar_and_use_ijar_test_impl(env, target): assert_compilation_args.transitive_runtime_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) assert_compilation_args.transitive_compile_time_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib-ijar.jar"]) +def _with_output_jar_and_use_ijar_outputs_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + use_ijar = True, + ) + + analysis_test( + name = name, + impl = _with_output_jar_and_use_ijar_outputs_test_impl, + target = target_name, + ) + +def _with_output_jar_and_use_ijar_outputs_test_impl(env, target): + assert_outputs = java_info_subject.from_target(env, target).outputs() + + assert_outputs.source_output_jars().contains_exactly(["{package}/my_starlark_rule_src.jar"]) + assert_outputs.class_output_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_outputs.jars().singleton().compile_jar().short_path_equals("{package}/{name}/my_starlark_rule_lib-ijar.jar") + def java_info_tests(name): test_suite( name = name, tests = [ _with_output_jar_only_test, _with_output_jar_and_use_ijar_test, + _with_output_jar_and_use_ijar_outputs_test, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 71a82c1f..646b898d 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -15,6 +15,7 @@ def _new_java_info_subject(java_info, meta): cc_link_params_info = lambda: cc_info_subject.new_from_java_info(java_info, meta), constraints = lambda: subjects.collection(java_common.get_constraints(java_info), self.meta.derive("constraints")), annotation_processing = lambda: _new_annotation_processing_subject(self.actual, self.meta), + outputs = lambda: _new_rule_output_info_subject(self.actual, self.meta), ) return public @@ -26,6 +27,34 @@ def _java_info_subject_from_target(env, target): }, )) +def _new_rule_output_info_subject(java_info, meta): + actual = java_info.outputs + self = struct( + actual = actual, + meta = meta.derive("outputs"), + ) + + # JavaOutputInfo.source_jars is a list before Bazel 7 + source_jars_depset = depset([f for o in actual.jars for f in (o.source_jars.to_list() if hasattr(o.source_jars, "to_list") else o.source_jars)]) + public = struct( + jars = lambda: _new_java_outputs_collection_subject(actual.jars, self.meta.derive("jars")), + class_output_jars = lambda: subjects.depset_file(depset([o.class_jar for o in actual.jars]), self.meta.derive("class_output_jars")), + source_output_jars = lambda: subjects.depset_file(source_jars_depset, self.meta.derive("source_output_jars")), + ) + return public + +def _new_java_outputs_collection_subject(java_outputs, meta): + public = struct( + singleton = lambda: _new_java_outputs_subject(_get_singleton(java_outputs), meta.derive("[0]")), + ) + return public + +def _new_java_outputs_subject(java_output, meta): + public = struct( + compile_jar = lambda: subjects.file(java_output.compile_jar, meta.derive("compile_jar")), + ) + return public + def _new_java_compilation_args_subject(java_info, meta): is_binary = getattr(java_info, "_is_binary", False) actual = struct( @@ -93,6 +122,11 @@ def _new_annotation_processing_subject(java_info, meta): ) return public +def _get_singleton(seq): + if len(seq) != 1: + fail("expected singleton, got:", seq) + return seq[0] + java_info_subject = struct( new = _new_java_info_subject, from_target = _java_info_subject_from_target, From 08fa9f7907452781f1fb7a36b9c2e6bdc27bc211 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 04:42:56 -0800 Subject: [PATCH 149/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithDeps` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734508557 Change-Id: Iea01808b87eef2c6d7d19d14d6022e2860563fda --- java/test/common/java_info_tests.bzl | 37 +++++++++++++++++++ .../testutil/rules/custom_java_info_rule.bzl | 3 ++ 2 files changed, 40 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index ce09321e..5bda63dd 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -2,6 +2,7 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") +load("//java:java_library.bzl", "java_library") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") @@ -75,6 +76,41 @@ def _with_output_jar_and_use_ijar_outputs_test_impl(env, target): assert_outputs.class_output_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) assert_outputs.jars().singleton().compile_jar().short_path_equals("{package}/{name}/my_starlark_rule_lib-ijar.jar") +def _with_deps_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_direct", + srcs = ["java/A.java"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + dep = [target_name + "/my_java_lib_direct"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + ) + + analysis_test( + name = name, + impl = _with_deps_test_impl, + target = target_name, + ) + +def _with_deps_test_impl(env, target): + assert_compilation_args = java_info_subject.from_target(env, target).compilation_args() + + assert_compilation_args.compile_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.full_compile_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.transitive_runtime_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_direct.jar", + ]) + assert_compilation_args.transitive_compile_time_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_direct-hjar.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -82,5 +118,6 @@ def java_info_tests(name): _with_output_jar_only_test, _with_output_jar_and_use_ijar_test, _with_output_jar_and_use_ijar_outputs_test, + _with_deps_test, ], ) diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index 30728857..65b91e83 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -6,6 +6,7 @@ load("//java/common:java_semantics.bzl", "semantics") def _impl(ctx): ctx.actions.write(ctx.outputs.output_jar, "JavaInfo API Test", is_executable = False) + dp = [dep[JavaInfo] for dep in ctx.attr.dep] source_jar = ctx.files.source_jars[0] if ctx.files.source_jars else None compile_jar = java_common.run_ijar( ctx.actions, @@ -18,6 +19,7 @@ def _impl(ctx): output_jar = ctx.outputs.output_jar, compile_jar = compile_jar, source_jar = source_jar, + deps = dp, ), ] @@ -26,6 +28,7 @@ custom_java_info_rule = rule( attrs = { "output_jar": attr.output(mandatory = True), "source_jars": attr.label_list(allow_files = [".jar"]), + "dep": attr.label_list(), "use_ijar": attr.bool(default = False), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], From 0a6d10223498c4c1b902f6b3dc7b3718ef9afaf9 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 04:57:53 -0800 Subject: [PATCH 150/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithRunTimeDeps` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734512098 Change-Id: Ifd42b0657df61f9e89468b5ba314b32816919cf1 --- java/test/common/java_info_tests.bzl | 33 +++++++++++++++++++ .../testutil/rules/custom_java_info_rule.bzl | 3 ++ 2 files changed, 36 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 5bda63dd..19b35cbb 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -111,6 +111,38 @@ def _with_deps_test_impl(env, target): "{package}/lib{name}/my_java_lib_direct-hjar.jar", ]) +def _with_runtime_deps_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_direct", + srcs = ["java/A.java"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + dep_runtime = [target_name + "/my_java_lib_direct"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + ) + + analysis_test( + name = name, + impl = _with_runtime_deps_test_impl, + target = target_name, + ) + +def _with_runtime_deps_test_impl(env, target): + assert_compilation_args = java_info_subject.from_target(env, target).compilation_args() + + assert_compilation_args.compile_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.full_compile_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.transitive_runtime_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_direct.jar", + ]) + assert_compilation_args.transitive_compile_time_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + def java_info_tests(name): test_suite( name = name, @@ -119,5 +151,6 @@ def java_info_tests(name): _with_output_jar_and_use_ijar_test, _with_output_jar_and_use_ijar_outputs_test, _with_deps_test, + _with_runtime_deps_test, ], ) diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index 65b91e83..0492120e 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -7,6 +7,7 @@ load("//java/common:java_semantics.bzl", "semantics") def _impl(ctx): ctx.actions.write(ctx.outputs.output_jar, "JavaInfo API Test", is_executable = False) dp = [dep[JavaInfo] for dep in ctx.attr.dep] + dp_runtime = [dep[JavaInfo] for dep in ctx.attr.dep_runtime] source_jar = ctx.files.source_jars[0] if ctx.files.source_jars else None compile_jar = java_common.run_ijar( ctx.actions, @@ -20,6 +21,7 @@ def _impl(ctx): compile_jar = compile_jar, source_jar = source_jar, deps = dp, + runtime_deps = dp_runtime, ), ] @@ -29,6 +31,7 @@ custom_java_info_rule = rule( "output_jar": attr.output(mandatory = True), "source_jars": attr.label_list(allow_files = [".jar"]), "dep": attr.label_list(), + "dep_runtime": attr.label_list(), "use_ijar": attr.bool(default = False), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], From 62636749c7d11ce6854c7ccdda2e46abe2ff705f Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 05:16:41 -0800 Subject: [PATCH 151/465] Migrate the `JavaInfoStarlarkApiTest.javaInfo_setNativeLibraries` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734516551 Change-Id: Ia06c3ce4174e6e88899abc368f9735c40e3dcf21 --- java/test/common/java_info_tests.bzl | 31 +++++++++++++++++++ java/test/testutil/cc_info_subject.bzl | 12 ++++--- java/test/testutil/java_info_subject.bzl | 1 + .../testutil/rules/custom_java_info_rule.bzl | 4 +++ 4 files changed, 44 insertions(+), 4 deletions(-) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 19b35cbb..70ea6346 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -1,6 +1,8 @@ """Tests for the JavaInfo provider""" +load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") @@ -143,6 +145,34 @@ def _with_runtime_deps_test_impl(env, target): ]) assert_compilation_args.transitive_compile_time_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) +def _with_native_libraries_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + cc_library, + name = target_name + "/my_cc_lib_direct", + srcs = ["cc/a.cc"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + cc_dep = [target_name + "/my_cc_lib_direct"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + ) + + analysis_test( + name = name, + impl = _with_native_libraries_test_impl, + target = target_name, + # LibraryToLink.library_indentifier only available from Bazel 8 + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _with_native_libraries_test_impl(env, target): + assert_native_libs = java_info_subject.from_target(env, target).transitive_native_libraries() + + assert_native_libs.identifiers().contains_exactly_predicates([matching.str_endswith("my_cc_lib_direct")]) + def java_info_tests(name): test_suite( name = name, @@ -152,5 +182,6 @@ def java_info_tests(name): _with_output_jar_and_use_ijar_outputs_test, _with_deps_test, _with_runtime_deps_test, + _with_native_libraries_test, ], ) diff --git a/java/test/testutil/cc_info_subject.bzl b/java/test/testutil/cc_info_subject.bzl index 9d82be29..a2ab6706 100644 --- a/java/test/testutil/cc_info_subject.bzl +++ b/java/test/testutil/cc_info_subject.bzl @@ -20,7 +20,7 @@ def _new_cc_info_linking_context_subject(cc_info, meta): ) public = struct( equals = lambda other: _cc_info_linking_context_equals(self.actual, other, self.meta), - libraries_to_link = lambda: _new_cc_info_libraries_to_link_subject(self.actual, self.meta), + libraries_to_link = lambda: _new_cc_info_libraries_to_link_subject(self.actual.libraries_to_link, self.meta.derive("libraries_to_link")), static_mode_params_for_dynamic_library_libs = lambda: _new_static_mode_params_for_dynamic_library_libs_subject(self.actual, self.meta), ) return public @@ -51,10 +51,12 @@ def _cc_info_linking_context_equals(actual, expected, meta): "actual: {}".format(actual), ) -def _new_cc_info_libraries_to_link_subject(linking_context, meta): +def _new_cc_info_libraries_to_link_subject(libraries_to_link, meta): + if hasattr(libraries_to_link, "to_list"): + libraries_to_link = libraries_to_link.to_list() self = struct( - actual = linking_context.libraries_to_link, - meta = meta.derive("libraries_to_link"), + actual = libraries_to_link, + meta = meta, ) public = struct( identifiers = lambda: _new_library_to_link_identifiers_subject(self.actual, self.meta), @@ -68,9 +70,11 @@ def _new_library_to_link_identifiers_subject(libraries_to_link, meta): ) public = struct( contains_exactly = lambda expected: self.contains_exactly([meta.format_str(e) for e in expected]), + contains_exactly_predicates = lambda expected: self.contains_exactly_predicates(expected), ) return public cc_info_subject = struct( new_from_java_info = lambda java_info, meta: _new_cc_info_subject(java_info.cc_link_params_info, meta.derive("cc_link_params_info")), + libraries_to_link = _new_cc_info_libraries_to_link_subject, ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 646b898d..e64b61a1 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -13,6 +13,7 @@ def _new_java_info_subject(java_info, meta): is_binary = lambda: subjects.bool(getattr(java_info, "_is_binary", False), self.meta.derive("_is_binary")), has_attr = lambda a: subjects.bool(getattr(java_info, a, None) != None, meta = self.meta.derive("{} != None".format(a))).equals(True), cc_link_params_info = lambda: cc_info_subject.new_from_java_info(java_info, meta), + transitive_native_libraries = lambda: cc_info_subject.libraries_to_link(java_info.transitive_native_libraries, self.meta.derive("transitive_native_libraries")), constraints = lambda: subjects.collection(java_common.get_constraints(java_info), self.meta.derive("constraints")), annotation_processing = lambda: _new_annotation_processing_subject(self.actual, self.meta), outputs = lambda: _new_rule_output_info_subject(self.actual, self.meta), diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index 0492120e..2dc6d5e4 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -1,5 +1,6 @@ """Helper rule for creating JavaInfo instances""" +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") @@ -9,6 +10,7 @@ def _impl(ctx): dp = [dep[JavaInfo] for dep in ctx.attr.dep] dp_runtime = [dep[JavaInfo] for dep in ctx.attr.dep_runtime] source_jar = ctx.files.source_jars[0] if ctx.files.source_jars else None + dp_libs = [dep[CcInfo] for dep in ctx.attr.cc_dep] compile_jar = java_common.run_ijar( ctx.actions, jar = ctx.outputs.output_jar, @@ -22,6 +24,7 @@ def _impl(ctx): source_jar = source_jar, deps = dp, runtime_deps = dp_runtime, + native_libraries = dp_libs, ), ] @@ -32,6 +35,7 @@ custom_java_info_rule = rule( "source_jars": attr.label_list(allow_files = [".jar"]), "dep": attr.label_list(), "dep_runtime": attr.label_list(), + "cc_dep": attr.label_list(), "use_ijar": attr.bool(default = False), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], From 780f2acdf4115d69e8e901a108831026d8bb0db8 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 05:35:38 -0800 Subject: [PATCH 152/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithDepsAndNeverLink` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734520674 Change-Id: I96b359f083d61572feb4931f7e82d883b08b7f7b --- java/test/common/java_info_tests.bzl | 34 +++++++++++++++++++ .../testutil/rules/custom_java_info_rule.bzl | 2 ++ 2 files changed, 36 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 70ea6346..e7124656 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -173,6 +173,39 @@ def _with_native_libraries_test_impl(env, target): assert_native_libs.identifiers().contains_exactly_predicates([matching.str_endswith("my_cc_lib_direct")]) +def _with_deps_and_neverlink_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_direct", + srcs = ["java/A.java"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + dep = [target_name + "/my_java_lib_direct"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + neverlink = True, + ) + + analysis_test( + name = name, + impl = _with_deps_and_neverlink_test_impl, + target = target_name, + ) + +def _with_deps_and_neverlink_test_impl(env, target): + assert_compilation_args = java_info_subject.from_target(env, target).compilation_args() + + assert_compilation_args.compile_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.full_compile_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.transitive_runtime_jars().contains_exactly([]) + assert_compilation_args.transitive_compile_time_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_direct-hjar.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -183,5 +216,6 @@ def java_info_tests(name): _with_deps_test, _with_runtime_deps_test, _with_native_libraries_test, + _with_deps_and_neverlink_test, ], ) diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index 2dc6d5e4..909ffa44 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -25,6 +25,7 @@ def _impl(ctx): deps = dp, runtime_deps = dp_runtime, native_libraries = dp_libs, + neverlink = ctx.attr.neverlink, ), ] @@ -37,6 +38,7 @@ custom_java_info_rule = rule( "dep_runtime": attr.label_list(), "cc_dep": attr.label_list(), "use_ijar": attr.bool(default = False), + "neverlink": attr.bool(default = False), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], ) From 2d01682c43ca90617211bb113ae56dee5dfdca74 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 06:13:38 -0800 Subject: [PATCH 153/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoSourceJarsProviderWithSourceJars` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734530626 Change-Id: I4b487633bc94cfd5ed7a7289f675018e1d626b2e --- java/test/common/java_info_tests.bzl | 26 ++++++++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 2 ++ 2 files changed, 28 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index e7124656..88db896e 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -206,6 +206,31 @@ def _with_deps_and_neverlink_test_impl(env, target): "{package}/lib{name}/my_java_lib_direct-hjar.jar", ]) +def _with_source_jars_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + ) + + analysis_test( + name = name, + impl = _with_source_jars_test_impl, + target = target_name, + ) + +def _with_source_jars_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("my_starlark_rule_src.jar"), + ]) + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/my_starlark_rule_src.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -217,5 +242,6 @@ def java_info_tests(name): _with_runtime_deps_test, _with_native_libraries_test, _with_deps_and_neverlink_test, + _with_source_jars_test, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index e64b61a1..3e188338 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -17,6 +17,8 @@ def _new_java_info_subject(java_info, meta): constraints = lambda: subjects.collection(java_common.get_constraints(java_info), self.meta.derive("constraints")), annotation_processing = lambda: _new_annotation_processing_subject(self.actual, self.meta), outputs = lambda: _new_rule_output_info_subject(self.actual, self.meta), + source_jars = lambda: subjects.collection(java_info.source_jars, self.meta.derive("source_jars")), + transitive_source_jars = lambda: subjects.depset_file(java_info.transitive_source_jars, self.meta.derive("transitive_source_jars")), ) return public From 6da6693337f4bee73e7f715c3df39bb62d39b614 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 06:30:44 -0800 Subject: [PATCH 154/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperPackSources_repackSingleJar` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734534968 Change-Id: Ie0481c51e68b39126f457212656e7b71297364c0 --- java/test/common/java_info_tests.bzl | 27 +++++++++++++++++++ .../testutil/rules/custom_java_info_rule.bzl | 10 ++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 88db896e..0d326574 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -231,6 +231,32 @@ def _with_source_jars_test_impl(env, target): "{package}/my_starlark_rule_src.jar", ]) +def _with_packed_sourcejars_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + pack_sources = True, + ) + + analysis_test( + name = name, + impl = _with_packed_sourcejars_test_impl, + target = target_name, + ) + +def _with_packed_sourcejars_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("my_starlark_rule_lib-src.jar"), + ]) + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib-src.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -243,5 +269,6 @@ def java_info_tests(name): _with_native_libraries_test, _with_deps_and_neverlink_test, _with_source_jars_test, + _with_packed_sourcejars_test, ], ) diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index 909ffa44..877e26d6 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -9,7 +9,14 @@ def _impl(ctx): ctx.actions.write(ctx.outputs.output_jar, "JavaInfo API Test", is_executable = False) dp = [dep[JavaInfo] for dep in ctx.attr.dep] dp_runtime = [dep[JavaInfo] for dep in ctx.attr.dep_runtime] - source_jar = ctx.files.source_jars[0] if ctx.files.source_jars else None + source_jar = java_common.pack_sources( + ctx.actions, + output_source_jar = ctx.actions.declare_file(ctx.outputs.output_jar.basename[:-4] + "-src.jar", sibling = ctx.outputs.output_jar), + source_jars = ctx.files.source_jars, + java_toolchain = semantics.find_java_toolchain(ctx), + ) if ctx.attr.pack_sources else ( + ctx.files.source_jars[0] if ctx.files.source_jars else None + ) dp_libs = [dep[CcInfo] for dep in ctx.attr.cc_dep] compile_jar = java_common.run_ijar( ctx.actions, @@ -39,6 +46,7 @@ custom_java_info_rule = rule( "cc_dep": attr.label_list(), "use_ijar": attr.bool(default = False), "neverlink": attr.bool(default = False), + "pack_sources": attr.bool(default = False), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], ) From 310b644878055c36eefa761809ee42ccebefd94b Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 07:03:35 -0800 Subject: [PATCH 155/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithSourcesFiles` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734543682 Change-Id: I3a08c4413f16e46dad88444fb65c07aebbca0413 --- java/test/common/java_info_tests.bzl | 30 +++++++++++++++++++ .../testutil/rules/custom_java_info_rule.bzl | 2 ++ 2 files changed, 32 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 0d326574..7e590fa7 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -257,6 +257,35 @@ def _with_packed_sourcejars_test_impl(env, target): "{package}/{name}/my_starlark_rule_lib-src.jar", ]) +def _with_packed_sources_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + output_jar = target_name + "/my_starlark_rule_lib.jar", + sources = ["ClassA.java", "ClassB.java", "ClassC.java", "ClassD.java"], + pack_sources = True, + ) + + analysis_test( + name = name, + impl = _with_packed_sources_test_impl, + target = target_name, + ) + +def _with_packed_sources_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.outputs().source_output_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib-src.jar", + ]) + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("my_starlark_rule_lib-src.jar"), + ]) + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib-src.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -270,5 +299,6 @@ def java_info_tests(name): _with_deps_and_neverlink_test, _with_source_jars_test, _with_packed_sourcejars_test, + _with_packed_sources_test, ], ) diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index 877e26d6..9d0c9a75 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -12,6 +12,7 @@ def _impl(ctx): source_jar = java_common.pack_sources( ctx.actions, output_source_jar = ctx.actions.declare_file(ctx.outputs.output_jar.basename[:-4] + "-src.jar", sibling = ctx.outputs.output_jar), + sources = ctx.files.sources, source_jars = ctx.files.source_jars, java_toolchain = semantics.find_java_toolchain(ctx), ) if ctx.attr.pack_sources else ( @@ -41,6 +42,7 @@ custom_java_info_rule = rule( attrs = { "output_jar": attr.output(mandatory = True), "source_jars": attr.label_list(allow_files = [".jar"]), + "sources": attr.label_list(allow_files = [".java"]), "dep": attr.label_list(), "dep_runtime": attr.label_list(), "cc_dep": attr.label_list(), From a792026b96cf161edf08015acad8274542411b10 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 07:44:43 -0800 Subject: [PATCH 156/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithSourcesFilesAndSourcesJars` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734554698 Change-Id: I401a22d0ef2c85ce0dc5fd12059ba845ac267f4d --- java/test/common/java_info_tests.bzl | 31 ++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 7e590fa7..aaf001a5 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -286,6 +286,36 @@ def _with_packed_sources_test_impl(env, target): "{package}/{name}/my_starlark_rule_lib-src.jar", ]) +def _with_packed_sources_and_source_jars_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src-A.jar"], + sources = ["ClassA.java", "ClassB.java", "ClassC.java", "ClassD.java"], + pack_sources = True, + ) + + analysis_test( + name = name, + impl = _with_packed_sources_and_source_jars_test_impl, + target = target_name, + ) + +def _with_packed_sources_and_source_jars_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.outputs().source_output_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib-src.jar", + ]) + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("my_starlark_rule_lib-src.jar"), + ]) + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib-src.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -300,5 +330,6 @@ def java_info_tests(name): _with_source_jars_test, _with_packed_sourcejars_test, _with_packed_sources_test, + _with_packed_sources_and_source_jars_test, ], ) From 9f340ac861801dd9a9c88bd6f714caec3b93783d Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 08:15:54 -0800 Subject: [PATCH 157/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoSourceJarsProviderWithDeps` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734563930 Change-Id: Id72f8e1c532a420bf52c736b602a725d72510b62 --- java/test/common/java_info_tests.bzl | 33 ++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index aaf001a5..8b95fc47 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -316,6 +316,38 @@ def _with_packed_sources_and_source_jars_test_impl(env, target): "{package}/{name}/my_starlark_rule_lib-src.jar", ]) +def _with_deps_source_jars_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_direct", + srcs = ["java/A.java"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + dep = [target_name + "/my_java_lib_direct"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + ) + + analysis_test( + name = name, + impl = _with_deps_source_jars_test_impl, + target = target_name, + ) + +def _with_deps_source_jars_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("my_starlark_rule_src.jar"), + ]) + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/my_starlark_rule_src.jar", + "{package}/lib{name}/my_java_lib_direct-src.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -331,5 +363,6 @@ def java_info_tests(name): _with_packed_sourcejars_test, _with_packed_sources_test, _with_packed_sources_and_source_jars_test, + _with_deps_source_jars_test, ], ) From 3105872b40c944149f3dc5f9e859407e34b0d127 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 08:33:50 -0800 Subject: [PATCH 158/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoJavaSourceJarsProviderAndRuntimeDeps` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734569236 Change-Id: Iba1a2d32df5187045040179fe51868c26c865054 --- java/test/common/java_info_tests.bzl | 33 ++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 8b95fc47..c89fa48d 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -348,6 +348,38 @@ def _with_deps_source_jars_test_impl(env, target): "{package}/lib{name}/my_java_lib_direct-src.jar", ]) +def _with_runtime_deps_source_jars_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_direct", + srcs = ["java/A.java"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + dep_runtime = [target_name + "/my_java_lib_direct"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + ) + + analysis_test( + name = name, + impl = _with_runtime_deps_source_jars_test_impl, + target = target_name, + ) + +def _with_runtime_deps_source_jars_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("my_starlark_rule_src.jar"), + ]) + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/my_starlark_rule_src.jar", + "{package}/lib{name}/my_java_lib_direct-src.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -364,5 +396,6 @@ def java_info_tests(name): _with_packed_sources_test, _with_packed_sources_and_source_jars_test, _with_deps_source_jars_test, + _with_runtime_deps_source_jars_test, ], ) From 965ec76f109bc8dd47a8da19848e0aa955989c4d Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 08:51:50 -0800 Subject: [PATCH 159/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoJavaSourceJarsProviderAndTransitiveDeps` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734574842 Change-Id: Ie536dc1687462c4dfd632b3bd1f447821aef1fad --- java/test/common/java_info_tests.bzl | 40 ++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index c89fa48d..2794245e 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -380,6 +380,45 @@ def _with_runtime_deps_source_jars_test_impl(env, target): "{package}/lib{name}/my_java_lib_direct-src.jar", ]) +def _with_transitive_deps_source_jars_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_transitive", + srcs = ["java/B.java"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_direct", + srcs = ["java/A.java"], + deps = [target_name + "/my_java_lib_transitive"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + dep_runtime = [target_name + "/my_java_lib_direct"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + ) + + analysis_test( + name = name, + impl = _with_transitive_deps_source_jars_test_impl, + target = target_name, + ) + +def _with_transitive_deps_source_jars_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("my_starlark_rule_src.jar"), + ]) + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/my_starlark_rule_src.jar", + "{package}/lib{name}/my_java_lib_direct-src.jar", + "{package}/lib{name}/my_java_lib_transitive-src.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -397,5 +436,6 @@ def java_info_tests(name): _with_packed_sources_and_source_jars_test, _with_deps_source_jars_test, _with_runtime_deps_source_jars_test, + _with_transitive_deps_source_jars_test, ], ) From cdb3c48a6e01c88db9d53a593d0734d404b10a5f Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 09:09:45 -0800 Subject: [PATCH 160/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoJavaSourceJarsProviderAndTransitiveRuntimeDeps` test to Starlark The existing native test was actually incorrect in that it was not testing runtime deps as the name would suggest. Fixed in the Starlark test. The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734580266 Change-Id: If2c94fd44bb81c75902cf3631a72e64f1f89f1eb --- java/test/common/java_info_tests.bzl | 40 ++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 2794245e..fe82f0e9 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -419,6 +419,45 @@ def _with_transitive_deps_source_jars_test_impl(env, target): "{package}/lib{name}/my_java_lib_transitive-src.jar", ]) +def _with_transitive_runtime_deps_source_jars_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_transitive", + srcs = ["java/B.java"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_direct", + srcs = ["java/A.java"], + runtime_deps = [target_name + "/my_java_lib_transitive"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + dep_runtime = [target_name + "/my_java_lib_direct"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + ) + + analysis_test( + name = name, + impl = _with_transitive_runtime_deps_source_jars_test_impl, + target = target_name, + ) + +def _with_transitive_runtime_deps_source_jars_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("my_starlark_rule_src.jar"), + ]) + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/my_starlark_rule_src.jar", + "{package}/lib{name}/my_java_lib_direct-src.jar", + "{package}/lib{name}/my_java_lib_transitive-src.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -437,5 +476,6 @@ def java_info_tests(name): _with_deps_source_jars_test, _with_runtime_deps_source_jars_test, _with_transitive_deps_source_jars_test, + _with_transitive_runtime_deps_source_jars_test, ], ) From 65d7c62edaff4a883a139b7c290c84b35c479c96 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 09:27:41 -0800 Subject: [PATCH 161/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoExportProviderExportsDepsAdded` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734585354 Change-Id: I68f3d162c1170b62a73dc823a0294c4dc7b3af01 --- java/test/common/java_info_tests.bzl | 44 +++++++++++++++++++ .../testutil/rules/custom_java_info_rule.bzl | 3 ++ 2 files changed, 47 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index fe82f0e9..790bb56a 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -458,6 +458,49 @@ def _with_transitive_runtime_deps_source_jars_test_impl(env, target): "{package}/lib{name}/my_java_lib_transitive-src.jar", ]) +def _with_exports_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_exports", + srcs = ["java/A.java"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + dep_exports = [target_name + "/my_java_lib_exports"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + ) + + analysis_test( + name = name, + impl = _with_exports_test_impl, + target = target_name, + ) + +def _with_exports_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.source_jars().contains_exactly([]) + + assert_compilation_args = assert_java_info.compilation_args() + assert_compilation_args.compile_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_exports-hjar.jar", + ]) + assert_compilation_args.full_compile_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_exports.jar", + ]) + assert_compilation_args.transitive_runtime_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_exports.jar", + ]) + assert_compilation_args.transitive_compile_time_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_exports-hjar.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -477,5 +520,6 @@ def java_info_tests(name): _with_runtime_deps_source_jars_test, _with_transitive_deps_source_jars_test, _with_transitive_runtime_deps_source_jars_test, + _with_exports_test, ], ) diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index 9d0c9a75..215c9353 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -9,6 +9,7 @@ def _impl(ctx): ctx.actions.write(ctx.outputs.output_jar, "JavaInfo API Test", is_executable = False) dp = [dep[JavaInfo] for dep in ctx.attr.dep] dp_runtime = [dep[JavaInfo] for dep in ctx.attr.dep_runtime] + dp_exports = [dep[java_common.provider] for dep in ctx.attr.dep_exports] source_jar = java_common.pack_sources( ctx.actions, output_source_jar = ctx.actions.declare_file(ctx.outputs.output_jar.basename[:-4] + "-src.jar", sibling = ctx.outputs.output_jar), @@ -32,6 +33,7 @@ def _impl(ctx): source_jar = source_jar, deps = dp, runtime_deps = dp_runtime, + exports = dp_exports, native_libraries = dp_libs, neverlink = ctx.attr.neverlink, ), @@ -45,6 +47,7 @@ custom_java_info_rule = rule( "sources": attr.label_list(allow_files = [".java"]), "dep": attr.label_list(), "dep_runtime": attr.label_list(), + "dep_exports": attr.label_list(), "cc_dep": attr.label_list(), "use_ijar": attr.bool(default = False), "neverlink": attr.bool(default = False), From cc186d5867b8fd471b8ca7861aeb56bf984f543c Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 09:44:47 -0800 Subject: [PATCH 162/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoExportProvider` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734590452 Change-Id: Ib5455de7b048400a129f39e4c27d202e7e3804c9 --- java/test/common/java_info_tests.bzl | 63 ++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 790bb56a..0887bdaa 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -501,6 +501,68 @@ def _with_exports_test_impl(env, target): "{package}/lib{name}/my_java_lib_exports-hjar.jar", ]) +def _with_transitive_exports_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_c", + srcs = ["java/C.java"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_b", + srcs = ["java/B.java"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_a", + srcs = ["java/A.java"], + exports = [target_name + "/my_java_lib_b"], + deps = [ + target_name + "/my_java_lib_b", + target_name + "/my_java_lib_c", + ], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + dep_exports = [target_name + "/my_java_lib_a"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + ) + + analysis_test( + name = name, + impl = _with_transitive_exports_test_impl, + target = target_name, + ) + +def _with_transitive_exports_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_compilation_args = assert_java_info.compilation_args() + assert_compilation_args.compile_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_a-hjar.jar", + "{package}/lib{name}/my_java_lib_b-hjar.jar", + ]) + assert_compilation_args.full_compile_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_a.jar", + "{package}/lib{name}/my_java_lib_b.jar", + ]) + assert_compilation_args.transitive_runtime_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_a.jar", + "{package}/lib{name}/my_java_lib_b.jar", + "{package}/lib{name}/my_java_lib_c.jar", + ]) + assert_compilation_args.transitive_compile_time_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_a-hjar.jar", + "{package}/lib{name}/my_java_lib_b-hjar.jar", + "{package}/lib{name}/my_java_lib_c-hjar.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -521,5 +583,6 @@ def java_info_tests(name): _with_transitive_deps_source_jars_test, _with_transitive_runtime_deps_source_jars_test, _with_exports_test, + _with_transitive_exports_test, ], ) From d254714c46ef9d310e010cf85fc1f362f41e0d2f Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 10:02:44 -0800 Subject: [PATCH 163/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoExportProvider001` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734596619 Change-Id: I69ea52dc821a2301bc77eb9f03b3a9dd65d248f7 --- java/test/common/java_info_tests.bzl | 79 ++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 0887bdaa..7a83f5b7 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -563,6 +563,84 @@ def _with_transitive_exports_test_impl(env, target): "{package}/lib{name}/my_java_lib_c-hjar.jar", ]) +def _with_transitive_deps_and_exports_test(name): + # Tests case: my_lib + # / \ + # a c + # || || + # b d + # where single line is normal dependency and double is exports dependency. + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_b", + srcs = ["java/B.java"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_a", + srcs = ["java/A.java"], + exports = [target_name + "/my_java_lib_b"], + deps = [target_name + "/my_java_lib_b"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_d", + srcs = ["java/D.java"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_c", + srcs = ["java/C.java"], + exports = [target_name + "/my_java_lib_d"], + deps = [target_name + "/my_java_lib_d"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + dep = [ + target_name + "/my_java_lib_a", + target_name + "/my_java_lib_c", + ], + dep_exports = [target_name + "/my_java_lib_a"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + ) + + analysis_test( + name = name, + impl = _with_transitive_deps_and_exports_test_impl, + target = target_name, + ) + +def _with_transitive_deps_and_exports_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_compilation_args = assert_java_info.compilation_args() + assert_compilation_args.compile_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_a-hjar.jar", + "{package}/lib{name}/my_java_lib_b-hjar.jar", + ]) + assert_compilation_args.full_compile_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_a.jar", + "{package}/lib{name}/my_java_lib_b.jar", + ]) + assert_compilation_args.transitive_runtime_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_a.jar", + "{package}/lib{name}/my_java_lib_b.jar", + "{package}/lib{name}/my_java_lib_c.jar", + "{package}/lib{name}/my_java_lib_d.jar", + ]) + assert_compilation_args.transitive_compile_time_jars().contains_exactly([ + "{package}/{name}/my_starlark_rule_lib.jar", + "{package}/lib{name}/my_java_lib_a-hjar.jar", + "{package}/lib{name}/my_java_lib_b-hjar.jar", + "{package}/lib{name}/my_java_lib_c-hjar.jar", + "{package}/lib{name}/my_java_lib_d-hjar.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -584,5 +662,6 @@ def java_info_tests(name): _with_transitive_runtime_deps_source_jars_test, _with_exports_test, _with_transitive_exports_test, + _with_transitive_deps_and_exports_test, ], ) From 4f287488e2f60ba6d791dfa775b93d2801d617b3 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 10:20:39 -0800 Subject: [PATCH 164/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoPluginsFromExports` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734603913 Change-Id: I09d3b5605d5c601593fec1e0df250801af66a028 --- java/test/common/java_info_tests.bzl | 39 ++++++++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 1 + 2 files changed, 40 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 7a83f5b7..fbe5b930 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -5,6 +5,7 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") +load("//java:java_plugin.bzl", "java_plugin") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") @@ -641,6 +642,43 @@ def _with_transitive_deps_and_exports_test_impl(env, target): "{package}/lib{name}/my_java_lib_d-hjar.jar", ]) +def _with_plugins_via_exports_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/plugin_dep", + srcs = ["ProcessorDep.java"], + ) + util.helper_target( + java_plugin, + name = target_name + "/plugin", + srcs = ["AnnotationProcessor.java"], + processor_class = "com.google.process.stuff", + deps = [target_name + "/plugin_dep"], + ) + util.helper_target( + java_library, + name = target_name + "/export", + exported_plugins = [target_name + "/plugin"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + dep_exports = [target_name + "/export"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + ) + + analysis_test( + name = name, + impl = _with_plugins_via_exports_test_impl, + target = target_name, + ) + +def _with_plugins_via_exports_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.plugins().processor_classes().contains_exactly(["com.google.process.stuff"]) + def java_info_tests(name): test_suite( name = name, @@ -663,5 +701,6 @@ def java_info_tests(name): _with_exports_test, _with_transitive_exports_test, _with_transitive_deps_and_exports_test, + _with_plugins_via_exports_test, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 3e188338..66a22563 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -102,6 +102,7 @@ def _new_java_info_plugins_subject(java_info, meta): ) public = struct( processor_jars = lambda: subjects.depset_file(self.actual.processor_jars, meta = self.meta.derive("processor_jars")), + processor_classes = lambda: subjects.collection(self.actual.processor_classes, meta = self.meta.derive("processor_classes")), ) return public From 4fc371bd1c826dfbd2651de4575a21a92b46d752 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 10:37:47 -0800 Subject: [PATCH 165/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithPlugins` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734610281 Change-Id: If41a8e2793d0a983538a892d4fe2ca0f4aa168c4 --- java/test/common/java_info_tests.bzl | 33 +++++++++++++++++++ .../testutil/rules/custom_java_info_rule.bzl | 4 +++ 2 files changed, 37 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index fbe5b930..224d7634 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -679,6 +679,38 @@ def _with_plugins_via_exports_test_impl(env, target): assert_java_info.plugins().processor_classes().contains_exactly(["com.google.process.stuff"]) +def _with_plugins_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/plugin_dep", + srcs = ["ProcessorDep.java"], + ) + util.helper_target( + java_plugin, + name = target_name + "/plugin", + srcs = ["AnnotationProcessor.java"], + processor_class = "com.google.process.stuff", + deps = [target_name + "/plugin_dep"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name, + dep_exported_plugins = [target_name + "/plugin"], + output_jar = target_name + "/my_starlark_rule_lib.jar", + ) + + analysis_test( + name = name, + impl = _with_plugins_test_impl, + target = target_name, + ) + +def _with_plugins_test_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.plugins().processor_classes().contains_exactly(["com.google.process.stuff"]) + def java_info_tests(name): test_suite( name = name, @@ -702,5 +734,6 @@ def java_info_tests(name): _with_transitive_exports_test, _with_transitive_deps_and_exports_test, _with_plugins_via_exports_test, + _with_plugins_test, ], ) diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index 215c9353..c8138d21 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -3,6 +3,7 @@ load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/common:java_semantics.bzl", "semantics") def _impl(ctx): @@ -10,6 +11,7 @@ def _impl(ctx): dp = [dep[JavaInfo] for dep in ctx.attr.dep] dp_runtime = [dep[JavaInfo] for dep in ctx.attr.dep_runtime] dp_exports = [dep[java_common.provider] for dep in ctx.attr.dep_exports] + dp_exported_plugins = [dep[JavaPluginInfo] for dep in ctx.attr.dep_exported_plugins] source_jar = java_common.pack_sources( ctx.actions, output_source_jar = ctx.actions.declare_file(ctx.outputs.output_jar.basename[:-4] + "-src.jar", sibling = ctx.outputs.output_jar), @@ -34,6 +36,7 @@ def _impl(ctx): deps = dp, runtime_deps = dp_runtime, exports = dp_exports, + exported_plugins = dp_exported_plugins, native_libraries = dp_libs, neverlink = ctx.attr.neverlink, ), @@ -48,6 +51,7 @@ custom_java_info_rule = rule( "dep": attr.label_list(), "dep_runtime": attr.label_list(), "dep_exports": attr.label_list(), + "dep_exported_plugins": attr.label_list(), "cc_dep": attr.label_list(), "use_ijar": attr.bool(default = False), "neverlink": attr.bool(default = False), From d59acd9f0aa0976c52fe0e16ad206cc9d770ea8d Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 11:15:04 -0800 Subject: [PATCH 166/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithOutputJarAndStampJar` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734624934 Change-Id: Ib89f8f0b3990a3bbd4e5582efae4eec577aa0952 --- java/test/common/java_info_tests.bzl | 25 +++++++++++++++++++ .../testutil/rules/custom_java_info_rule.bzl | 12 ++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 224d7634..53f647d4 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -711,6 +711,30 @@ def _with_plugins_test_impl(env, target): assert_java_info.plugins().processor_classes().contains_exactly(["com.google.process.stuff"]) +def _with_stamped_jar_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + stamp_jar = True, + ) + + analysis_test( + name = name, + impl = _with_stamped_jar_test_impl, + target = target_name, + ) + +def _with_stamped_jar_test_impl(env, target): + assert_compilation_args = java_info_subject.from_target(env, target).compilation_args() + + assert_compilation_args.full_compile_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.compile_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib-stamped.jar"]) + assert_compilation_args.transitive_runtime_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_compilation_args.transitive_compile_time_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib-stamped.jar"]) + def java_info_tests(name): test_suite( name = name, @@ -735,5 +759,6 @@ def java_info_tests(name): _with_transitive_deps_and_exports_test, _with_plugins_via_exports_test, _with_plugins_test, + _with_stamped_jar_test, ], ) diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index c8138d21..1cd2b06f 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -7,6 +7,8 @@ load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/common:java_semantics.bzl", "semantics") def _impl(ctx): + if ctx.attr.use_ijar and ctx.attr.stamp_jar: + fail("only one of use_ijar or stamp_jar may be set") ctx.actions.write(ctx.outputs.output_jar, "JavaInfo API Test", is_executable = False) dp = [dep[JavaInfo] for dep in ctx.attr.dep] dp_runtime = [dep[JavaInfo] for dep in ctx.attr.dep_runtime] @@ -26,7 +28,14 @@ def _impl(ctx): ctx.actions, jar = ctx.outputs.output_jar, java_toolchain = semantics.find_java_toolchain(ctx), - ) if ctx.attr.use_ijar else ctx.outputs.output_jar + ) if ctx.attr.use_ijar else ( + java_common.stamp_jar( + ctx.actions, + jar = ctx.outputs.output_jar, + target_label = ctx.label, + java_toolchain = semantics.find_java_toolchain(ctx), + ) if ctx.attr.stamp_jar else ctx.outputs.output_jar + ) return [ JavaInfo( @@ -56,6 +65,7 @@ custom_java_info_rule = rule( "use_ijar": attr.bool(default = False), "neverlink": attr.bool(default = False), "pack_sources": attr.bool(default = False), + "stamp_jar": attr.bool(default = False), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], ) From 3e5f818788de8fb8cec31b80bb4582ab365b277c Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 11:32:56 -0800 Subject: [PATCH 167/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithJdeps_javaRuleOutputJarsProvider` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734631344 Change-Id: I6b2d5254144a38620cf036d37aa3f0620824d1e3 --- java/test/common/java_info_tests.bzl | 24 +++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 1 + .../testutil/rules/custom_java_info_rule.bzl | 2 ++ 3 files changed, 27 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 53f647d4..d29bda4e 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -735,6 +735,29 @@ def _with_stamped_jar_test_impl(env, target): assert_compilation_args.transitive_runtime_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) assert_compilation_args.transitive_compile_time_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib-stamped.jar"]) +def _with_jdeps_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + jdeps = "my_jdeps.pb", + output_jar = target_name + "/my_starlark_rule_lib.jar", + source_jars = ["my_starlark_rule_src.jar"], + ) + + analysis_test( + name = name, + impl = _with_jdeps_test_impl, + target = target_name, + ) + +def _with_jdeps_test_impl(env, target): + assert_outputs = java_info_subject.from_target(env, target).outputs() + + assert_outputs.class_output_jars().contains_exactly(["{package}/{name}/my_starlark_rule_lib.jar"]) + assert_outputs.source_output_jars().contains_exactly(["{package}/my_starlark_rule_src.jar"]) + assert_outputs.jdeps().contains_exactly(["{package}/my_jdeps.pb"]) + def java_info_tests(name): test_suite( name = name, @@ -760,5 +783,6 @@ def java_info_tests(name): _with_plugins_via_exports_test, _with_plugins_test, _with_stamped_jar_test, + _with_jdeps_test, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 66a22563..f111999c 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -43,6 +43,7 @@ def _new_rule_output_info_subject(java_info, meta): jars = lambda: _new_java_outputs_collection_subject(actual.jars, self.meta.derive("jars")), class_output_jars = lambda: subjects.depset_file(depset([o.class_jar for o in actual.jars]), self.meta.derive("class_output_jars")), source_output_jars = lambda: subjects.depset_file(source_jars_depset, self.meta.derive("source_output_jars")), + jdeps = lambda: subjects.depset_file(depset([o.jdeps for o in actual.jars]), self.meta.derive("jdeps")), ) return public diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index 1cd2b06f..547693ae 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -48,6 +48,7 @@ def _impl(ctx): exported_plugins = dp_exported_plugins, native_libraries = dp_libs, neverlink = ctx.attr.neverlink, + jdeps = ctx.file.jdeps, ), ] @@ -62,6 +63,7 @@ custom_java_info_rule = rule( "dep_exports": attr.label_list(), "dep_exported_plugins": attr.label_list(), "cc_dep": attr.label_list(), + "jdeps": attr.label(allow_single_file = True), "use_ijar": attr.bool(default = False), "neverlink": attr.bool(default = False), "pack_sources": attr.bool(default = False), From 19903d58f30bb8f7a722ba7c7c8a9612b3f39fca Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 11:50:53 -0800 Subject: [PATCH 168/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithGeneratedJars_javaRuleOutputJarsProvider` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734637737 Change-Id: I0150bf630b23876b7dc1a2a66cd63ac6c86fdb7e --- java/test/common/java_info_tests.bzl | 23 +++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 2 ++ .../testutil/rules/custom_java_info_rule.bzl | 4 ++++ 3 files changed, 29 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index d29bda4e..e99a436f 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -758,6 +758,28 @@ def _with_jdeps_test_impl(env, target): assert_outputs.source_output_jars().contains_exactly(["{package}/my_starlark_rule_src.jar"]) assert_outputs.jdeps().contains_exactly(["{package}/my_jdeps.pb"]) +def _with_generated_jars_outputs_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + generated_class_jar = "generated_class.jar", + generated_source_jar = "generated_srcs.jar", + output_jar = target_name + "/my_starlark_rule_lib.jar", + ) + + analysis_test( + name = name, + impl = _with_generated_jars_outputs_test_impl, + target = target_name, + ) + +def _with_generated_jars_outputs_test_impl(env, target): + assert_outputs = java_info_subject.from_target(env, target).outputs() + + assert_outputs.generated_class_jars().contains_exactly(["{package}/generated_class.jar"]) + assert_outputs.generated_source_jars().contains_exactly(["{package}/generated_srcs.jar"]) + def java_info_tests(name): test_suite( name = name, @@ -784,5 +806,6 @@ def java_info_tests(name): _with_plugins_test, _with_stamped_jar_test, _with_jdeps_test, + _with_generated_jars_outputs_test, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index f111999c..9ff3631c 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -43,6 +43,8 @@ def _new_rule_output_info_subject(java_info, meta): jars = lambda: _new_java_outputs_collection_subject(actual.jars, self.meta.derive("jars")), class_output_jars = lambda: subjects.depset_file(depset([o.class_jar for o in actual.jars]), self.meta.derive("class_output_jars")), source_output_jars = lambda: subjects.depset_file(source_jars_depset, self.meta.derive("source_output_jars")), + generated_class_jars = lambda: subjects.depset_file(depset([o.generated_class_jar for o in actual.jars]), self.meta.derive("generated_class_jars")), + generated_source_jars = lambda: subjects.depset_file(depset([o.generated_source_jar for o in actual.jars]), self.meta.derive("generated_source_jars")), jdeps = lambda: subjects.depset_file(depset([o.jdeps for o in actual.jars]), self.meta.derive("jdeps")), ) return public diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index 547693ae..cb198ae1 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -49,6 +49,8 @@ def _impl(ctx): native_libraries = dp_libs, neverlink = ctx.attr.neverlink, jdeps = ctx.file.jdeps, + generated_class_jar = ctx.file.generated_class_jar, + generated_source_jar = ctx.file.generated_source_jar, ), ] @@ -64,6 +66,8 @@ custom_java_info_rule = rule( "dep_exported_plugins": attr.label_list(), "cc_dep": attr.label_list(), "jdeps": attr.label(allow_single_file = True), + "generated_class_jar": attr.label(allow_single_file = True), + "generated_source_jar": attr.label(allow_single_file = True), "use_ijar": attr.bool(default = False), "neverlink": attr.bool(default = False), "pack_sources": attr.bool(default = False), From 554ca8c2a973a5f30740c7d38530fdb476f3c6d4 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 12:14:09 -0800 Subject: [PATCH 169/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithGeneratedJars_javaGenJarsProvider` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734646093 Change-Id: Ia004be3dfcf7ccad3ac95cb4c958ed61d61c3a56 --- java/test/common/java_info_tests.bzl | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index e99a436f..1b66f9c8 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -780,6 +780,28 @@ def _with_generated_jars_outputs_test_impl(env, target): assert_outputs.generated_class_jars().contains_exactly(["{package}/generated_class.jar"]) assert_outputs.generated_source_jars().contains_exactly(["{package}/generated_srcs.jar"]) +def _with_generated_jars_annotation_processing_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + generated_class_jar = "generated_class.jar", + generated_source_jar = "generated_srcs.jar", + output_jar = target_name + "/my_starlark_rule_lib.jar", + ) + + analysis_test( + name = name, + impl = _with_generated_jars_annotation_processing_test_impl, + target = target_name, + ) + +def _with_generated_jars_annotation_processing_test_impl(env, target): + assert_annotation_processing = java_info_subject.from_target(env, target).annotation_processing() + + assert_annotation_processing.class_jar().short_path_equals("{package}/generated_class.jar") + assert_annotation_processing.source_jar().short_path_equals("{package}/generated_srcs.jar") + def java_info_tests(name): test_suite( name = name, @@ -807,5 +829,6 @@ def java_info_tests(name): _with_stamped_jar_test, _with_jdeps_test, _with_generated_jars_outputs_test, + _with_generated_jars_annotation_processing_test, ], ) From 73f0bc08a42dbca8a296e7bf4c4532cf224d6e8e Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 12:31:59 -0800 Subject: [PATCH 170/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithCompileJdeps_javaRuleOutputJarsProvider` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734651588 Change-Id: I038eba7eeca6a6d51cd6e77e457e4cf0f6ac3c64 --- java/test/common/java_info_tests.bzl | 21 +++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 1 + .../testutil/rules/custom_java_info_rule.bzl | 2 ++ 3 files changed, 24 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 1b66f9c8..9e4d1a38 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -802,6 +802,26 @@ def _with_generated_jars_annotation_processing_test_impl(env, target): assert_annotation_processing.class_jar().short_path_equals("{package}/generated_class.jar") assert_annotation_processing.source_jar().short_path_equals("{package}/generated_srcs.jar") +def _with_compile_jdeps_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + compile_jdeps = "compile.deps", + output_jar = target_name + "/my_starlark_rule_lib.jar", + ) + + analysis_test( + name = name, + impl = _with_compile_jdeps_test_impl, + target = target_name, + ) + +def _with_compile_jdeps_test_impl(env, target): + java_info_subject.from_target(env, target).outputs().compile_jdeps().contains_exactly([ + "{package}/compile.deps", + ]) + def java_info_tests(name): test_suite( name = name, @@ -830,5 +850,6 @@ def java_info_tests(name): _with_jdeps_test, _with_generated_jars_outputs_test, _with_generated_jars_annotation_processing_test, + _with_compile_jdeps_test, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 9ff3631c..a3db4ba1 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -46,6 +46,7 @@ def _new_rule_output_info_subject(java_info, meta): generated_class_jars = lambda: subjects.depset_file(depset([o.generated_class_jar for o in actual.jars]), self.meta.derive("generated_class_jars")), generated_source_jars = lambda: subjects.depset_file(depset([o.generated_source_jar for o in actual.jars]), self.meta.derive("generated_source_jars")), jdeps = lambda: subjects.depset_file(depset([o.jdeps for o in actual.jars]), self.meta.derive("jdeps")), + compile_jdeps = lambda: subjects.depset_file(depset([o.compile_jdeps for o in actual.jars]), self.meta.derive("compile_jdeps")), ) return public diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index cb198ae1..a74f9c3a 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -49,6 +49,7 @@ def _impl(ctx): native_libraries = dp_libs, neverlink = ctx.attr.neverlink, jdeps = ctx.file.jdeps, + compile_jdeps = ctx.file.compile_jdeps, generated_class_jar = ctx.file.generated_class_jar, generated_source_jar = ctx.file.generated_source_jar, ), @@ -66,6 +67,7 @@ custom_java_info_rule = rule( "dep_exported_plugins": attr.label_list(), "cc_dep": attr.label_list(), "jdeps": attr.label(allow_single_file = True), + "compile_jdeps": attr.label(allow_single_file = True), "generated_class_jar": attr.label(allow_single_file = True), "generated_source_jar": attr.label(allow_single_file = True), "use_ijar": attr.bool(default = False), From bcd1de81e5ed38e3f383924de6e1a30ea627ef66 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 12:49:48 -0800 Subject: [PATCH 171/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithNativeHeaders_javaRuleOutputJarsProvider` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734657671 Change-Id: I4b106fca127a48ced816d57c5c9c5ca25f523677 --- java/test/common/java_info_tests.bzl | 21 +++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 1 + .../testutil/rules/custom_java_info_rule.bzl | 2 ++ 3 files changed, 24 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 9e4d1a38..4c26af5c 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -822,6 +822,26 @@ def _with_compile_jdeps_test_impl(env, target): "{package}/compile.deps", ]) +def _with_native_headers_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + native_headers_jar = "native_headers.jar", + output_jar = target_name + "/my_starlark_rule_lib.jar", + ) + + analysis_test( + name = name, + impl = _with_native_headers_test_impl, + target = target_name, + ) + +def _with_native_headers_test_impl(env, target): + java_info_subject.from_target(env, target).outputs().native_headers().contains_exactly([ + "{package}/native_headers.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -851,5 +871,6 @@ def java_info_tests(name): _with_generated_jars_outputs_test, _with_generated_jars_annotation_processing_test, _with_compile_jdeps_test, + _with_native_headers_test, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index a3db4ba1..aea927b6 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -47,6 +47,7 @@ def _new_rule_output_info_subject(java_info, meta): generated_source_jars = lambda: subjects.depset_file(depset([o.generated_source_jar for o in actual.jars]), self.meta.derive("generated_source_jars")), jdeps = lambda: subjects.depset_file(depset([o.jdeps for o in actual.jars]), self.meta.derive("jdeps")), compile_jdeps = lambda: subjects.depset_file(depset([o.compile_jdeps for o in actual.jars]), self.meta.derive("compile_jdeps")), + native_headers = lambda: subjects.depset_file(depset([o.native_headers_jar for o in actual.jars]), self.meta.derive("native_headers")), ) return public diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index a74f9c3a..ad1bb651 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -52,6 +52,7 @@ def _impl(ctx): compile_jdeps = ctx.file.compile_jdeps, generated_class_jar = ctx.file.generated_class_jar, generated_source_jar = ctx.file.generated_source_jar, + native_headers_jar = ctx.file.native_headers_jar, ), ] @@ -70,6 +71,7 @@ custom_java_info_rule = rule( "compile_jdeps": attr.label(allow_single_file = True), "generated_class_jar": attr.label(allow_single_file = True), "generated_source_jar": attr.label(allow_single_file = True), + "native_headers_jar": attr.label(allow_single_file = True), "use_ijar": attr.bool(default = False), "neverlink": attr.bool(default = False), "pack_sources": attr.bool(default = False), From 7ea6427f1cbde01cb320f882ee67a5288690376f Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 13:06:07 -0800 Subject: [PATCH 172/465] Migrate the `JavaInfoStarlarkApiTest.buildHelperCreateJavaInfoWithManifestProto_javaRuleOutputJarsProvider` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734663045 Change-Id: I334f0d35f814f23c704de2d55dafd2bfa4f1d412 --- java/test/common/java_info_tests.bzl | 21 +++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 1 + .../testutil/rules/custom_java_info_rule.bzl | 2 ++ 3 files changed, 24 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 4c26af5c..2663f528 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -842,6 +842,26 @@ def _with_native_headers_test_impl(env, target): "{package}/native_headers.jar", ]) +def _with_manifest_proto_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + manifest_proto = "manifest.proto", + output_jar = target_name + "/my_starlark_rule_lib.jar", + ) + + analysis_test( + name = name, + impl = _with_manifest_proto_test_impl, + target = target_name, + ) + +def _with_manifest_proto_test_impl(env, target): + java_info_subject.from_target(env, target).outputs().manifest_protos().contains_exactly([ + "{package}/manifest.proto", + ]) + def java_info_tests(name): test_suite( name = name, @@ -872,5 +892,6 @@ def java_info_tests(name): _with_generated_jars_annotation_processing_test, _with_compile_jdeps_test, _with_native_headers_test, + _with_manifest_proto_test, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index aea927b6..9a7ef7ca 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -48,6 +48,7 @@ def _new_rule_output_info_subject(java_info, meta): jdeps = lambda: subjects.depset_file(depset([o.jdeps for o in actual.jars]), self.meta.derive("jdeps")), compile_jdeps = lambda: subjects.depset_file(depset([o.compile_jdeps for o in actual.jars]), self.meta.derive("compile_jdeps")), native_headers = lambda: subjects.depset_file(depset([o.native_headers_jar for o in actual.jars]), self.meta.derive("native_headers")), + manifest_protos = lambda: subjects.depset_file(depset([o.manifest_proto for o in actual.jars]), self.meta.derive("manifest_protos")), ) return public diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index ad1bb651..55086e3e 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -53,6 +53,7 @@ def _impl(ctx): generated_class_jar = ctx.file.generated_class_jar, generated_source_jar = ctx.file.generated_source_jar, native_headers_jar = ctx.file.native_headers_jar, + manifest_proto = ctx.file.manifest_proto, ), ] @@ -72,6 +73,7 @@ custom_java_info_rule = rule( "generated_class_jar": attr.label(allow_single_file = True), "generated_source_jar": attr.label(allow_single_file = True), "native_headers_jar": attr.label(allow_single_file = True), + "manifest_proto": attr.label(allow_single_file = True), "use_ijar": attr.bool(default = False), "neverlink": attr.bool(default = False), "pack_sources": attr.bool(default = False), From 69416a8b68f88eb3debe451ff6ac828db897116b Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 13:23:55 -0800 Subject: [PATCH 173/465] Migrate the `JavaStarlarkApiTest.testExposesJavaCommonProvider` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734668871 Change-Id: I1e70b195712a28b3173f4299e6902b46753f59b8 --- java/test/common/java_common_tests.bzl | 46 ++++++++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 4 +++ 2 files changed, 50 insertions(+) diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index a3580ff9..9555ecd1 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -1,6 +1,7 @@ """Tests for java_common APIs""" load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java/common:java_common.bzl", "java_common") @@ -232,6 +233,50 @@ def _test_compile_override_with_empty_bootclasspath_impl(env, target): "{}/custom-system".format(target.label.package), )]) +def _test_exposes_java_info_as_provider(name): + util.helper_target( + java_library, + name = name + "/dep", + srcs = ["Dep.java"], + ) + analysis_test( + name = name, + impl = _test_exposes_java_info_as_provider_impl, + target = name + "/dep", + ) + +def _test_exposes_java_info_as_provider_impl(env, target): + java_info = target[java_common.provider] + assert_java_info = java_info_subject.new( + java_info, + env.expect.meta.derive( + format_str_kwargs = { + "name": target.label.name, + "package": target.label.package, + }, + ), + ) + + assert_java_info.compilation_args().transitive_runtime_jars().contains_exactly([ + "{package}/lib{name}.jar", + ]) + assert_java_info.compilation_args().transitive_compile_time_jars().contains_exactly([ + "{package}/lib{name}-hjar.jar", + ]) + assert_java_info.compilation_args().full_compile_jars().contains_exactly([ + "{package}/lib{name}.jar", + ]) + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("dep-src.jar"), + ]) + + assert_output = assert_java_info.outputs().jars().singleton() + assert_output.class_jar().short_path_equals("{package}/lib{name}.jar") + assert_output.compile_jar().short_path_equals("{package}/lib{name}-hjar.jar") + assert_output.source_jars().contains_exactly(["{package}/lib{name}-src.jar"]) + assert_output.jdeps().short_path_equals("{package}/lib{name}.jdeps") + assert_output.compile_jdeps().short_path_equals("{package}/lib{name}-hjar.jdeps") + def java_common_tests(name): test_suite( name = name, @@ -244,5 +289,6 @@ def java_common_tests(name): _test_compile_extend_compile_time_jdeps_rule_outputs, _test_compile_bootclasspath, _test_compile_override_with_empty_bootclasspath, + _test_exposes_java_info_as_provider, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 9a7ef7ca..8b74925a 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -60,7 +60,11 @@ def _new_java_outputs_collection_subject(java_outputs, meta): def _new_java_outputs_subject(java_output, meta): public = struct( + class_jar = lambda: subjects.file(java_output.class_jar, meta.derive("class_jar")), compile_jar = lambda: subjects.file(java_output.compile_jar, meta.derive("compile_jar")), + source_jars = lambda: subjects.depset_file(java_output.source_jars if hasattr(java_output.source_jars, "to_list") else depset(java_output.source_jars), meta.derive("source_jars")), + jdeps = lambda: subjects.file(java_output.jdeps, meta.derive("jdeps")), + compile_jdeps = lambda: subjects.file(java_output.compile_jdeps, meta.derive("compile_jdeps")), ) return public From 066193e0a7657a99e37f17f07d57fe095097a6e2 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 7 Mar 2025 13:38:17 -0800 Subject: [PATCH 174/465] Migrate the `JavaStarlarkApiTest.javaPlugin_exposesJavaOutputs` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 734673271 Change-Id: Ie77c81ffe89fc95f7fe187fbd49063450ea06e2a --- java/test/common/BUILD | 3 ++ java/test/common/java_plugin_info_tests.bzl | 43 +++++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 21 ++++++++++ 3 files changed, 67 insertions(+) create mode 100644 java/test/common/java_plugin_info_tests.bzl diff --git a/java/test/common/BUILD b/java/test/common/BUILD index c9cd0668..5305a01e 100644 --- a/java/test/common/BUILD +++ b/java/test/common/BUILD @@ -1,6 +1,9 @@ load(":java_common_tests.bzl", "java_common_tests") load(":java_info_tests.bzl", "java_info_tests") +load(":java_plugin_info_tests.bzl", "java_plugin_info_tests") java_common_tests(name = "java_common_tests") java_info_tests(name = "java_info_tests") + +java_plugin_info_tests(name = "java_plugin_info_tests") diff --git a/java/test/common/java_plugin_info_tests.bzl b/java/test/common/java_plugin_info_tests.bzl new file mode 100644 index 00000000..381a6d48 --- /dev/null +++ b/java/test/common/java_plugin_info_tests.bzl @@ -0,0 +1,43 @@ +"""Tests for the JavaPluginInfo provider""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_library.bzl", "java_library") +load("//java:java_plugin.bzl", "java_plugin") +load("//java/test/testutil:java_info_subject.bzl", "java_plugin_info_subject") + +def _test_exposes_java_outputs(name): + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["Lib.java"], + ) + util.helper_target( + java_plugin, + name = name + "/dep", + srcs = ["Dep.java"], + deps = [name + "/lib"], + ) + + analysis_test( + name = name, + impl = _test_exposes_java_outputs_impl, + target = name + "/dep", + ) + +def _test_exposes_java_outputs_impl(env, target): + assert_output = java_plugin_info_subject.from_target(env, target).java_outputs().singleton() + + assert_output.class_jar().short_path_equals("{package}/lib{name}.jar") + assert_output.compile_jar().short_path_equals("{package}/lib{name}-hjar.jar") + assert_output.source_jars().contains_exactly(["{package}/lib{name}-src.jar"]) + assert_output.jdeps().short_path_equals("{package}/lib{name}.jdeps") + assert_output.compile_jdeps().short_path_equals("{package}/lib{name}-hjar.jdeps") + +def java_plugin_info_tests(name): + test_suite( + name = name, + tests = [ + _test_exposes_java_outputs, + ], + ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 8b74925a..de2d2180 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -3,6 +3,7 @@ load("@rules_testing//lib:truth.bzl", "subjects", "truth") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load(":cc_info_subject.bzl", "cc_info_subject") def _new_java_info_subject(java_info, meta): @@ -136,6 +137,21 @@ def _new_annotation_processing_subject(java_info, meta): ) return public +def _new_java_plugin_info_subject(java_plugin_info, meta): + self = struct(actual = java_plugin_info, meta = meta.derive("JavaPluginInfo")) + public = struct( + java_outputs = lambda: _new_java_outputs_collection_subject(self.actual.java_outputs, meta.derive("java_outputs")), + ) + return public + +def _java_plugin_info_subject_from_target(env, target): + return _new_java_plugin_info_subject(target[JavaPluginInfo], meta = truth.expect(env).meta.derive( + format_str_kwargs = { + "name": target.label.name, + "package": target.label.package, + }, + )) + def _get_singleton(seq): if len(seq) != 1: fail("expected singleton, got:", seq) @@ -145,3 +161,8 @@ java_info_subject = struct( new = _new_java_info_subject, from_target = _java_info_subject_from_target, ) + +java_plugin_info_subject = struct( + new = _new_java_plugin_info_subject, + from_target = _java_plugin_info_subject_from_target, +) From d649cd8dc67d26904f8d884e9b0f4abd70fedfc1 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 10 Mar 2025 02:04:55 -0700 Subject: [PATCH 175/465] Migrate the `JavaStarlarkApiTest.testJavaCommonCompileExposesOutputJarProvider` test to Starlark The test is removed from Bazel and added in rules_java PiperOrigin-RevId: 735290781 Change-Id: Ifd457722d746da45bbb503d100af48a0d2af0c0e --- java/test/common/java_common_tests.bzl | 24 ++++++++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 1 + 2 files changed, 25 insertions(+) diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 9555ecd1..1fb9b441 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -277,6 +277,29 @@ def _test_exposes_java_info_as_provider_impl(env, target): assert_output.jdeps().short_path_equals("{package}/lib{name}.jdeps") assert_output.compile_jdeps().short_path_equals("{package}/lib{name}-hjar.jdeps") +def _test_compile_exposes_outputs_provider(name): + util.helper_target( + custom_library, + name = name + "/dep", + srcs = ["Main.java"], + ) + + analysis_test( + name = name, + impl = _test_compile_exposes_outputs_provider_impl, + target = name + "/dep", + ) + +def _test_compile_exposes_outputs_provider_impl(env, target): + assert_output = java_info_subject.from_target(env, target).outputs().jars().singleton() + + assert_output.class_jar().short_path_equals("{package}/lib{name}.jar") + assert_output.compile_jar().short_path_equals("{package}/lib{name}-hjar.jar") + assert_output.source_jars().contains_exactly(["{package}/lib{name}-src.jar"]) + assert_output.jdeps().short_path_equals("{package}/lib{name}.jdeps") + assert_output.native_headers_jar().short_path_equals("{package}/lib{name}-native-header.jar") + assert_output.compile_jdeps().short_path_equals("{package}/lib{name}-hjar.jdeps") + def java_common_tests(name): test_suite( name = name, @@ -290,5 +313,6 @@ def java_common_tests(name): _test_compile_bootclasspath, _test_compile_override_with_empty_bootclasspath, _test_exposes_java_info_as_provider, + _test_compile_exposes_outputs_provider, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index de2d2180..246b56e7 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -66,6 +66,7 @@ def _new_java_outputs_subject(java_output, meta): source_jars = lambda: subjects.depset_file(java_output.source_jars if hasattr(java_output.source_jars, "to_list") else depset(java_output.source_jars), meta.derive("source_jars")), jdeps = lambda: subjects.file(java_output.jdeps, meta.derive("jdeps")), compile_jdeps = lambda: subjects.file(java_output.compile_jdeps, meta.derive("compile_jdeps")), + native_headers_jar = lambda: subjects.file(java_output.native_headers_jar, meta.derive("native_headers_jar")), ) return public From aef7514ad80ae6b7c366b7b72dfde40f366498cb Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 10 Mar 2025 14:17:16 -0700 Subject: [PATCH 176/465] Add java_library outputs to validation outputs This ensures that compilation actions are performed for libraries that are only used as neverlink dependencies, to ensure that any compilation errors are reported. The minimize the number of additional validation actions, the validation is done for targets that set neverlink, and their transitive runtime dependencies, so anything that is used as a transitive neverlink dep is covered. PiperOrigin-RevId: 735509081 Change-Id: I76b30e68c8b37eca165861e893ec595cb3040d6c --- java/common/rules/impl/basic_java_library_impl.bzl | 10 +++++++++- java/common/rules/impl/java_binary_impl.bzl | 5 ++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/java/common/rules/impl/basic_java_library_impl.bzl b/java/common/rules/impl/basic_java_library_impl.bzl index a43b4517..cf7c5c19 100644 --- a/java/common/rules/impl/basic_java_library_impl.bzl +++ b/java/common/rules/impl/basic_java_library_impl.bzl @@ -156,6 +156,8 @@ def basic_java_library( _direct_source_jars = java_info.source_jars, ) + validation_outputs = [] + if ctx.fragments.java.run_android_lint: generated_source_jars = [ output.generated_source_jar @@ -168,7 +170,13 @@ def basic_java_library( compilation_info, ) if lint_output: - output_groups["_validation"] = [lint_output] + validation_outputs.append(depset([lint_output])) + + if neverlink: + validation_outputs.append(java_info.compilation_info.runtime_classpath) + + if validation_outputs: + output_groups["_validation"] = depset(transitive = validation_outputs) target["InstrumentedFilesInfo"] = coverage_common.instrumented_files_info( ctx, diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl index 93114300..a5a14d04 100644 --- a/java/common/rules/impl/java_binary_impl.bzl +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -251,7 +251,10 @@ def basic_java_binary( ]) if validation_outputs: - output_groups["_validation"] = output_groups.get("_validation", []) + validation_outputs + output_groups["_validation"] = depset( + validation_outputs, + transitive = [output_groups.get("_validation", depset([]))], + ) _filter_validation_output_group(ctx, output_groups) From ca202de9f7537413de9901e63debeadf7d5cb2bf Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 11 Mar 2025 06:49:19 -0700 Subject: [PATCH 177/465] Improve rules_java CI config - Removes duplication by using the matrix configuration - Separates out linux-only tests, so we can run analysis tests on all platforms - Uses https://github.com/bazelbuild/continuous-integration/pull/2188 for task names PiperOrigin-RevId: 735739491 Change-Id: I0b0fbe296bed6a24a693a41e319a439f9e0ac358 --- .bazelci/presubmit.yml | 169 ++++++++++++----------------------------- 1 file changed, 49 insertions(+), 120 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 2bf1a1fc..de1be01f 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -22,6 +22,8 @@ build_targets_integration: &build_targets_integration test_targets: &test_targets - "//test/..." - "//java/test/..." + # linux-only tests + - "-//test:check_remote_jdk_configs_test" # TODO: re-enable docs after moving them out of https://bazel.build/reference/be/java - "-//test:docs_up_to_date_test" @@ -38,146 +40,73 @@ flags_workspace_integration: &flags_workspace_integration buildifier: latest +matrix: + all_platforms: ["ubuntu2004", "macos", "windows"] + integration_platforms: ["ubuntu2004", "macos"] # TODO: add windows batch setup script + bazel: ["7.4.0", "8.1.0", "last_green"] # Bazel 6 tested separately, needs different flags + modern_bazel: ["8.1.0", "last_green"] # Fully supported Bazel versions + tasks: # Bazel 7.x - ubuntu2004_bazel7: - name: "Bazel 7.x" - bazel: "7.4.0" - platform: ubuntu2004 + build_and_test_bazel7: + name: "Bazel 7.5.0" + bazel: "7.5.0" + platform: ${{ all_platforms }} build_targets: *build_targets test_targets: *test_targets test_flags: - "--test_tag_filters=-min_bazel_8" - ubuntu2004_integration_bazel7: - name: "Bazel 7.x Integration" - bazel: "7.4.0" - platform: ubuntu2004 - working_directory: "test/repo" - shell_commands: - - sh setup.sh - build_targets: *build_targets_integration - test_targets: *test_target_integration - ubuntu2004_integration_workspace_bazel7: - name: "Bazel 7.x Integration (WORKSPACE)" - bazel: "7.4.0" - platform: ubuntu2004 - working_directory: "test/repo" - shell_commands: - - sh setup.sh - build_targets: *build_targets_integration - build_flags: *flags_workspace_integration - test_targets: *test_target_integration - test_flags: *flags_workspace_integration - macos_bazel7: - name: "Bazel 7.x" - bazel: "7.4.0" - platform: macos - build_targets: *build_targets - windows_bazel7: - name: "Bazel 7.x" - bazel: "7.4.0" - platform: windows - build_targets: *build_targets -# Bazel 8.x - ubuntu2004_bazel8: - name: "Bazel 8.x" - bazel: "8.1.0" - platform: ubuntu2004 +# Bazel 8+ + build_and_test: + name: "Bazel {modern_bazel}" + bazel: ${{ modern_bazel }} + platform: ${{ all_platforms }} build_targets: *build_targets test_targets: *test_targets - ubuntu2004_integration_bazel8: - name: "Bazel 8.x Integration" - bazel: "8.1.0" - platform: ubuntu2004 - working_directory: "test/repo" - shell_commands: - - sh setup.sh - build_targets: *build_targets_integration - test_targets: *test_target_integration - ubuntu2004_integration_workspace_bazel8: - name: "Bazel 8.x Integration (WORKSPACE)" - bazel: "8.1.0" +# Bazel 6.x + build_and_test_bazel6: + name: "Bazel 6.5.0" + bazel: 6.5.0 + platform: ${{ all_platforms }} + build_targets: *build_targets_bazel6 + test_targets: *test_targets_bazel6 + test_flags: + - "--test_tag_filters=-min_bazel_7,-min_bazel_8" + ubuntu2004_integration_bazel6: + name: "Integration w/ Bazel 6.5.0" + bazel: 6.5.0 platform: ubuntu2004 working_directory: "test/repo" shell_commands: - - sh setup.sh + - sh setup.sh build_targets: *build_targets_integration - build_flags: *flags_workspace_integration test_targets: *test_target_integration - test_flags: *flags_workspace_integration - macos_bazel8: - name: "Bazel 8.x" - bazel: "8.1.0" - platform: macos - build_targets: *build_targets - windows_bazel8: - name: "Bazel 8.x" - bazel: "8.1.0" - platform: windows - build_targets: *build_targets -# Bazel@HEAD - ubuntu2004_head: - name: "Bazel@HEAD" - bazel: last_green - platform: ubuntu2004 - build_targets: *build_targets - test_targets: *test_targets - ubuntu2004_integration_head: - name: "Bazel@HEAD Integration" - bazel: last_green - platform: ubuntu2004 + +# Integration tests + integration_build_and_test: + name: "Integration w/ Bazel {bazel}" + bazel: ${{ bazel }} + platform: ${{ integration_platforms }} working_directory: "test/repo" shell_commands: - - sh setup.sh + - sh setup.sh build_targets: *build_targets_integration test_targets: *test_target_integration - ubuntu2004_integration_head_workspace: - name: "Bazel@HEAD Integration (WORKSPACE)" - bazel: "last_green" - platform: ubuntu2004 + integration_build_and_test_workspace: + name: "Integration (WORKSPACE) w/ Bazel {bazel}" + bazel: ${{ bazel }} + platform: ${{ integration_platforms }} working_directory: "test/repo" shell_commands: - - sh setup.sh + - sh setup.sh build_targets: *build_targets_integration build_flags: *flags_workspace_integration test_targets: *test_target_integration test_flags: *flags_workspace_integration - macos_head: - name: "Bazel@HEAD" - bazel: last_green - platform: macos - build_targets: *build_targets - windows_head: - name: "Bazel@HEAD" - bazel: last_green - platform: windows - build_targets: *build_targets - -# Bazel 6.x - ubuntu2004_bazel6: - name: "Bazel 6.x" - bazel: 6.4.0 - platform: ubuntu2004 - build_targets: *build_targets_bazel6 - test_targets: *test_targets_bazel6 - test_flags: - - "--test_tag_filters=-min_bazel_7,-min_bazel_8" - ubuntu2004_integration_bazel6: - name: "Bazel 6.x Integration" - bazel: 6.4.0 - platform: ubuntu2004 - working_directory: "test/repo" - shell_commands: - - sh setup.sh - build_targets: *build_targets_integration - test_targets: *test_target_integration - macos_bazel6: - name: "Bazel 6.x" - bazel: 6.4.0 - platform: macos - build_targets: *build_targets_bazel6 - windows_bazel6: - name: "Bazel 6.x" - bazel: 6.4.0 - platform: windows - build_targets: *build_targets_bazel6 +# Linux-only tests + linux_only_tests: + name: "Extra tests w/ Bazel {bazel}" + bazel: ${{ bazel }} + platform: "ubuntu2004" + test_targets: + - "//test:check_remote_jdk_configs_test" From 16e6f4ddab68b4e8ebffef63b94871d9664d9501 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 11 Mar 2025 11:03:56 -0700 Subject: [PATCH 178/465] Test with Bazel 8 for rules_java BCR releases PiperOrigin-RevId: 735818870 Change-Id: I23cd3c94af8e0e6fcbf5500f128a06df6ba53ca1 --- .bcr/presubmit.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.bcr/presubmit.yml b/.bcr/presubmit.yml index a9943343..c81cf084 100644 --- a/.bcr/presubmit.yml +++ b/.bcr/presubmit.yml @@ -7,9 +7,10 @@ matrix: - windows bazel: - 7.x + - 8.x tasks: verify_build_targets: - name: "Verify build targets" + name: "Verify build targets w/ Bazel {bazel}" platform: ${{ platform }} bazel: ${{ bazel }} build_targets: From c100754fb8d3b28b782a26cbcf94c540f7ad713d Mon Sep 17 00:00:00 2001 From: "Ian (Hee) Cha" Date: Thu, 13 Mar 2025 01:09:33 -0700 Subject: [PATCH 179/465] Update rules_java to 8.11.0 and java_tools to 13.18 (#280) Closes #280 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/280 from bazelbuild:java_v13.18 dc7f92e89e658b636c8b2488b14767975c0f2336 PiperOrigin-RevId: 736413036 Change-Id: I9d1b2141659ce02baff6ca476e6eaff7f62d592e --- MODULE.bazel | 2 +- java/repositories.bzl | 32 ++++++++++++++++---------------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index adcf1c0c..f60025ad 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.10.0", + version = "8.11.0", bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) diff --git a/java/repositories.bzl b/java/repositories.bzl index d755c2ba..9ebb660d 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.17", + "version": "v13.18", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.17/java_tools_linux-v13.17.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.17/java_tools_linux-v13.17.zip", - "sha": "acae69407bbc7c240eb2e5fae7af787d22c98e4f7446be535bfa92bacaf42bde", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.18/java_tools_linux-v13.18.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.18/java_tools_linux-v13.18.zip", + "sha": "0da77fca085dd477a057581f26fe677d88e4b9f542c517d813e50553829f66a0", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.17/java_tools_windows-v13.17.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.17/java_tools_windows-v13.17.zip", - "sha": "de2c5b9da64c6a759f026d0afcab6d44af1b5aafcf9ade07506da02b3255e014", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.18/java_tools_windows-v13.18.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.18/java_tools_windows-v13.18.zip", + "sha": "e07c1604a492a5f316e8d8142446d2b297066d243d4ed3d54324aa89122ca862", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.17/java_tools_darwin_x86_64-v13.17.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.17/java_tools_darwin_x86_64-v13.17.zip", - "sha": "f9aa10b78a8b1d15f1036f44307171bf05dde4e9906bd74e282ddcba0687cee5", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.18/java_tools_darwin_x86_64-v13.18.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.18/java_tools_darwin_x86_64-v13.18.zip", + "sha": "ecc155c338ab106324dbd036364478b0fd85d4f12d11a95268b6c436b4bb41a2", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.17/java_tools_darwin_arm64-v13.17.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.17/java_tools_darwin_arm64-v13.17.zip", - "sha": "4bb3f1950a3db214f788035efce711c5b35a7fd884dffa66b1fb045d33889b14", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.18/java_tools_darwin_arm64-v13.18.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.18/java_tools_darwin_arm64-v13.18.zip", + "sha": "d11cdccc9e906f68137b882d75d485122f3c6a9b50374b6bb2e526384114f897", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.17/java_tools-v13.17.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.17/java_tools-v13.17.zip", - "sha": "a5e1c740690399ec0d5dacff59a2aa0cb13fbb904efa5cdf6e7fda4e030515ef", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.18/java_tools-v13.18.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.18/java_tools-v13.18.zip", + "sha": "1945286e31ca21184b672290caa83cc3470dcdbd00ce0af34f02d24398974ebf", }, }, } From ab0ab2a12e887be719ffe3c3707a645099906659 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 18 Mar 2025 09:02:35 -0700 Subject: [PATCH 180/465] Migrate the `JavaStarlarkApiTest.javaCommonCompile_setsRuntimeDeps` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738026498 Change-Id: Ibe372f56771716eb48465ec0e1e2f9a56dbab57e --- java/test/common/java_common_tests.bzl | 50 +++++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 15 +++++++ java/test/testutil/rules/custom_library.bzl | 7 +++ 3 files changed, 72 insertions(+) diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 1fb9b441..e60ea0a2 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -300,6 +300,55 @@ def _test_compile_exposes_outputs_provider_impl(env, target): assert_output.native_headers_jar().short_path_equals("{package}/lib{name}-native-header.jar") assert_output.compile_jdeps().short_path_equals("{package}/lib{name}-hjar.jdeps") +def _test_compile_sets_runtime_deps(name): + target_name = name + "/custom" + util.helper_target( + custom_library, + name = target_name, + srcs = ["Main.java"], + runtime_deps = [target_name + "/runtime"], + deps = [target_name + "/dep"], + ) + util.helper_target( + java_library, + name = target_name + "/dep", + srcs = ["Dep.java"], + ) + util.helper_target( + java_library, + name = target_name + "/runtime", + srcs = ["Runtime.java"], + ) + + analysis_test( + name = name, + impl = _test_compile_sets_runtime_deps_impl, + target = target_name, + ) + +def _test_compile_sets_runtime_deps_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.compilation_args().transitive_runtime_jars_list().contains_exactly_predicates([ + matching.file_basename_equals("custom.jar"), + matching.file_basename_equals("dep.jar"), + matching.file_basename_equals("runtime.jar"), + ]).in_order() + assert_java_info.runtime_output_jars().contains_exactly(["{package}/lib{name}.jar"]) + assert_java_info.compilation_info().compilation_classpath().contains_exactly([ + "{package}/lib{name}/dep-hjar.jar", + ]) + assert_java_info.compilation_info().runtime_classpath_list().contains_exactly_predicates([ + matching.file_basename_equals("custom.jar"), + matching.file_basename_equals("runtime.jar"), + matching.file_basename_equals("dep.jar"), + ]).in_order() + assert_java_info.transitive_source_jars_list().contains_exactly_predicates([ + matching.file_basename_equals("runtime-src.jar"), + matching.file_basename_equals("dep-src.jar"), + matching.file_basename_equals("custom-src.jar"), + ]).in_order() + def java_common_tests(name): test_suite( name = name, @@ -314,5 +363,6 @@ def java_common_tests(name): _test_compile_override_with_empty_bootclasspath, _test_exposes_java_info_as_provider, _test_compile_exposes_outputs_provider, + _test_compile_sets_runtime_deps, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 246b56e7..532b05fa 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -10,6 +10,7 @@ def _new_java_info_subject(java_info, meta): self = struct(actual = java_info, meta = meta.derive("JavaInfo")) public = struct( compilation_args = lambda: _new_java_compilation_args_subject(self.actual, self.meta), + compilation_info = lambda: _new_java_compilation_info_subject(self.actual, self.meta), plugins = lambda: _new_java_info_plugins_subject(self.actual, self.meta), is_binary = lambda: subjects.bool(getattr(java_info, "_is_binary", False), self.meta.derive("_is_binary")), has_attr = lambda a: subjects.bool(getattr(java_info, a, None) != None, meta = self.meta.derive("{} != None".format(a))).equals(True), @@ -20,6 +21,8 @@ def _new_java_info_subject(java_info, meta): outputs = lambda: _new_rule_output_info_subject(self.actual, self.meta), source_jars = lambda: subjects.collection(java_info.source_jars, self.meta.derive("source_jars")), transitive_source_jars = lambda: subjects.depset_file(java_info.transitive_source_jars, self.meta.derive("transitive_source_jars")), + transitive_source_jars_list = lambda: subjects.collection(java_info.transitive_source_jars.to_list(), self.meta.derive("transitive_source_jars.to_list()")), + runtime_output_jars = lambda: subjects.depset_file(java_info.runtime_output_jars, self.meta.derive("runtime_output_jars")), ) return public @@ -31,6 +34,17 @@ def _java_info_subject_from_target(env, target): }, )) +def _new_java_compilation_info_subject(java_info, meta): + self = struct( + actual = java_info.compilation_info, + meta = meta.derive("compilation_info"), + ) + public = struct( + compilation_classpath = lambda: subjects.depset_file(self.actual.compilation_classpath, self.meta.derive("compilation_classpath")), + runtime_classpath_list = lambda: subjects.collection(self.actual.runtime_classpath.to_list(), self.meta.derive("runtime_classpath.to_list()")), + ) + return public + def _new_rule_output_info_subject(java_info, meta): actual = java_info.outputs self = struct( @@ -91,6 +105,7 @@ def _new_java_compilation_args_subject(java_info, meta): full_compile_jars = lambda: subjects.depset_file(actual.full_compile_jars, self.meta.derive("full_compile_jars")), transitive_runtime_jars = lambda: subjects.depset_file(actual.transitive_runtime_jars, self.meta.derive("transitive_runtime_jars")), transitive_compile_time_jars = lambda: subjects.depset_file(actual.transitive_compile_time_jars, self.meta.derive("transitive_compile_time_jars")), + transitive_runtime_jars_list = lambda: subjects.collection(actual.transitive_runtime_jars.to_list(), self.meta.derive("transitive_runtime_jars.to_list()")), self = self, actual = actual, ) diff --git a/java/test/testutil/rules/custom_library.bzl b/java/test/testutil/rules/custom_library.bzl index 58307b60..ff30c254 100644 --- a/java/test/testutil/rules/custom_library.bzl +++ b/java/test/testutil/rules/custom_library.bzl @@ -1,14 +1,19 @@ """Helper rule for testing compilation with default parameter values""" load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") def _custom_library_impl(ctx): output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") + deps = [dep[JavaInfo] for dep in ctx.attr.deps] + runtime_deps = [dep[JavaInfo] for dep in ctx.attr.runtime_deps] compilation_provider = java_common.compile( ctx, source_files = ctx.files.srcs, output = output_jar, + deps = deps, + runtime_deps = runtime_deps, java_toolchain = semantics.find_java_toolchain(ctx), ) return [DefaultInfo(files = depset([output_jar])), compilation_provider] @@ -17,6 +22,8 @@ custom_library = rule( _custom_library_impl, attrs = { "srcs": attr.label_list(allow_files = [".java"]), + "deps": attr.label_list(), + "runtime_deps": attr.label_list(), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], fragments = ["java"], From 0589e6a7d2fe6918d61f033b5b4f7bc58751d317 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 01:40:57 -0700 Subject: [PATCH 181/465] Migrate the `JavaStarlarkApiTest.testJavaCommonCompileExposesAnnotationProcessingInfo` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738300505 Change-Id: I6ec757c10f847208ae134bdddf09bde6a4537de8 --- java/test/common/java_common_tests.bzl | 75 +++++++++++++++++++++ java/test/testutil/rules/custom_library.bzl | 5 ++ 2 files changed, 80 insertions(+) diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index e60ea0a2..140e4efa 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -4,6 +4,7 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") +load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") @@ -349,6 +350,79 @@ def _test_compile_sets_runtime_deps_impl(env, target): matching.file_basename_equals("custom-src.jar"), ]).in_order() +def _test_compile_exposes_annotation_processing_info(name): + _test_annotation_processing_info_is_starlark_accessible(name, custom_library) + +def _test_annotation_processing_info_is_starlark_accessible(name, to_be_processed_rule_class): + target_name = name + "/to_be_processed" + util.helper_target( + to_be_processed_rule_class, + name = target_name, + plugins = [target_name + "/plugin"], + srcs = ["ToBeProcessed.java"], + deps = [target_name + "/dep"], + exports = [target_name + "/export"], + ) + util.helper_target( + java_library, + name = target_name + "/plugin_dep", + srcs = ["Processordep.java"], + ) + util.helper_target( + java_plugin, + name = target_name + "/plugin", + srcs = ["AnnotationProcessor.java"], + processor_class = "com.google.process.stuff", + deps = [target_name + "/plugin_dep"], + ) + util.helper_target( + java_library, + name = target_name + "/dep", + srcs = ["Dep.java"], + plugins = [target_name + "/plugin"], + ) + util.helper_target( + java_library, + name = target_name + "/export", + srcs = ["Export.java"], + plugins = [target_name + "/plugin"], + ) + + analysis_test( + name = name, + impl = _test_annotation_processing_info_is_starlark_accessible_impl, + target = target_name, + ) + +def _test_annotation_processing_info_is_starlark_accessible_impl(env, target): + depj = target[JavaInfo] + result = struct( + enabled = depj.annotation_processing.enabled, + class_jar = depj.outputs.jars[0].generated_class_jar, + source_jar = depj.outputs.jars[0].generated_source_jar, + old_class_jar = depj.annotation_processing.class_jar, + old_source_jar = depj.annotation_processing.source_jar, + processor_classpath = depj.annotation_processing.processor_classpath, + processor_classnames = depj.annotation_processing.processor_classnames, + transitive_class_jars = depj.annotation_processing.transitive_class_jars, + transitive_source_jars = depj.annotation_processing.transitive_source_jars, + ) + + env.expect.that_bool(result.enabled).equals(True) + env.expect.that_file(result.class_jar).equals(result.old_class_jar) + env.expect.that_file(result.source_jar).equals(result.old_source_jar) + env.expect.that_collection(result.processor_classnames).contains_exactly([ + "com.google.process.stuff", + ]) + env.expect.that_collection(result.processor_classpath.to_list()).contains_exactly_predicates([ + matching.file_basename_equals("plugin.jar"), + matching.file_basename_equals("plugin_dep.jar"), + ]) + env.expect.that_collection(result.transitive_class_jars.to_list()).has_size(3) + env.expect.that_collection(result.transitive_class_jars.to_list()).contains(result.class_jar) + env.expect.that_collection(result.transitive_source_jars.to_list()).has_size(3) + env.expect.that_collection(result.transitive_source_jars.to_list()).contains(result.source_jar) + def java_common_tests(name): test_suite( name = name, @@ -364,5 +438,6 @@ def java_common_tests(name): _test_exposes_java_info_as_provider, _test_compile_exposes_outputs_provider, _test_compile_sets_runtime_deps, + _test_compile_exposes_annotation_processing_info, ], ) diff --git a/java/test/testutil/rules/custom_library.bzl b/java/test/testutil/rules/custom_library.bzl index ff30c254..01bfb871 100644 --- a/java/test/testutil/rules/custom_library.bzl +++ b/java/test/testutil/rules/custom_library.bzl @@ -2,6 +2,7 @@ load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/common:java_semantics.bzl", "semantics") def _custom_library_impl(ctx): @@ -14,6 +15,8 @@ def _custom_library_impl(ctx): output = output_jar, deps = deps, runtime_deps = runtime_deps, + exports = [e[JavaInfo] for e in ctx.attr.exports], + plugins = [p[JavaPluginInfo] for p in ctx.attr.plugins], java_toolchain = semantics.find_java_toolchain(ctx), ) return [DefaultInfo(files = depset([output_jar])), compilation_provider] @@ -24,6 +27,8 @@ custom_library = rule( "srcs": attr.label_list(allow_files = [".java"]), "deps": attr.label_list(), "runtime_deps": attr.label_list(), + "exports": attr.label_list(), + "plugins": attr.label_list(), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], fragments = ["java"], From 60b594b54398ad88f08813502a4e42c141a62c4d Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 02:04:37 -0700 Subject: [PATCH 182/465] Migrate the `JavaStarlarkApiTest.testJavaPlugin` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738306567 Change-Id: I794c529f0af139a271a7ec73fd8db2a9b880a515 --- java/test/common/java_common_tests.bzl | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 140e4efa..b8c16762 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -353,6 +353,9 @@ def _test_compile_sets_runtime_deps_impl(env, target): def _test_compile_exposes_annotation_processing_info(name): _test_annotation_processing_info_is_starlark_accessible(name, custom_library) +def _test_java_library_exposes_annotation_processing_info(name): + _test_annotation_processing_info_is_starlark_accessible(name, java_library) + def _test_annotation_processing_info_is_starlark_accessible(name, to_be_processed_rule_class): target_name = name + "/to_be_processed" util.helper_target( @@ -439,5 +442,6 @@ def java_common_tests(name): _test_compile_exposes_outputs_provider, _test_compile_sets_runtime_deps, _test_compile_exposes_annotation_processing_info, + _test_java_library_exposes_annotation_processing_info, ], ) From ee1039d38cf03f4ac57e5b2d476ec20029d5de5e Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 02:30:56 -0700 Subject: [PATCH 183/465] Migrate the `JavaStarlarkApiTest.javaCommonCompile_requiresJavaPluginInfo` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738313270 Change-Id: I966643c3905a9f5f02fc717d932a46bf08b11df7 --- java/test/common/java_common_tests.bzl | 28 +++++++++++++++++++ ...custom_library_with_wrong_plugins_type.bzl | 24 ++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 java/test/testutil/rules/custom_library_with_wrong_plugins_type.bzl diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index b8c16762..2b594b0f 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -14,6 +14,7 @@ load("//java/test/testutil:rules/custom_library_extended_compile_jdeps.bzl", "Co load("//java/test/testutil:rules/custom_library_with_bootclasspath.bzl", "custom_bootclasspath", "custom_library_with_bootclasspath") load("//java/test/testutil:rules/custom_library_with_exports.bzl", "custom_library_with_exports") load("//java/test/testutil:rules/custom_library_with_sourcepaths.bzl", "custom_library_with_sourcepaths") +load("//java/test/testutil:rules/custom_library_with_wrong_plugins_type.bzl", "custom_library_with_wrong_plugins_type") def _test_compile_default_values(name): util.helper_target(custom_library, name = name + "/custom", srcs = ["Main.java"]) @@ -426,6 +427,32 @@ def _test_annotation_processing_info_is_starlark_accessible_impl(env, target): env.expect.that_collection(result.transitive_source_jars.to_list()).has_size(3) env.expect.that_collection(result.transitive_source_jars.to_list()).contains(result.source_jar) +def _test_compile_requires_java_plugin_info(name): + target_name = name + "/to_be_processed" + util.helper_target( + java_library, + name = target_name + "/dep", + srcs = ["ProcessorDep.java"], + ) + util.helper_target( + custom_library_with_wrong_plugins_type, + name = target_name, + srcs = ["ToBeProcessed.java"], + deps = [target_name + "/dep"], + ) + + analysis_test( + name = name, + impl = _test_compile_requires_java_plugin_info_impl, + target = target_name, + expect_failure = True, + ) + +def _test_compile_requires_java_plugin_info_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("at index 0 of plugins, got element of type JavaInfo, want JavaPluginInfo"), + ) + def java_common_tests(name): test_suite( name = name, @@ -443,5 +470,6 @@ def java_common_tests(name): _test_compile_sets_runtime_deps, _test_compile_exposes_annotation_processing_info, _test_java_library_exposes_annotation_processing_info, + _test_compile_requires_java_plugin_info, ], ) diff --git a/java/test/testutil/rules/custom_library_with_wrong_plugins_type.bzl b/java/test/testutil/rules/custom_library_with_wrong_plugins_type.bzl new file mode 100644 index 00000000..12535307 --- /dev/null +++ b/java/test/testutil/rules/custom_library_with_wrong_plugins_type.bzl @@ -0,0 +1,24 @@ +"""Custom rule to test java_common.compile(plugins = ...) expects JavaPluginInfo""" + +load("//java:defs.bzl", "JavaInfo", "java_common") +load("//java/common:java_semantics.bzl", "semantics") + +def _impl(ctx): + output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") + return java_common.compile( + ctx, + source_files = ctx.files.srcs, + plugins = [p[JavaInfo] for p in ctx.attr.deps], + output = output_jar, + java_toolchain = semantics.find_java_toolchain(ctx), + ) + +custom_library_with_wrong_plugins_type = rule( + implementation = _impl, + attrs = { + "srcs": attr.label_list(allow_files = [".java"]), + "deps": attr.label_list(), + }, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], + fragments = ["java"], +) From 034f49e7c7adc14ea7620904b94ef7f2c82b2d6b Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 06:23:03 -0700 Subject: [PATCH 184/465] Migrate the `JavaStarlarkApiTest.testJavaRuntimeProviderJavaAbsolute` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738370419 Change-Id: Ie30a18d5dc62be8c3ff884413f45b9875eebd6b5 --- .../testutil/java_runtime_info_subject.bzl | 33 ++++++++++ .../rules/forward_java_runtime_info.bzl | 13 ++++ java/test/toolchains/BUILD | 3 + java/test/toolchains/java_runtime_tests.bzl | 65 +++++++++++++++++++ 4 files changed, 114 insertions(+) create mode 100644 java/test/testutil/java_runtime_info_subject.bzl create mode 100644 java/test/testutil/rules/forward_java_runtime_info.bzl create mode 100644 java/test/toolchains/BUILD create mode 100644 java/test/toolchains/java_runtime_tests.bzl diff --git a/java/test/testutil/java_runtime_info_subject.bzl b/java/test/testutil/java_runtime_info_subject.bzl new file mode 100644 index 00000000..fedb5e74 --- /dev/null +++ b/java/test/testutil/java_runtime_info_subject.bzl @@ -0,0 +1,33 @@ +"""Custom @rules_testing subject for the JavaRuntimeInfo provider""" + +load("@rules_testing//lib:truth.bzl", "subjects", "truth") +load("//java/common:java_common.bzl", "java_common") + +def _new_java_runtime_info_subject(java_runtime_info, meta): + self = struct( + actual = java_runtime_info, + meta = meta.derive("JavaRuntimeInfo"), + ) + public = struct( + java_home = lambda: subjects.str(self.actual.java_home, self.meta.derive("java_home")), + java_home_runfiles_path = lambda: subjects.str(self.actual.java_home_runfiles_path, self.meta.derive("java_home_runfiles_path")), + java_executable_exec_path = lambda: subjects.str(self.actual.java_executable_exec_path, self.meta.derive("java_executable_exec_path")), + java_executable_runfiles_path = lambda: subjects.str(self.actual.java_executable_runfiles_path, self.meta.derive("java_executable_runfiles_path")), + ) + return public + +def _from_target(env, target): + return _new_java_runtime_info_subject( + target[java_common.JavaRuntimeInfo], + meta = truth.expect(env).meta.derive( + format_str_kwargs = { + "name": target.label.name, + "package": target.label.package, + }, + ), + ) + +java_runtime_info_subject = struct( + new = _new_java_runtime_info_subject, + from_target = _from_target, +) diff --git a/java/test/testutil/rules/forward_java_runtime_info.bzl b/java/test/testutil/rules/forward_java_runtime_info.bzl new file mode 100644 index 00000000..217081fe --- /dev/null +++ b/java/test/testutil/rules/forward_java_runtime_info.bzl @@ -0,0 +1,13 @@ +"""Helper rule to test java_runtime and JavaRuntimeInfo""" + +load("//java/common:java_common.bzl", "java_common") + +def _impl(ctx): + return ctx.attr.java_runtime[java_common.JavaRuntimeInfo] + +java_runtime_info_forwarding_rule = rule( + _impl, + attrs = { + "java_runtime": attr.label(), + }, +) diff --git a/java/test/toolchains/BUILD b/java/test/toolchains/BUILD new file mode 100644 index 00000000..44f223bd --- /dev/null +++ b/java/test/toolchains/BUILD @@ -0,0 +1,3 @@ +load(":java_runtime_tests.bzl", "java_runtime_tests") + +java_runtime_tests(name = "java_runtime_tests") diff --git a/java/test/toolchains/java_runtime_tests.bzl b/java/test/toolchains/java_runtime_tests.bzl new file mode 100644 index 00000000..31cbab33 --- /dev/null +++ b/java/test/toolchains/java_runtime_tests.bzl @@ -0,0 +1,65 @@ +"""Tests for the java_runtime rule""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java/common:java_semantics.bzl", "semantics") +load("//java/test/testutil:java_runtime_info_subject.bzl", "java_runtime_info_subject") +load("//java/test/testutil:rules/forward_java_runtime_info.bzl", "java_runtime_info_forwarding_rule") +load("//java/toolchains:java_runtime.bzl", "java_runtime") +load("//toolchains:java_toolchain_alias.bzl", "java_runtime_alias") + +def _test_with_absolute_java_home(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + srcs = [], + java_home = "/foo/bar", + ) + util.helper_target( + java_runtime_alias, + name = name + "/alias", + ) + util.helper_target( + java_runtime_info_forwarding_rule, + name = name + "/r", + java_runtime = name + "/alias", + ) + util.helper_target( + native.toolchain, + name = name + "/java_runtime_toolchain", + toolchain = name + "/jvm", + toolchain_type = semantics.JAVA_RUNTIME_TOOLCHAIN_TYPE, + ) + + analysis_test( + name = name, + impl = _test_with_absolute_java_home_impl, + target = name + "/r", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/java_runtime_toolchain")], + }, + # Bazel 6 doesn't accept Label's for the transition above + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_with_absolute_java_home_impl(env, target): + assert_info = java_runtime_info_subject.from_target(env, target) + + assert_info.java_home().equals("/foo/bar") + assert_info.java_home_runfiles_path().equals("/foo/bar") + assert_info.java_executable_exec_path().is_in([ + "/foo/bar/bin/java", + "/foo/bar/bin/java.exe", + ]) + assert_info.java_executable_runfiles_path().is_in([ + "/foo/bar/bin/java", + "/foo/bar/bin/java.exe", + ]) + +def java_runtime_tests(name): + test_suite( + name = name, + tests = [ + _test_with_absolute_java_home, + ], + ) From ea02285f399c9c0b8d1e21a3958b57befa2929c5 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 06:40:00 -0700 Subject: [PATCH 185/465] Migrate the `JavaStarlarkApiTest.testJavaRuntimeProviderJavaHermetic` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738375246 Change-Id: Ic87608b17b98e5b4d6d6cecd833584cd3e7d2452 --- .../testutil/java_runtime_info_subject.bzl | 23 ++++++-- java/test/toolchains/java_runtime_tests.bzl | 53 ++++++++++++++++--- 2 files changed, 64 insertions(+), 12 deletions(-) diff --git a/java/test/testutil/java_runtime_info_subject.bzl b/java/test/testutil/java_runtime_info_subject.bzl index fedb5e74..79ab2fc4 100644 --- a/java/test/testutil/java_runtime_info_subject.bzl +++ b/java/test/testutil/java_runtime_info_subject.bzl @@ -9,13 +9,28 @@ def _new_java_runtime_info_subject(java_runtime_info, meta): meta = meta.derive("JavaRuntimeInfo"), ) public = struct( - java_home = lambda: subjects.str(self.actual.java_home, self.meta.derive("java_home")), - java_home_runfiles_path = lambda: subjects.str(self.actual.java_home_runfiles_path, self.meta.derive("java_home_runfiles_path")), - java_executable_exec_path = lambda: subjects.str(self.actual.java_executable_exec_path, self.meta.derive("java_executable_exec_path")), - java_executable_runfiles_path = lambda: subjects.str(self.actual.java_executable_runfiles_path, self.meta.derive("java_executable_runfiles_path")), + java_home = lambda: _new_path_string_subject(self.actual.java_home, self.meta.derive("java_home")), + java_home_runfiles_path = lambda: _new_path_string_subject(self.actual.java_home_runfiles_path, self.meta.derive("java_home_runfiles_path")), + java_executable_exec_path = lambda: _new_path_string_subject(self.actual.java_executable_exec_path, self.meta.derive("java_executable_exec_path")), + java_executable_runfiles_path = lambda: _new_path_string_subject(self.actual.java_executable_runfiles_path, self.meta.derive("java_executable_runfiles_path")), ) return public +def _new_path_string_subject(str, meta): + public = struct( + equals = lambda other: subjects.str(str, meta).equals(meta.format_str(other)), + is_in = lambda expected: subjects.str(str, meta).is_in([meta.format_str(e) for e in expected]), + starts_with = lambda prefix: _check_str_prefix(str, prefix, meta), + ) + return public + +def _check_str_prefix(actual, prefix, meta): + if not actual.startswith(meta.format_str(prefix)): + meta.add_failure( + "did not start with required prefix: {}".format(prefix), + "actual: {}".format(actual), + ) + def _from_target(env, target): return _new_java_runtime_info_subject( target[java_common.JavaRuntimeInfo], diff --git a/java/test/toolchains/java_runtime_tests.bzl b/java/test/toolchains/java_runtime_tests.bzl index 31cbab33..2dfcbbd6 100644 --- a/java/test/toolchains/java_runtime_tests.bzl +++ b/java/test/toolchains/java_runtime_tests.bzl @@ -47,19 +47,56 @@ def _test_with_absolute_java_home_impl(env, target): assert_info.java_home().equals("/foo/bar") assert_info.java_home_runfiles_path().equals("/foo/bar") - assert_info.java_executable_exec_path().is_in([ - "/foo/bar/bin/java", - "/foo/bar/bin/java.exe", - ]) - assert_info.java_executable_runfiles_path().is_in([ - "/foo/bar/bin/java", - "/foo/bar/bin/java.exe", - ]) + assert_info.java_executable_exec_path().starts_with("/foo/bar/bin/java") + assert_info.java_executable_runfiles_path().starts_with("/foo/bar/bin/java") + +def _test_with_hermetic_java_home(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + srcs = [], + java_home = "foo/bar", + ) + util.helper_target( + java_runtime_alias, + name = name + "/alias", + ) + util.helper_target( + java_runtime_info_forwarding_rule, + name = name + "/r", + java_runtime = name + "/alias", + ) + util.helper_target( + native.toolchain, + name = name + "/java_runtime_toolchain", + toolchain = name + "/jvm", + toolchain_type = semantics.JAVA_RUNTIME_TOOLCHAIN_TYPE, + ) + + analysis_test( + name = name, + impl = _test_with_hermetic_java_home_impl, + target = name + "/r", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/java_runtime_toolchain")], + }, + # Bazel 6 doesn't accept Label's for the transition above + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_with_hermetic_java_home_impl(env, target): + assert_info = java_runtime_info_subject.from_target(env, target) + + assert_info.java_home().equals("{package}/foo/bar") + assert_info.java_home_runfiles_path().equals("{package}/foo/bar") + assert_info.java_executable_exec_path().starts_with("{package}/foo/bar/bin/java") + assert_info.java_executable_runfiles_path().starts_with("{package}/foo/bar/bin/java") def java_runtime_tests(name): test_suite( name = name, tests = [ _test_with_absolute_java_home, + _test_with_hermetic_java_home, ], ) From bcfb25aa9adf4e35d5243ec9cf8df0057e42f091 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 07:01:22 -0700 Subject: [PATCH 186/465] Migrate the `JavaStarlarkApiTest.testJavaRuntimeProviderJavaGenerated` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738381284 Change-Id: Ie15bbe60e85bba0261ca248a67c77d48014c76a5 --- .../testutil/java_runtime_info_subject.bzl | 2 + java/test/toolchains/java_runtime_tests.bzl | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/java/test/testutil/java_runtime_info_subject.bzl b/java/test/testutil/java_runtime_info_subject.bzl index 79ab2fc4..ef5bdf92 100644 --- a/java/test/testutil/java_runtime_info_subject.bzl +++ b/java/test/testutil/java_runtime_info_subject.bzl @@ -1,6 +1,7 @@ """Custom @rules_testing subject for the JavaRuntimeInfo provider""" load("@rules_testing//lib:truth.bzl", "subjects", "truth") +load("@rules_testing//lib:util.bzl", "TestingAspectInfo") load("//java/common:java_common.bzl", "java_common") def _new_java_runtime_info_subject(java_runtime_info, meta): @@ -38,6 +39,7 @@ def _from_target(env, target): format_str_kwargs = { "name": target.label.name, "package": target.label.package, + "bindir": target[TestingAspectInfo].bin_path, }, ), ) diff --git a/java/test/toolchains/java_runtime_tests.bzl b/java/test/toolchains/java_runtime_tests.bzl index 2dfcbbd6..2f2b86d2 100644 --- a/java/test/toolchains/java_runtime_tests.bzl +++ b/java/test/toolchains/java_runtime_tests.bzl @@ -92,11 +92,61 @@ def _test_with_hermetic_java_home_impl(env, target): assert_info.java_executable_exec_path().starts_with("{package}/foo/bar/bin/java") assert_info.java_executable_runfiles_path().starts_with("{package}/foo/bar/bin/java") +def _test_with_generated_java_executable(name): + util.helper_target( + native.genrule, + name = name + "/gen", + cmd = "", + outs = ["foo/bar/bin/java"], + output_to_bindir = True, + ) + util.helper_target( + java_runtime, + name = name + "/jvm", + srcs = [], + java = "foo/bar/bin/java", + ) + util.helper_target( + java_runtime_alias, + name = name + "/alias", + ) + util.helper_target( + java_runtime_info_forwarding_rule, + name = name + "/r", + java_runtime = name + "/alias", + ) + util.helper_target( + native.toolchain, + name = name + "/java_runtime_toolchain", + toolchain = name + "/jvm", + toolchain_type = semantics.JAVA_RUNTIME_TOOLCHAIN_TYPE, + ) + + analysis_test( + name = name, + impl = _test_with_generated_java_executable_impl, + target = name + "/r", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/java_runtime_toolchain")], + }, + # Bazel 6 doesn't accept Label's for the transition above + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_with_generated_java_executable_impl(env, target): + assert_info = java_runtime_info_subject.from_target(env, target) + + assert_info.java_home().equals("{bindir}/{package}/foo/bar") + assert_info.java_home_runfiles_path().equals("{package}/foo/bar") + assert_info.java_executable_exec_path().starts_with("{bindir}/{package}/foo/bar/bin/java") + assert_info.java_executable_runfiles_path().starts_with("{package}/foo/bar/bin/java") + def java_runtime_tests(name): test_suite( name = name, tests = [ _test_with_absolute_java_home, _test_with_hermetic_java_home, + _test_with_generated_java_executable, ], ) From f6d461d3621a3707cee26717d670d49e08d03404 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 07:32:13 -0700 Subject: [PATCH 187/465] Migrate the `JavaStarlarkApiTest.testJavaCommonCompileCompilationInfo` test to Starlark The test is removed from Bazel and added in `@rules_java` Also fixes `semantics.tokenize()` for Bazel which was apparently unused :/ PiperOrigin-RevId: 738390715 Change-Id: Iff5c2d1869c9c8194a9e32ccfb066c6f4e04a7ae --- java/common/java_semantics.bzl | 8 ++++- java/test/common/java_common_tests.bzl | 34 +++++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 3 ++ java/test/testutil/rules/custom_library.bzl | 2 ++ 4 files changed, 46 insertions(+), 1 deletion(-) diff --git a/java/common/java_semantics.bzl b/java/common/java_semantics.bzl index 87873938..88d0bcc8 100644 --- a/java/common/java_semantics.bzl +++ b/java/common/java_semantics.bzl @@ -66,6 +66,12 @@ system property. }, ) +def _tokenize_javacopts(opts): + result = [] + for opt_str in opts: + cc_helper.tokenize(result, opt_str) + return result + semantics = struct( JAVA_TOOLCHAIN_LABEL = "@bazel_tools//tools/jdk:current_java_toolchain", JAVA_TOOLCHAIN_TYPE = "@bazel_tools//tools/jdk:toolchain_type", @@ -104,6 +110,6 @@ semantics = struct( for_attribute = lambda name: _DOCS.ATTRS.get(name, ""), ), minimize_cc_info = _minimize_cc_info, - tokenize_javacopts = cc_helper.tokenize, + tokenize_javacopts = _tokenize_javacopts, PLATFORMS_ROOT = "@platforms//", ) diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 2b594b0f..1676155a 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -453,6 +453,39 @@ def _test_compile_requires_java_plugin_info_impl(env, target): matching.str_matches("at index 0 of plugins, got element of type JavaInfo, want JavaPluginInfo"), ) +def _test_compile_compilation_info(name): + target_name = name + "/custom" + util.helper_target( + custom_library, + name = target_name, + srcs = ["Main.java"], + deps = [target_name + "/dep"], + javac_opts = ["-XDone -XDtwo"], + ) + util.helper_target( + java_library, + name = target_name + "/dep", + srcs = ["Dep.java"], + ) + + analysis_test( + name = name, + impl = _test_compile_compilation_info_impl, + target = target_name, + ) + +def _test_compile_compilation_info_impl(env, target): + assert_compilation_info = java_info_subject.from_target(env, target).compilation_info() + + assert_compilation_info.compilation_classpath().contains_exactly([ + "{package}/lib{name}/dep-hjar.jar", + ]) + assert_compilation_info.runtime_classpath().contains_exactly([ + "{package}/lib{name}/dep.jar", + "{package}/lib{name}.jar", + ]) + assert_compilation_info.javac_options().contains("-XDone") + def java_common_tests(name): test_suite( name = name, @@ -471,5 +504,6 @@ def java_common_tests(name): _test_compile_exposes_annotation_processing_info, _test_java_library_exposes_annotation_processing_info, _test_compile_requires_java_plugin_info, + _test_compile_compilation_info, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 532b05fa..147057df 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -4,6 +4,7 @@ load("@rules_testing//lib:truth.bzl", "subjects", "truth") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") +load("//java/common/rules/impl:java_helper.bzl", "helper") load(":cc_info_subject.bzl", "cc_info_subject") def _new_java_info_subject(java_info, meta): @@ -41,7 +42,9 @@ def _new_java_compilation_info_subject(java_info, meta): ) public = struct( compilation_classpath = lambda: subjects.depset_file(self.actual.compilation_classpath, self.meta.derive("compilation_classpath")), + runtime_classpath = lambda: subjects.depset_file(self.actual.runtime_classpath, self.meta.derive("runtime_classpath")), runtime_classpath_list = lambda: subjects.collection(self.actual.runtime_classpath.to_list(), self.meta.derive("runtime_classpath.to_list()")), + javac_options = lambda: subjects.collection(helper.tokenize_javacopts(opts = self.actual.javac_options), self.meta.derive("javac_options")), ) return public diff --git a/java/test/testutil/rules/custom_library.bzl b/java/test/testutil/rules/custom_library.bzl index 01bfb871..adedeb3e 100644 --- a/java/test/testutil/rules/custom_library.bzl +++ b/java/test/testutil/rules/custom_library.bzl @@ -17,6 +17,7 @@ def _custom_library_impl(ctx): runtime_deps = runtime_deps, exports = [e[JavaInfo] for e in ctx.attr.exports], plugins = [p[JavaPluginInfo] for p in ctx.attr.plugins], + javac_opts = ctx.attr.javac_opts, java_toolchain = semantics.find_java_toolchain(ctx), ) return [DefaultInfo(files = depset([output_jar])), compilation_provider] @@ -29,6 +30,7 @@ custom_library = rule( "runtime_deps": attr.label_list(), "exports": attr.label_list(), "plugins": attr.label_list(), + "javac_opts": attr.string_list(), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], fragments = ["java"], From 6d396eb08a54d835d0a34acb68af30dbf0b48820 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 08:07:45 -0700 Subject: [PATCH 188/465] Migrate the `JavaStarlarkApiTest.testJavaCommonCompileTransitiveSourceJars` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738401953 Change-Id: I36ff13fa63d007ecddea770c1241adfb8750a727 --- java/test/common/java_common_tests.bzl | 32 ++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 1676155a..ab462531 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -486,6 +486,37 @@ def _test_compile_compilation_info_impl(env, target): ]) assert_compilation_info.javac_options().contains("-XDone") +def _test_compile_transitive_source_jars(name): + target_name = name + "/custom" + util.helper_target( + custom_library, + name = target_name, + srcs = ["Main.java"], + deps = [target_name + "/dep"], + ) + util.helper_target( + java_library, + name = target_name + "/dep", + srcs = ["Dep.java"], + ) + + analysis_test( + name = name, + impl = _test_compile_transitive_source_jars_impl, + target = target_name, + ) + +def _test_compile_transitive_source_jars_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("custom-src.jar"), + ]) + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/lib{name}/dep-src.jar", + "{package}/lib{name}-src.jar", + ]) + def java_common_tests(name): test_suite( name = name, @@ -505,5 +536,6 @@ def java_common_tests(name): _test_java_library_exposes_annotation_processing_info, _test_compile_requires_java_plugin_info, _test_compile_compilation_info, + _test_compile_transitive_source_jars, ], ) From 5e7f74fd746e11d2b1ffcb2ca5d652f1aa8c261e Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 08:36:02 -0700 Subject: [PATCH 189/465] Migrate the `JavaStarlarkApiTest.testJavaCommonCompileSourceJarName` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738411122 Change-Id: Ibfee767b9e41b89a3cb5b718cd6a9c380c238928 --- java/test/common/java_common_tests.bzl | 35 ++++++++++++++++ .../custom_library_with_named_outputs.bzl | 40 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 java/test/testutil/rules/custom_library_with_named_outputs.bzl diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index ab462531..f01b2d2e 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -13,6 +13,7 @@ load("//java/test/testutil:rules/custom_library.bzl", "custom_library") load("//java/test/testutil:rules/custom_library_extended_compile_jdeps.bzl", "CompileJdepsInfo", "custom_library_extended_jdeps") load("//java/test/testutil:rules/custom_library_with_bootclasspath.bzl", "custom_bootclasspath", "custom_library_with_bootclasspath") load("//java/test/testutil:rules/custom_library_with_exports.bzl", "custom_library_with_exports") +load("//java/test/testutil:rules/custom_library_with_named_outputs.bzl", "custom_library_with_named_outputs") load("//java/test/testutil:rules/custom_library_with_sourcepaths.bzl", "custom_library_with_sourcepaths") load("//java/test/testutil:rules/custom_library_with_wrong_plugins_type.bzl", "custom_library_with_wrong_plugins_type") @@ -517,6 +518,39 @@ def _test_compile_transitive_source_jars_impl(env, target): "{package}/lib{name}-src.jar", ]) +def _test_compile_source_jar_name_derived_from_output_jar(name): + target_name = name + "/custom" + util.helper_target( + custom_library_with_named_outputs, + name = target_name, + srcs = ["Main.java"], + deps = [target_name + "/dep"], + ) + util.helper_target( + java_library, + name = target_name + "/dep", + srcs = ["Dep.java"], + ) + + analysis_test( + name = name, + impl = _test_compile_source_jar_name_derived_from_output_jar_impl, + target = target_name, + ) + +def _test_compile_source_jar_name_derived_from_output_jar_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("amazing-src.jar"), + matching.file_basename_equals("wonderful-src.jar"), + ]) + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/lib{name}/dep-src.jar", + "{package}/{name}/amazing-src.jar", + "{package}/{name}/wonderful-src.jar", + ]) + def java_common_tests(name): test_suite( name = name, @@ -537,5 +571,6 @@ def java_common_tests(name): _test_compile_requires_java_plugin_info, _test_compile_compilation_info, _test_compile_transitive_source_jars, + _test_compile_source_jar_name_derived_from_output_jar, ], ) diff --git a/java/test/testutil/rules/custom_library_with_named_outputs.bzl b/java/test/testutil/rules/custom_library_with_named_outputs.bzl new file mode 100644 index 00000000..ec0a412b --- /dev/null +++ b/java/test/testutil/rules/custom_library_with_named_outputs.bzl @@ -0,0 +1,40 @@ +"""Custom rule to test that source jar names are derived from the output jar""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_semantics.bzl", "semantics") + +def _impl(ctx): + output_jar = ctx.actions.declare_file(ctx.attr.name + "/amazing.jar") + other_output_jar = ctx.actions.declare_file(ctx.attr.name + "/wonderful.jar") + deps = [dep[java_common.provider] for dep in ctx.attr.deps] + compilation_provider = java_common.compile( + ctx, + source_files = ctx.files.srcs, + output = output_jar, + deps = deps, + java_toolchain = semantics.find_java_toolchain(ctx), + ) + other_compilation_provider = java_common.compile( + ctx, + source_files = ctx.files.srcs, + output = other_output_jar, + deps = deps, + java_toolchain = semantics.find_java_toolchain(ctx), + ) + result_provider = java_common.merge([compilation_provider, other_compilation_provider]) + return [ + DefaultInfo( + files = depset([output_jar]), + ), + result_provider, + ] + +custom_library_with_named_outputs = rule( + implementation = _impl, + attrs = { + "srcs": attr.label_list(allow_files = [".java"]), + "deps": attr.label_list(), + }, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], + fragments = ["java"], +) From cfa82ca771268f8ac95814da771edbe9c7e5e5cb Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 08:58:33 -0700 Subject: [PATCH 190/465] Migrate the `JavaStarlarkApiTest.testJavaCommonCompileWithOnlyOneSourceJar` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738418816 Change-Id: If935ebce9c89aa94972082cfcf16bc0f9284a2bf --- java/test/common/java_common_tests.bzl | 26 +++++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 1 + java/test/testutil/rules/custom_library.bzl | 2 ++ 3 files changed, 29 insertions(+) diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index f01b2d2e..0b9303f2 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -551,6 +551,31 @@ def _test_compile_source_jar_name_derived_from_output_jar_impl(env, target): "{package}/{name}/wonderful-src.jar", ]) +def _test_compile_with_only_one_source_jar(name): + util.helper_target( + custom_library, + name = name + "/custom", + source_jars = ["myjar-src.jar"], + ) + analysis_test( + name = name, + impl = _test_compile_with_only_one_source_jar_impl, + target = name + "/custom", + ) + +def _test_compile_with_only_one_source_jar_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("custom-src.jar"), + ]) + assert_output = assert_java_info.java_outputs().singleton() + assert_output.class_jar().short_path_equals("{package}/lib{name}.jar") + assert_output.compile_jar().short_path_equals("{package}/lib{name}-hjar.jar") + assert_output.source_jars().contains_exactly(["{package}/lib{name}-src.jar"]) + assert_output.jdeps().short_path_equals("{package}/lib{name}.jdeps") + assert_output.compile_jdeps().short_path_equals("{package}/lib{name}-hjar.jdeps") + def java_common_tests(name): test_suite( name = name, @@ -572,5 +597,6 @@ def java_common_tests(name): _test_compile_compilation_info, _test_compile_transitive_source_jars, _test_compile_source_jar_name_derived_from_output_jar, + _test_compile_with_only_one_source_jar, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 147057df..3ab4124a 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -20,6 +20,7 @@ def _new_java_info_subject(java_info, meta): constraints = lambda: subjects.collection(java_common.get_constraints(java_info), self.meta.derive("constraints")), annotation_processing = lambda: _new_annotation_processing_subject(self.actual, self.meta), outputs = lambda: _new_rule_output_info_subject(self.actual, self.meta), + java_outputs = lambda: _new_java_outputs_collection_subject(self.actual.java_outputs, self.meta.derive("java_outputs")), source_jars = lambda: subjects.collection(java_info.source_jars, self.meta.derive("source_jars")), transitive_source_jars = lambda: subjects.depset_file(java_info.transitive_source_jars, self.meta.derive("transitive_source_jars")), transitive_source_jars_list = lambda: subjects.collection(java_info.transitive_source_jars.to_list(), self.meta.derive("transitive_source_jars.to_list()")), diff --git a/java/test/testutil/rules/custom_library.bzl b/java/test/testutil/rules/custom_library.bzl index adedeb3e..500ad2b5 100644 --- a/java/test/testutil/rules/custom_library.bzl +++ b/java/test/testutil/rules/custom_library.bzl @@ -12,6 +12,7 @@ def _custom_library_impl(ctx): compilation_provider = java_common.compile( ctx, source_files = ctx.files.srcs, + source_jars = ctx.files.source_jars, output = output_jar, deps = deps, runtime_deps = runtime_deps, @@ -26,6 +27,7 @@ custom_library = rule( _custom_library_impl, attrs = { "srcs": attr.label_list(allow_files = [".java"]), + "source_jars": attr.label_list(allow_files = [".jar"]), "deps": attr.label_list(), "runtime_deps": attr.label_list(), "exports": attr.label_list(), From 097e8f06849cf16f7c02efb096cdf79c9d62e911 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 09:16:34 -0700 Subject: [PATCH 191/465] Migrate the `JavaStarlarkApiTest.testJavaCommonCompile_noSources` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738425092 Change-Id: I9eef5a7f53fb31e159f5ac74fca7f71cbfb38238 --- java/test/common/java_common_tests.bzl | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 0b9303f2..2fa69d92 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -576,6 +576,28 @@ def _test_compile_with_only_one_source_jar_impl(env, target): assert_output.jdeps().short_path_equals("{package}/lib{name}.jdeps") assert_output.compile_jdeps().short_path_equals("{package}/lib{name}-hjar.jdeps") +def _test_compile_no_sources(name): + util.helper_target( + custom_library, + name = name + "/custom", + ) + + analysis_test( + name = name, + impl = _test_compile_no_sources_impl, + target = name + "/custom", + ) + +def _test_compile_no_sources_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("custom-src.jar"), + ]) + assert_output = assert_java_info.java_outputs().singleton() + assert_output.class_jar().short_path_equals("{package}/lib{name}.jar") + assert_output.source_jars().contains_exactly(["{package}/lib{name}-src.jar"]) + def java_common_tests(name): test_suite( name = name, @@ -598,5 +620,6 @@ def java_common_tests(name): _test_compile_transitive_source_jars, _test_compile_source_jar_name_derived_from_output_jar, _test_compile_with_only_one_source_jar, + _test_compile_no_sources, ], ) From 23054ebce0277ea3ca9082475c033dac4e5410b4 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 09:44:40 -0700 Subject: [PATCH 192/465] Migrate the `JavaStarlarkApiTest.testJavaCommonCompileCustomSourceJar` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738434328 Change-Id: Ic3618c1cf24a0928fa4faa2899decb474dd5603a --- java/test/common/java_common_tests.bzl | 28 +++++++++++++++++ ..._library_with_custom_output_source_jar.bzl | 30 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 java/test/testutil/rules/custom_library_with_custom_output_source_jar.bzl diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 2fa69d92..bf7cfb88 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -12,6 +12,7 @@ load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") load("//java/test/testutil:rules/custom_library.bzl", "custom_library") load("//java/test/testutil:rules/custom_library_extended_compile_jdeps.bzl", "CompileJdepsInfo", "custom_library_extended_jdeps") load("//java/test/testutil:rules/custom_library_with_bootclasspath.bzl", "custom_bootclasspath", "custom_library_with_bootclasspath") +load("//java/test/testutil:rules/custom_library_with_custom_output_source_jar.bzl", "custom_library_with_custom_output_source_jar") load("//java/test/testutil:rules/custom_library_with_exports.bzl", "custom_library_with_exports") load("//java/test/testutil:rules/custom_library_with_named_outputs.bzl", "custom_library_with_named_outputs") load("//java/test/testutil:rules/custom_library_with_sourcepaths.bzl", "custom_library_with_sourcepaths") @@ -598,6 +599,32 @@ def _test_compile_no_sources_impl(env, target): assert_output.class_jar().short_path_equals("{package}/lib{name}.jar") assert_output.source_jars().contains_exactly(["{package}/lib{name}-src.jar"]) +def _test_compile_custom_output_source_jar(name): + util.helper_target( + custom_library_with_custom_output_source_jar, + name = name + "/custom", + srcs = ["myjar-src.jar"], + ) + + analysis_test( + name = name, + impl = _test_compile_custom_output_source_jar_impl, + target = name + "/custom", + ) + +def _test_compile_custom_output_source_jar_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.source_jars().contains_exactly_predicates([ + matching.file_basename_equals("custom-mysrc.jar"), + ]) + assert_output = assert_java_info.java_outputs().singleton() + assert_output.class_jar().short_path_equals("{package}/lib{name}.jar") + assert_output.compile_jar().short_path_equals("{package}/lib{name}-hjar.jar") + assert_output.source_jars().contains_exactly(["{package}/lib{name}-mysrc.jar"]) + assert_output.jdeps().short_path_equals("{package}/lib{name}.jdeps") + assert_output.compile_jdeps().short_path_equals("{package}/lib{name}-hjar.jdeps") + def java_common_tests(name): test_suite( name = name, @@ -621,5 +648,6 @@ def java_common_tests(name): _test_compile_source_jar_name_derived_from_output_jar, _test_compile_with_only_one_source_jar, _test_compile_no_sources, + _test_compile_custom_output_source_jar, ], ) diff --git a/java/test/testutil/rules/custom_library_with_custom_output_source_jar.bzl b/java/test/testutil/rules/custom_library_with_custom_output_source_jar.bzl new file mode 100644 index 00000000..531cb91b --- /dev/null +++ b/java/test/testutil/rules/custom_library_with_custom_output_source_jar.bzl @@ -0,0 +1,30 @@ +"""Custom rule to test java_common.compile() with a custom output source jar""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_semantics.bzl", "semantics") + +def _impl(ctx): + output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") + output_source_jar = ctx.actions.declare_file("lib" + ctx.label.name + "-mysrc.jar") + compilation_provider = java_common.compile( + ctx, + source_jars = ctx.files.srcs, + output = output_jar, + output_source_jar = output_source_jar, + java_toolchain = semantics.find_java_toolchain(ctx), + ) + return [ + DefaultInfo( + files = depset([output_source_jar]), + ), + compilation_provider, + ] + +custom_library_with_custom_output_source_jar = rule( + implementation = _impl, + attrs = { + "srcs": attr.label_list(allow_files = [".jar"]), + }, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], + fragments = ["java"], +) From b50d40e3a9cef9562ae39c04dc326f556a023324 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 10:12:35 -0700 Subject: [PATCH 193/465] Migrate the `JavaStarlarkApiTest.testJavaCommonCompileAdditionalInputsAndOutputs` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738445474 Change-Id: I74276b5c830234d602dc9e2a7eb0da49d1742e0f --- java/test/common/java_common_tests.bzl | 28 ++++++++++++++++++ .../custom_library_with_additional_inputs.bzl | 29 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 java/test/testutil/rules/custom_library_with_additional_inputs.bzl diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index bf7cfb88..02ee1812 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -11,6 +11,7 @@ load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") load("//java/test/testutil:rules/custom_library.bzl", "custom_library") load("//java/test/testutil:rules/custom_library_extended_compile_jdeps.bzl", "CompileJdepsInfo", "custom_library_extended_jdeps") +load("//java/test/testutil:rules/custom_library_with_additional_inputs.bzl", "custom_library_with_additional_inputs") load("//java/test/testutil:rules/custom_library_with_bootclasspath.bzl", "custom_bootclasspath", "custom_library_with_bootclasspath") load("//java/test/testutil:rules/custom_library_with_custom_output_source_jar.bzl", "custom_library_with_custom_output_source_jar") load("//java/test/testutil:rules/custom_library_with_exports.bzl", "custom_library_with_exports") @@ -625,6 +626,32 @@ def _test_compile_custom_output_source_jar_impl(env, target): assert_output.jdeps().short_path_equals("{package}/lib{name}.jdeps") assert_output.compile_jdeps().short_path_equals("{package}/lib{name}-hjar.jdeps") +def _test_compile_additional_inputs_and_outputs(name): + util.helper_target( + custom_library_with_additional_inputs, + name = name + "/custom", + srcs = ["myjar-src.jar"], + additional_inputs = ["additional_input.bin"], + ) + + analysis_test( + name = name, + impl = _test_compile_additional_inputs_and_outputs_impl, + target = name + "/custom", + ) + +def _test_compile_additional_inputs_and_outputs_impl(env, target): + assert_java_action = env.expect.that_target(target).action_generating( + "{package}/lib{name}.jar", + ) + + assert_java_action.inputs().contains_predicate( + matching.file_basename_equals("additional_input.bin"), + ) + env.expect.that_depset_of_files(assert_java_action.actual.outputs).contains_predicate( + matching.file_basename_equals("custom_additional_output"), + ) + def java_common_tests(name): test_suite( name = name, @@ -649,5 +676,6 @@ def java_common_tests(name): _test_compile_with_only_one_source_jar, _test_compile_no_sources, _test_compile_custom_output_source_jar, + _test_compile_additional_inputs_and_outputs, ], ) diff --git a/java/test/testutil/rules/custom_library_with_additional_inputs.bzl b/java/test/testutil/rules/custom_library_with_additional_inputs.bzl new file mode 100644 index 00000000..fa29429e --- /dev/null +++ b/java/test/testutil/rules/custom_library_with_additional_inputs.bzl @@ -0,0 +1,29 @@ +"""Custom rule to test java_common.compile() with additional inputs and outputs""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_semantics.bzl", "semantics") + +def _impl(ctx): + output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") + java_common.compile( + ctx, + source_jars = ctx.files.srcs, + output = output_jar, + annotation_processor_additional_inputs = ctx.files.additional_inputs, + annotation_processor_additional_outputs = [ctx.outputs.additional_output], + java_toolchain = semantics.find_java_toolchain(ctx), + ) + return [DefaultInfo(files = depset([output_jar]))] + +custom_library_with_additional_inputs = rule( + implementation = _impl, + outputs = { + "additional_output": "%{name}_additional_output", + }, + attrs = { + "srcs": attr.label_list(allow_files = [".jar"]), + "additional_inputs": attr.label_list(allow_files = [".bin"]), + }, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], + fragments = ["java"], +) From 36955388915f71b7ba56df2b16486d80508aa609 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 10:30:56 -0700 Subject: [PATCH 194/465] Migrate the `JavaStarlarkApiTest.javaPlugin_exposesPluginsToStarlark` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738452711 Change-Id: I093918d6defca2419cfa6aa90b007b7a62569a92 --- java/test/common/rules/BUILD | 3 ++ java/test/common/rules/java_plugin_tests.bzl | 49 ++++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 27 +++++++---- 3 files changed, 70 insertions(+), 9 deletions(-) create mode 100644 java/test/common/rules/java_plugin_tests.bzl diff --git a/java/test/common/rules/BUILD b/java/test/common/rules/BUILD index 1045061a..a97a3fb5 100644 --- a/java/test/common/rules/BUILD +++ b/java/test/common/rules/BUILD @@ -1,6 +1,9 @@ load(":java_binary_tests.bzl", "java_binary_tests") +load(":java_plugin_tests.bzl", "java_plugin_tests") load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") merge_attrs_test_suite(name = "merge_attrs_tests") java_binary_tests(name = "java_binary_tests") + +java_plugin_tests(name = "java_plugin_tests") diff --git a/java/test/common/rules/java_plugin_tests.bzl b/java/test/common/rules/java_plugin_tests.bzl new file mode 100644 index 00000000..af69e427 --- /dev/null +++ b/java/test/common/rules/java_plugin_tests.bzl @@ -0,0 +1,49 @@ +"""Tests for the java_plugin rule""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_library.bzl", "java_library") +load("//java:java_plugin.bzl", "java_plugin") +load("//java/test/testutil:java_info_subject.bzl", "java_plugin_info_subject") + +def _test_exposes_plugins_to_starlark(name): + target_name = name + "/plugin" + util.helper_target( + java_library, + name = target_name + "/plugin_dep", + srcs = ["ProcessorDep.java"], + data = ["depfile.dat"], + ) + util.helper_target( + java_plugin, + name = target_name, + srcs = ["AnnotationProcessor.java"], + data = ["pluginfile.dat"], + processor_class = "com.google.process.stuff", + deps = [target_name + "/plugin_dep"], + ) + + analysis_test( + name = name, + impl = _test_exposes_plugins_to_starlark_impl, + target = target_name, + ) + +def _test_exposes_plugins_to_starlark_impl(env, target): + assert_plugin_data = java_plugin_info_subject.from_target(env, target).plugins() + assert_plugin_data.processor_classes().contains_exactly(["com.google.process.stuff"]) + assert_plugin_data.processor_jars().contains_exactly([ + "{package}/lib{name}.jar", + "{package}/lib{name}/plugin_dep.jar", + ]) + assert_plugin_data.processor_data().contains_exactly(["{package}/pluginfile.dat"]) + + java_plugin_info_subject.from_target(env, target).api_generating_plugins().is_empty() + +def java_plugin_tests(name): + test_suite( + name = name, + tests = [ + _test_exposes_plugins_to_starlark, + ], + ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 3ab4124a..5712a9a9 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -12,7 +12,7 @@ def _new_java_info_subject(java_info, meta): public = struct( compilation_args = lambda: _new_java_compilation_args_subject(self.actual, self.meta), compilation_info = lambda: _new_java_compilation_info_subject(self.actual, self.meta), - plugins = lambda: _new_java_info_plugins_subject(self.actual, self.meta), + plugins = lambda: _new_java_plugin_data_subject(self.actual.plugins, self.meta.derive("plugins")), is_binary = lambda: subjects.bool(getattr(java_info, "_is_binary", False), self.meta.derive("_is_binary")), has_attr = lambda a: subjects.bool(getattr(java_info, a, None) != None, meta = self.meta.derive("{} != None".format(a))).equals(True), cc_link_params_info = lambda: cc_info_subject.new_from_java_info(java_info, meta), @@ -126,17 +126,24 @@ def _java_compilation_args_equals(self, other): "actual: {}".format(this_attr), ) -def _new_java_info_plugins_subject(java_info, meta): - self = struct( - actual = java_info.plugins, - meta = meta.derive("plugins"), - ) +def _new_java_plugin_data_subject(java_plugin_data, meta): public = struct( - processor_jars = lambda: subjects.depset_file(self.actual.processor_jars, meta = self.meta.derive("processor_jars")), - processor_classes = lambda: subjects.collection(self.actual.processor_classes, meta = self.meta.derive("processor_classes")), + processor_jars = lambda: subjects.depset_file(java_plugin_data.processor_jars, meta = meta.derive("processor_jars")), + processor_classes = lambda: subjects.collection(java_plugin_data.processor_classes, meta = meta.derive("processor_classes")), + processor_data = lambda: subjects.depset_file(java_plugin_data.processor_data, meta = meta.derive("processor_data")), + is_empty = lambda: _check_plugin_data_empty(java_plugin_data, meta.derive("is_empty()")), ) return public +def _check_plugin_data_empty(plugin_data, meta): + for attr in ["processor_jars", "processor_classes", "processor_data"]: + value = getattr(plugin_data, attr) + if value: + meta.add_failure( + "expected: {} to be empty".format(attr), + "actual: {}".format(value), + ) + def _new_annotation_processing_subject(java_info, meta): actual = java_info.annotation_processing meta = meta.derive("annotation_processing") @@ -160,7 +167,9 @@ def _new_annotation_processing_subject(java_info, meta): def _new_java_plugin_info_subject(java_plugin_info, meta): self = struct(actual = java_plugin_info, meta = meta.derive("JavaPluginInfo")) public = struct( - java_outputs = lambda: _new_java_outputs_collection_subject(self.actual.java_outputs, meta.derive("java_outputs")), + java_outputs = lambda: _new_java_outputs_collection_subject(self.actual.java_outputs, self.meta.derive("java_outputs")), + plugins = lambda: _new_java_plugin_data_subject(self.actual.plugins, self.meta.derive("plugins")), + api_generating_plugins = lambda: _new_java_plugin_data_subject(self.actual.api_generating_plugins, self.meta.derive("api_generating_plugins")), ) return public From 3678d25fac9bed79fe7e4d1b5e6bf3bc0636a756 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 10:57:15 -0700 Subject: [PATCH 195/465] Migrate the `JavaStarlarkApiTest.apiGeneratingjavaPlugin_exposesPluginsToStarlark` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738463236 Change-Id: I94b0f783fd6ccc61bd70aadfa21c5372e218f84e --- java/test/common/rules/java_plugin_tests.bzl | 36 ++++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 1 + 2 files changed, 37 insertions(+) diff --git a/java/test/common/rules/java_plugin_tests.bzl b/java/test/common/rules/java_plugin_tests.bzl index af69e427..047917a9 100644 --- a/java/test/common/rules/java_plugin_tests.bzl +++ b/java/test/common/rules/java_plugin_tests.bzl @@ -4,6 +4,7 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") +load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/test/testutil:java_info_subject.bzl", "java_plugin_info_subject") def _test_exposes_plugins_to_starlark(name): @@ -40,10 +41,45 @@ def _test_exposes_plugins_to_starlark_impl(env, target): java_plugin_info_subject.from_target(env, target).api_generating_plugins().is_empty() +def _test_exposes_api_generating_plugins_to_starlark(name): + target_name = name + "/plugin" + util.helper_target( + java_library, + name = target_name + "/plugin_dep", + srcs = ["ProcessorDep.java"], + data = ["depfile.dat"], + ) + util.helper_target( + java_plugin, + name = target_name, + srcs = ["AnnotationProcessor.java"], + data = ["pluginfile.dat"], + processor_class = "com.google.process.stuff", + deps = [target_name + "/plugin_dep"], + generates_api = True, + ) + + analysis_test( + name = name, + impl = _test_exposes_api_generating_plugins_to_starlark_impl, + target = target_name, + ) + +def _test_exposes_api_generating_plugins_to_starlark_impl(env, target): + assert_api_plugin_data = java_plugin_info_subject.from_target(env, target).api_generating_plugins() + assert_api_plugin_data.processor_classes().contains_exactly(["com.google.process.stuff"]) + assert_api_plugin_data.processor_jars().contains_exactly([ + "{package}/lib{name}.jar", + "{package}/lib{name}/plugin_dep.jar", + ]) + assert_api_plugin_data.processor_data().contains_exactly(["{package}/pluginfile.dat"]) + assert_api_plugin_data.equals(target[JavaPluginInfo].plugins) + def java_plugin_tests(name): test_suite( name = name, tests = [ _test_exposes_plugins_to_starlark, + _test_exposes_api_generating_plugins_to_starlark, ], ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index 5712a9a9..b9580971 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -132,6 +132,7 @@ def _new_java_plugin_data_subject(java_plugin_data, meta): processor_classes = lambda: subjects.collection(java_plugin_data.processor_classes, meta = meta.derive("processor_classes")), processor_data = lambda: subjects.depset_file(java_plugin_data.processor_data, meta = meta.derive("processor_data")), is_empty = lambda: _check_plugin_data_empty(java_plugin_data, meta.derive("is_empty()")), + equals = lambda other: subjects.bool(java_plugin_data == other, meta.derive("equals({})".format(other))).equals(True), ) return public From e2061b24bc2893d2dbcf535bd39e4e5ff78e3302 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 11:25:27 -0700 Subject: [PATCH 196/465] Migrate the `JavaStarlarkApiTest.javaLibrary_exposesPluginsToStarlark` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738474383 Change-Id: Ib8ba611675bcb0ab12d9fbf6b1b00781eb15211e --- java/test/common/rules/BUILD | 3 + java/test/common/rules/java_library_tests.bzl | 86 +++++++++++++++++++ java/test/testutil/java_info_subject.bzl | 1 + 3 files changed, 90 insertions(+) create mode 100644 java/test/common/rules/java_library_tests.bzl diff --git a/java/test/common/rules/BUILD b/java/test/common/rules/BUILD index a97a3fb5..e46aa944 100644 --- a/java/test/common/rules/BUILD +++ b/java/test/common/rules/BUILD @@ -1,4 +1,5 @@ load(":java_binary_tests.bzl", "java_binary_tests") +load(":java_library_tests.bzl", "java_library_tests") load(":java_plugin_tests.bzl", "java_plugin_tests") load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") @@ -7,3 +8,5 @@ merge_attrs_test_suite(name = "merge_attrs_tests") java_binary_tests(name = "java_binary_tests") java_plugin_tests(name = "java_plugin_tests") + +java_library_tests(name = "java_library_tests") diff --git a/java/test/common/rules/java_library_tests.bzl b/java/test/common/rules/java_library_tests.bzl new file mode 100644 index 00000000..fb8c9a7d --- /dev/null +++ b/java/test/common/rules/java_library_tests.bzl @@ -0,0 +1,86 @@ +"""Tests for the java_library rule""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_library.bzl", "java_library") +load("//java:java_plugin.bzl", "java_plugin") +load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") + +def _test_exposes_plugins(name): + target_name = name + "/library" + util.helper_target( + java_library, + name = target_name + "/plugin_dep1", + srcs = ["A.java"], + data = ["depfile1.dat"], + ) + util.helper_target( + java_library, + name = target_name + "/plugin_dep2", + srcs = ["B.java"], + data = ["depfile2.dat"], + ) + util.helper_target( + java_plugin, + name = target_name + "/plugin", + srcs = ["AnnotationProcessor1.java"], + data = ["pluginfile1.dat"], + processor_class = "com.google.process.stuff", + deps = [target_name + "/plugin_dep1"], + ) + util.helper_target( + java_plugin, + name = target_name + "/apiplugin", + srcs = ["AnnotationProcessor2.java"], + data = ["pluginfile2.dat"], + generates_api = True, + processor_class = "com.google.process.apistuff", + deps = [target_name + "/plugin_dep2"], + ) + util.helper_target( + java_library, + name = target_name, + exported_plugins = [ + target_name + "/plugin", + target_name + "/apiplugin", + ], + ) + + analysis_test( + name = name, + impl = _test_exposes_plugins_impl, + target = target_name, + ) + +def _test_exposes_plugins_impl(env, target): + assert_plugin_data = java_info_subject.from_target(env, target).plugins() + assert_plugin_data.processor_classes().contains_exactly([ + "com.google.process.stuff", + "com.google.process.apistuff", + ]) + assert_plugin_data.processor_jars().contains_exactly([ + "{package}/lib{name}/plugin.jar", + "{package}/lib{name}/plugin_dep1.jar", + "{package}/lib{name}/apiplugin.jar", + "{package}/lib{name}/plugin_dep2.jar", + ]) + assert_plugin_data.processor_data().contains_exactly([ + "{package}/pluginfile1.dat", + "{package}/pluginfile2.dat", + ]) + + assert_api_plugin_data = java_info_subject.from_target(env, target).api_generating_plugins() + assert_api_plugin_data.processor_classes().contains_exactly(["com.google.process.apistuff"]) + assert_api_plugin_data.processor_jars().contains_exactly([ + "{package}/lib{name}/apiplugin.jar", + "{package}/lib{name}/plugin_dep2.jar", + ]) + assert_api_plugin_data.processor_data().contains_exactly(["{package}/pluginfile2.dat"]) + +def java_library_tests(name): + test_suite( + name = name, + tests = [ + _test_exposes_plugins, + ], + ) diff --git a/java/test/testutil/java_info_subject.bzl b/java/test/testutil/java_info_subject.bzl index b9580971..a49963a1 100644 --- a/java/test/testutil/java_info_subject.bzl +++ b/java/test/testutil/java_info_subject.bzl @@ -13,6 +13,7 @@ def _new_java_info_subject(java_info, meta): compilation_args = lambda: _new_java_compilation_args_subject(self.actual, self.meta), compilation_info = lambda: _new_java_compilation_info_subject(self.actual, self.meta), plugins = lambda: _new_java_plugin_data_subject(self.actual.plugins, self.meta.derive("plugins")), + api_generating_plugins = lambda: _new_java_plugin_data_subject(self.actual.api_generating_plugins, self.meta.derive("api_generating_plugins")), is_binary = lambda: subjects.bool(getattr(java_info, "_is_binary", False), self.meta.derive("_is_binary")), has_attr = lambda a: subjects.bool(getattr(java_info, a, None) != None, meta = self.meta.derive("{} != None".format(a))).equals(True), cc_link_params_info = lambda: cc_info_subject.new_from_java_info(java_info, meta), From b43a99e233de898e7ce1311f36c60321d986d293 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 12:10:02 -0700 Subject: [PATCH 197/465] Migrate the `JavaStarlarkApiTest.javaPluginInfo_create` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738491544 Change-Id: I1db16f7e82c1e7d8a3dc836160761ec8b7bead52 --- java/test/common/java_plugin_info_tests.bzl | 38 +++++++++++++++++++++ java/test/testutil/rules/custom_plugin.bzl | 30 ++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 java/test/testutil/rules/custom_plugin.bzl diff --git a/java/test/common/java_plugin_info_tests.bzl b/java/test/common/java_plugin_info_tests.bzl index 381a6d48..2206e7d1 100644 --- a/java/test/common/java_plugin_info_tests.bzl +++ b/java/test/common/java_plugin_info_tests.bzl @@ -5,6 +5,7 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/test/testutil:java_info_subject.bzl", "java_plugin_info_subject") +load("//java/test/testutil:rules/custom_plugin.bzl", "custom_plugin") def _test_exposes_java_outputs(name): util.helper_target( @@ -34,10 +35,47 @@ def _test_exposes_java_outputs_impl(env, target): assert_output.jdeps().short_path_equals("{package}/lib{name}.jdeps") assert_output.compile_jdeps().short_path_equals("{package}/lib{name}-hjar.jdeps") +def _test_provider_contstructor(name): + target_name = name + "/plugin" + util.helper_target( + java_library, + name = target_name + "/plugin_dep1", + srcs = ["A.java"], + data = ["depfile1.dat"], + ) + util.helper_target( + custom_plugin, + name = target_name, + data = ["pluginfile1.dat"], + processor_class = "com.google.process.stuff", + deps = [target_name + "/plugin_dep1"], + ) + + analysis_test( + name = name, + impl = _test_provider_contstructor_impl, + target = target_name, + ) + +def _test_provider_contstructor_impl(env, target): + assert_plugin_data = java_plugin_info_subject.from_target(env, target).plugins() + assert_plugin_data.processor_classes().contains_exactly(["com.google.process.stuff"]) + assert_plugin_data.processor_jars().contains_exactly([ + "{package}/{name}/lib.jar", + "{package}/lib{name}/plugin_dep1.jar", + ]) + assert_plugin_data.processor_data().contains_exactly(["{package}/pluginfile1.dat"]) + + assert_api_plugin_data = java_plugin_info_subject.from_target(env, target).api_generating_plugins() + assert_api_plugin_data.processor_classes().contains_exactly([]) + assert_api_plugin_data.processor_jars().contains_exactly([]) + assert_api_plugin_data.processor_data().contains_exactly([]) + def java_plugin_info_tests(name): test_suite( name = name, tests = [ _test_exposes_java_outputs, + _test_provider_contstructor, ], ) diff --git a/java/test/testutil/rules/custom_plugin.bzl b/java/test/testutil/rules/custom_plugin.bzl new file mode 100644 index 00000000..a7d7e332 --- /dev/null +++ b/java/test/testutil/rules/custom_plugin.bzl @@ -0,0 +1,30 @@ +"""Custom rule to test the JavaPluginInfo provider""" + +load("//java/common:java_info.bzl", "JavaInfo") +load( + "//java/common:java_plugin_info.bzl", + "JavaPluginInfo", +) + +def _impl(ctx): + output_jar = ctx.actions.declare_file(ctx.label.name + "/lib.jar") + ctx.actions.write(output_jar, "") + dep = JavaInfo( + output_jar = output_jar, + compile_jar = None, + deps = [d[JavaInfo] for d in ctx.attr.deps], + ) + return [JavaPluginInfo( + runtime_deps = [dep], + processor_class = ctx.attr.processor_class, + data = ctx.files.data, + )] + +custom_plugin = rule( + implementation = _impl, + attrs = { + "deps": attr.label_list(), + "processor_class": attr.string(), + "data": attr.label_list(allow_files = True), + }, +) From 27acaa7cbb222573947c4452ad0a28e322e49c9d Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 12:28:04 -0700 Subject: [PATCH 198/465] Migrate the `JavaStarlarkApiTest.javaPluginInfo_createApiPlugin` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738498457 Change-Id: Ia4b350b4cccd4e03fdd4d35131a7c19eb9e713e3 --- java/test/common/java_plugin_info_tests.bzl | 35 +++++++++++++++++++++ java/test/testutil/rules/custom_plugin.bzl | 2 ++ 2 files changed, 37 insertions(+) diff --git a/java/test/common/java_plugin_info_tests.bzl b/java/test/common/java_plugin_info_tests.bzl index 2206e7d1..5d79f414 100644 --- a/java/test/common/java_plugin_info_tests.bzl +++ b/java/test/common/java_plugin_info_tests.bzl @@ -4,6 +4,7 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") +load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/test/testutil:java_info_subject.bzl", "java_plugin_info_subject") load("//java/test/testutil:rules/custom_plugin.bzl", "custom_plugin") @@ -71,11 +72,45 @@ def _test_provider_contstructor_impl(env, target): assert_api_plugin_data.processor_jars().contains_exactly([]) assert_api_plugin_data.processor_data().contains_exactly([]) +def _test_api_generating_provider_constructor(name): + target_name = name + "/plugin" + util.helper_target( + java_library, + name = target_name + "/plugin_dep1", + srcs = ["A.java"], + data = ["depfile1.dat"], + ) + util.helper_target( + custom_plugin, + name = target_name, + data = ["pluginfile1.dat"], + processor_class = "com.google.process.stuff", + deps = [target_name + "/plugin_dep1"], + generates_api = True, + ) + + analysis_test( + name = name, + impl = _test_api_generating_provider_constructor_impl, + target = target_name, + ) + +def _test_api_generating_provider_constructor_impl(env, target): + assert_api_plugin_data = java_plugin_info_subject.from_target(env, target).api_generating_plugins() + assert_api_plugin_data.processor_classes().contains_exactly(["com.google.process.stuff"]) + assert_api_plugin_data.processor_jars().contains_exactly([ + "{package}/{name}/lib.jar", + "{package}/lib{name}/plugin_dep1.jar", + ]) + assert_api_plugin_data.processor_data().contains_exactly(["{package}/pluginfile1.dat"]) + assert_api_plugin_data.equals(target[JavaPluginInfo].plugins) + def java_plugin_info_tests(name): test_suite( name = name, tests = [ _test_exposes_java_outputs, _test_provider_contstructor, + _test_api_generating_provider_constructor, ], ) diff --git a/java/test/testutil/rules/custom_plugin.bzl b/java/test/testutil/rules/custom_plugin.bzl index a7d7e332..417cc31c 100644 --- a/java/test/testutil/rules/custom_plugin.bzl +++ b/java/test/testutil/rules/custom_plugin.bzl @@ -18,6 +18,7 @@ def _impl(ctx): runtime_deps = [dep], processor_class = ctx.attr.processor_class, data = ctx.files.data, + generates_api = ctx.attr.generates_api, )] custom_plugin = rule( @@ -26,5 +27,6 @@ custom_plugin = rule( "deps": attr.label_list(), "processor_class": attr.string(), "data": attr.label_list(allow_files = True), + "generates_api": attr.bool(default = False), }, ) From a6a508420219ee777250217ef8667cd7ed6b59c7 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 12:46:06 -0700 Subject: [PATCH 199/465] Migrate the `JavaStarlarkApiTest.javaPluginInfo_createWithoutProcessorClass` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738504237 Change-Id: Ia02533e02459b6ab82dac699f0f5d0b008580e49 --- java/test/common/java_plugin_info_tests.bzl | 37 +++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/java/test/common/java_plugin_info_tests.bzl b/java/test/common/java_plugin_info_tests.bzl index 5d79f414..fc568414 100644 --- a/java/test/common/java_plugin_info_tests.bzl +++ b/java/test/common/java_plugin_info_tests.bzl @@ -105,6 +105,42 @@ def _test_api_generating_provider_constructor_impl(env, target): assert_api_plugin_data.processor_data().contains_exactly(["{package}/pluginfile1.dat"]) assert_api_plugin_data.equals(target[JavaPluginInfo].plugins) +def _test_without_processor_class(name): + target_name = name + "/plugin" + util.helper_target( + java_library, + name = target_name + "/plugin_dep1", + srcs = ["A.java"], + data = ["depfile1.dat"], + ) + util.helper_target( + custom_plugin, + name = target_name, + processor_class = None, + data = ["pluginfile1.dat"], + deps = [target_name + "/plugin_dep1"], + ) + analysis_test( + name = name, + impl = _test_without_processor_class_impl, + target = target_name, + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_without_processor_class_impl(env, target): + assert_plugin_data = java_plugin_info_subject.from_target(env, target).plugins() + assert_plugin_data.processor_classes().contains_exactly([]) + assert_plugin_data.processor_jars().contains_exactly([ + "{package}/{name}/lib.jar", + "{package}/lib{name}/plugin_dep1.jar", + ]) + assert_plugin_data.processor_data().contains_exactly(["{package}/pluginfile1.dat"]) + + assert_api_plugin_data = java_plugin_info_subject.from_target(env, target).api_generating_plugins() + assert_api_plugin_data.processor_classes().contains_exactly([]) + assert_api_plugin_data.processor_jars().contains_exactly([]) + assert_api_plugin_data.processor_data().contains_exactly([]) + def java_plugin_info_tests(name): test_suite( name = name, @@ -112,5 +148,6 @@ def java_plugin_info_tests(name): _test_exposes_java_outputs, _test_provider_contstructor, _test_api_generating_provider_constructor, + _test_without_processor_class, ], ) From 6683a8d2ea12626238f473c28e8a3ee51175ba89 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 13:04:09 -0700 Subject: [PATCH 200/465] Migrate the `JavaStarlarkApiTest.javaPluginInfo_createWithDataDepset` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738510587 Change-Id: Icdd04e401455779a19eefb6f49bf1ea9c16e5f4c --- java/test/common/java_plugin_info_tests.bzl | 38 +++++++++++++++++++++ java/test/testutil/rules/custom_plugin.bzl | 4 ++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/java/test/common/java_plugin_info_tests.bzl b/java/test/common/java_plugin_info_tests.bzl index fc568414..c8cd28e1 100644 --- a/java/test/common/java_plugin_info_tests.bzl +++ b/java/test/common/java_plugin_info_tests.bzl @@ -141,6 +141,43 @@ def _test_without_processor_class_impl(env, target): assert_api_plugin_data.processor_jars().contains_exactly([]) assert_api_plugin_data.processor_data().contains_exactly([]) +def _test_constructor_with_data_depset(name): + target_name = name + "/plugin" + util.helper_target( + java_library, + name = target_name + "/plugin_dep1", + srcs = ["A.java"], + data = ["depfile1.dat"], + ) + util.helper_target( + custom_plugin, + name = target_name, + processor_class = "com.google.process.stuff", + data = ["pluginfile1.dat"], + deps = [target_name + "/plugin_dep1"], + data_as_depset = True, + ) + + analysis_test( + name = name, + impl = _test_constructor_with_data_depset_impl, + target = target_name, + ) + +def _test_constructor_with_data_depset_impl(env, target): + assert_plugin_data = java_plugin_info_subject.from_target(env, target).plugins() + assert_plugin_data.processor_classes().contains_exactly(["com.google.process.stuff"]) + assert_plugin_data.processor_jars().contains_exactly([ + "{package}/{name}/lib.jar", + "{package}/lib{name}/plugin_dep1.jar", + ]) + assert_plugin_data.processor_data().contains_exactly(["{package}/pluginfile1.dat"]) + + assert_api_plugin_data = java_plugin_info_subject.from_target(env, target).api_generating_plugins() + assert_api_plugin_data.processor_classes().contains_exactly([]) + assert_api_plugin_data.processor_jars().contains_exactly([]) + assert_api_plugin_data.processor_data().contains_exactly([]) + def java_plugin_info_tests(name): test_suite( name = name, @@ -149,5 +186,6 @@ def java_plugin_info_tests(name): _test_provider_contstructor, _test_api_generating_provider_constructor, _test_without_processor_class, + _test_constructor_with_data_depset, ], ) diff --git a/java/test/testutil/rules/custom_plugin.bzl b/java/test/testutil/rules/custom_plugin.bzl index 417cc31c..a9afc66d 100644 --- a/java/test/testutil/rules/custom_plugin.bzl +++ b/java/test/testutil/rules/custom_plugin.bzl @@ -14,10 +14,11 @@ def _impl(ctx): compile_jar = None, deps = [d[JavaInfo] for d in ctx.attr.deps], ) + data = depset(ctx.files.data) if ctx.attr.data_as_depset else ctx.files.data return [JavaPluginInfo( runtime_deps = [dep], processor_class = ctx.attr.processor_class, - data = ctx.files.data, + data = data, generates_api = ctx.attr.generates_api, )] @@ -28,5 +29,6 @@ custom_plugin = rule( "processor_class": attr.string(), "data": attr.label_list(allow_files = True), "generates_api": attr.bool(default = False), + "data_as_depset": attr.bool(default = False), }, ) From 6b5c75940b2b43598d3467e1de8b25c7d07215e2 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 13:38:35 -0700 Subject: [PATCH 201/465] Migrate the `JavaStarlarkApiTest.javaProviderExposedOnJavaLibrary` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738522240 Change-Id: I8f57907a1e339ceaa7f9274e8d6e25841392782d --- java/test/common/rules/java_library_tests.bzl | 28 +++++++++++++++++++ java/test/testutil/rules/wrap_java_info.bzl | 14 ++++++++++ 2 files changed, 42 insertions(+) create mode 100644 java/test/testutil/rules/wrap_java_info.bzl diff --git a/java/test/common/rules/java_library_tests.bzl b/java/test/common/rules/java_library_tests.bzl index fb8c9a7d..a1011bc3 100644 --- a/java/test/common/rules/java_library_tests.bzl +++ b/java/test/common/rules/java_library_tests.bzl @@ -4,7 +4,9 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") +load("//java/common:java_info.bzl", "JavaInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//java/test/testutil:rules/wrap_java_info.bzl", "JavaInfoWrappingInfo", "java_info_wrapping_rule") def _test_exposes_plugins(name): target_name = name + "/library" @@ -77,10 +79,36 @@ def _test_exposes_plugins_impl(env, target): ]) assert_api_plugin_data.processor_data().contains_exactly(["{package}/pluginfile2.dat"]) +def _test_exposes_java_info(name): + util.helper_target( + java_library, + name = name + "/jl", + srcs = ["java/A.java"], + ) + util.helper_target( + java_info_wrapping_rule, + name = name + "/r", + dep = name + "/jl", + ) + analysis_test( + name = name, + impl = _test_exposes_java_info_impl, + targets = { + "r": name + "/r", + "jl": name + "/jl", + }, + ) + +def _test_exposes_java_info_impl(env, targets): + env.expect.that_bool( + targets.r[JavaInfoWrappingInfo].p == targets.jl[JavaInfo], + ).equals(True) + def java_library_tests(name): test_suite( name = name, tests = [ _test_exposes_plugins, + _test_exposes_java_info, ], ) diff --git a/java/test/testutil/rules/wrap_java_info.bzl b/java/test/testutil/rules/wrap_java_info.bzl new file mode 100644 index 00000000..ba78d500 --- /dev/null +++ b/java/test/testutil/rules/wrap_java_info.bzl @@ -0,0 +1,14 @@ +"""Custom rule to test wrapping of the JavaInfo provider""" + +load("//java/common:java_info.bzl", "JavaInfo") + +JavaInfoWrappingInfo = provider( + "Simple provider to wrap a JavaInfo", + fields = ["p"], +) + +def _impl(ctx): + dep_params = ctx.attr.dep[JavaInfo] + return [JavaInfoWrappingInfo(p = dep_params)] + +java_info_wrapping_rule = rule(_impl, attrs = {"dep": attr.label()}) From 65073f1d6b91d29a5184214988a3d984025c96f1 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 14:14:04 -0700 Subject: [PATCH 202/465] Migrate the `JavaStarlarkApiTest.javaProviderPropagation` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738535472 Change-Id: I9103e2228072bb0ab3e4c93f8c1bf6c0b7f74d3d --- java/test/common/rules/java_library_tests.bzl | 50 +++++++++++++++++++ .../test/testutil/rules/forward_java_info.bzl | 9 ++++ 2 files changed, 59 insertions(+) create mode 100644 java/test/testutil/rules/forward_java_info.bzl diff --git a/java/test/common/rules/java_library_tests.bzl b/java/test/common/rules/java_library_tests.bzl index a1011bc3..b0249640 100644 --- a/java/test/common/rules/java_library_tests.bzl +++ b/java/test/common/rules/java_library_tests.bzl @@ -6,6 +6,7 @@ load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//java/test/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") load("//java/test/testutil:rules/wrap_java_info.bzl", "JavaInfoWrappingInfo", "java_info_wrapping_rule") def _test_exposes_plugins(name): @@ -104,11 +105,60 @@ def _test_exposes_java_info_impl(env, targets): targets.r[JavaInfoWrappingInfo].p == targets.jl[JavaInfo], ).equals(True) +def _test_java_info_propagation(name): + util.helper_target( + java_library, + name = name + "/jl", + srcs = ["java/A.java"], + ) + util.helper_target( + java_info_forwarding_rule, + name = name + "/r", + dep = name + "/jl", + ) + util.helper_target( + java_library, + name = name + "/jl_top", + srcs = ["java/C.java"], + deps = [name + "/r"], + ) + + analysis_test( + name = name, + impl = _test_java_info_propagation_impl, + targets = { + "r": name + "/r", + "jl": name + "/jl", + "jl_top": name + "/jl_top", + }, + ) + +def _test_java_info_propagation_impl(env, targets): + env.expect.that_bool(targets.r[JavaInfo] == targets.jl[JavaInfo]).equals(True) + _assert_depsets_have_the_same_parent( + env, + targets.jl[JavaInfo].transitive_compile_time_jars, + targets.jl_top[JavaInfo].transitive_compile_time_jars, + ) + _assert_depsets_have_the_same_parent( + env, + targets.jl[JavaInfo].transitive_runtime_jars, + targets.jl_top[JavaInfo].transitive_runtime_jars, + ) + +def _assert_depsets_have_the_same_parent(env, depset1, depset2): + elements = depset1.to_list() + other_elements = depset2.to_list() + + for e, other_e in zip(elements, other_elements): + env.expect.that_str(e.dirname).equals(other_e.dirname) + def java_library_tests(name): test_suite( name = name, tests = [ _test_exposes_plugins, _test_exposes_java_info, + _test_java_info_propagation, ], ) diff --git a/java/test/testutil/rules/forward_java_info.bzl b/java/test/testutil/rules/forward_java_info.bzl new file mode 100644 index 00000000..6e05bfe0 --- /dev/null +++ b/java/test/testutil/rules/forward_java_info.bzl @@ -0,0 +1,9 @@ +"""Custom rule to forward a JavaInfo""" + +load("//java/common:java_info.bzl", "JavaInfo") + +def _impl(ctx): + dep_params = ctx.attr.dep[JavaInfo] + return [dep_params] + +java_info_forwarding_rule = rule(_impl, attrs = {"dep": attr.label()}) From f33e9351a65aa3e0476b48617f0d063c0693ce30 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 14:47:21 -0700 Subject: [PATCH 203/465] Migrate the `JavaStarlarkApiTest.starlarkJavaToJavaLibraryAttributes` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738547348 Change-Id: Ic2c7764323821b192f022625437a375bc104d0dc --- java/test/common/rules/java_library_tests.bzl | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/java/test/common/rules/java_library_tests.bzl b/java/test/common/rules/java_library_tests.bzl index b0249640..e9c9b4e0 100644 --- a/java/test/common/rules/java_library_tests.bzl +++ b/java/test/common/rules/java_library_tests.bzl @@ -1,6 +1,7 @@ """Tests for the java_library rule""" load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") @@ -153,6 +154,80 @@ def _assert_depsets_have_the_same_parent(env, depset1, depset2): for e, other_e in zip(elements, other_elements): env.expect.that_str(e.dirname).equals(other_e.dirname) +def _test_java_library_attributes(name): + util.helper_target( + java_library, + name = name + "/jl_bottom_for_deps", + srcs = ["java/A.java"], + ) + util.helper_target( + java_library, + name = name + "/jl_bottom_for_exports", + srcs = ["java/A2.java"], + ) + util.helper_target( + java_library, + name = name + "/jl_bottom_for_runtime_deps", + srcs = ["java/A2.java"], + ) + util.helper_target( + java_info_forwarding_rule, + name = name + "/mya", + dep = name + "/jl_bottom_for_deps", + ) + util.helper_target( + java_info_forwarding_rule, + name = name + "/myb", + dep = name + "/jl_bottom_for_exports", + ) + util.helper_target( + java_info_forwarding_rule, + name = name + "/myc", + dep = name + "/jl_bottom_for_runtime_deps", + ) + util.helper_target( + java_library, + name = name + "/lib_exports", + srcs = ["java/B.java"], + exports = [name + "/myb"], + runtime_deps = [name + "/myc"], + deps = [name + "/mya"], + ) + util.helper_target( + java_library, + name = name + "/lib_interm", + srcs = ["java/C.java"], + deps = [name + "/lib_exports"], + ) + util.helper_target( + java_library, + name = name + "/lib_top", + srcs = ["java/D.java"], + deps = [name + "/lib_interm"], + ) + + analysis_test( + name = name, + impl = _test_java_library_attributes_impl, + targets = { + "exports": name + "/lib_exports", + "interm": name + "/lib_interm", + }, + ) + +def _test_java_library_attributes_impl(env, targets): + # all bottom jars are on the runtime classpath of lib_exports. + java_info_subject.from_target(env, targets.exports).compilation_args().transitive_runtime_jars().contains_at_least_predicates([ + matching.file_basename_equals("jl_bottom_for_deps.jar"), + matching.file_basename_equals("jl_bottom_for_runtime_deps.jar"), + matching.file_basename_equals("jl_bottom_for_exports.jar"), + ]) + + # jl_bottom_for_exports.jar is in the recursive java compilation args of lib_top. + java_info_subject.from_target(env, targets.interm).compilation_args().transitive_runtime_jars().contains_predicate( + matching.file_basename_equals("jl_bottom_for_exports.jar"), + ) + def java_library_tests(name): test_suite( name = name, @@ -160,5 +235,6 @@ def java_library_tests(name): _test_exposes_plugins, _test_exposes_java_info, _test_java_info_propagation, + _test_java_library_attributes, ], ) From e8c3e6d09a62e5ffd88797a469a768efb0e31b73 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 16:11:06 -0700 Subject: [PATCH 204/465] Migrate the `JavaStarlarkApiTest.starlarkJavaToJavaBinaryAttributes` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738576515 Change-Id: Id4ccc84502d327921669adeea0207b67e19f367e --- java/test/common/rules/java_binary_tests.bzl | 48 ++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/java/test/common/rules/java_binary_tests.bzl b/java/test/common/rules/java_binary_tests.bzl index 2a8f0343..3b763f99 100644 --- a/java/test/common/rules/java_binary_tests.bzl +++ b/java/test/common/rules/java_binary_tests.bzl @@ -4,7 +4,9 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") +load("//java:java_library.bzl", "java_library") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//java/test/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") def _test_java_binary_provides_binary_java_info(name): util.helper_target(java_binary, name = "bin", srcs = ["Main.java"]) @@ -53,11 +55,57 @@ def _test_stamp_conversion_does_not_override_int_impl(env, target): matching.file_basename_equals("redacted_file.properties"), ) +def _test_java_binary_attributes(name): + util.helper_target( + java_library, + name = name + "/jl_bottom_for_deps", + srcs = ["java/A.java"], + ) + util.helper_target( + java_library, + name = name + "/jl_bottom_for_runtime_deps", + srcs = ["java/A2.java"], + ) + util.helper_target( + java_info_forwarding_rule, + name = name + "/mya", + dep = name + "/jl_bottom_for_deps", + ) + util.helper_target( + java_info_forwarding_rule, + name = name + "/myb", + dep = name + "/jl_bottom_for_runtime_deps", + ) + util.helper_target( + java_binary, + name = name + "/binary", + srcs = ["java/B.java"], + main_class = "foo.A", + deps = [name + "/mya"], + runtime_deps = [name + "/myb"], + ) + + analysis_test( + name = name, + impl = _test_java_binary_attributes_impl, + target = name + "/binary", + ) + +def _test_java_binary_attributes_impl(env, target): + assert_runtime_classpath = java_info_subject.from_target(env, target).compilation_info().runtime_classpath() + + # Test that all bottom jars are on the runtime classpath. + assert_runtime_classpath.contains_at_least_predicates([ + matching.file_basename_equals("jl_bottom_for_deps.jar"), + matching.file_basename_equals("jl_bottom_for_runtime_deps.jar"), + ]) + def java_binary_tests(name): test_suite( name = name, tests = [ _test_java_binary_provides_binary_java_info, _test_stamp_conversion_does_not_override_int, + _test_java_binary_attributes, ], ) From ff84f5dd6ea71125d688e80725a210e8eade1e84 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 17:56:56 -0700 Subject: [PATCH 205/465] Migrate the `JavaStarlarkApiTest.starlarkJavaToJavaImportAttributes` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738605511 Change-Id: If27e7c863f45b5853a57ad1cabeb21a198d58244 --- java/test/common/rules/BUILD | 3 + java/test/common/rules/java_import_tests.bzl | 62 ++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 java/test/common/rules/java_import_tests.bzl diff --git a/java/test/common/rules/BUILD b/java/test/common/rules/BUILD index e46aa944..0639d292 100644 --- a/java/test/common/rules/BUILD +++ b/java/test/common/rules/BUILD @@ -1,4 +1,5 @@ load(":java_binary_tests.bzl", "java_binary_tests") +load(":java_import_tests.bzl", "java_import_tests") load(":java_library_tests.bzl", "java_library_tests") load(":java_plugin_tests.bzl", "java_plugin_tests") load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") @@ -10,3 +11,5 @@ java_binary_tests(name = "java_binary_tests") java_plugin_tests(name = "java_plugin_tests") java_library_tests(name = "java_library_tests") + +java_import_tests(name = "java_import_tests") diff --git a/java/test/common/rules/java_import_tests.bzl b/java/test/common/rules/java_import_tests.bzl new file mode 100644 index 00000000..ca54e7fe --- /dev/null +++ b/java/test/common/rules/java_import_tests.bzl @@ -0,0 +1,62 @@ +"""Tests for the java_import rule""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_import.bzl", "java_import") +load("//java:java_library.bzl", "java_library") +load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//java/test/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") + +def _test_java_import_attributes(name): + target_name = name + "/import" + util.helper_target( + java_library, + name = target_name + "/jl_bottom_for_deps", + srcs = ["java/A.java"], + ) + util.helper_target( + java_library, + name = target_name + "/jl_bottom_for_runtime_deps", + srcs = ["java/A2.java"], + ) + util.helper_target( + java_info_forwarding_rule, + name = target_name + "/mya", + dep = target_name + "/jl_bottom_for_deps", + ) + util.helper_target( + java_info_forwarding_rule, + name = target_name + "/myb", + dep = target_name + "/jl_bottom_for_runtime_deps", + ) + util.helper_target( + java_import, + name = target_name, + jars = ["B.jar"], + runtime_deps = [target_name + "/myb"], + deps = [target_name + "/mya"], + ) + + analysis_test( + name = name, + impl = _test_java_import_attributes_impl, + target = target_name, + ) + +def _test_java_import_attributes_impl(env, target): + assert_runtime_jars = java_info_subject.from_target(env, target).compilation_args().transitive_runtime_jars() + + # Test that all bottom jars are on the runtime classpath. + assert_runtime_jars.contains_at_least_predicates([ + matching.file_basename_equals("jl_bottom_for_deps.jar"), + matching.file_basename_equals("jl_bottom_for_runtime_deps.jar"), + ]) + +def java_import_tests(name): + test_suite( + name = name, + tests = [ + _test_java_import_attributes, + ], + ) From 9c39eff0341b1d6aa6178a23cea0fb656d2d4536 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 19 Mar 2025 20:54:56 -0700 Subject: [PATCH 206/465] Migrate the `JavaStarlarkApiTest.testJavaInfoSequenceParametersTypeChecked` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738648817 Change-Id: I5f5a286298d79422249207a4dc77fd445e60d290 --- java/test/common/java_info_tests.bzl | 34 +++++++++++++++++++ .../testutil/rules/bad_java_info_rules.bzl | 29 ++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 java/test/testutil/rules/bad_java_info_rules.bzl diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 2663f528..21d7a6d9 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -7,6 +7,7 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//java/test/testutil:rules/bad_java_info_rules.bzl", "bad_deps", "bad_exports", "bad_libs", "bad_runtime_deps") load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") def _with_output_jar_only_test(name): @@ -862,6 +863,38 @@ def _with_manifest_proto_test_impl(env, target): "{package}/manifest.proto", ]) +def _sequence_parameters_are_type_checked_test(name): + util.helper_target(bad_deps, name = name + "/bad_deps") + util.helper_target(bad_runtime_deps, name = name + "/bad_runtime_deps") + util.helper_target(bad_exports, name = name + "/bad_exports") + util.helper_target(bad_libs, name = name + "/bad_libs") + + analysis_test( + name = name, + impl = _sequence_parameters_are_type_checked_test_impl, + targets = { + "deps": name + "/bad_deps", + "runtime_deps": name + "/bad_runtime_deps", + "exports": name + "/bad_exports", + "libs": name + "/bad_libs", + }, + expect_failure = True, + ) + +def _sequence_parameters_are_type_checked_test_impl(env, targets): + env.expect.that_target(targets.deps).failures().contains_predicate( + matching.str_matches("at index 0 of deps, got element of type File, want JavaInfo"), + ) + env.expect.that_target(targets.runtime_deps).failures().contains_predicate( + matching.str_matches("at index 0 of runtime_deps, got element of type File, want JavaInfo"), + ) + env.expect.that_target(targets.exports).failures().contains_predicate( + matching.str_matches("at index 0 of exports, got element of type File, want JavaInfo"), + ) + env.expect.that_target(targets.libs).failures().contains_predicate( + matching.str_matches("at index 0 of native_libraries, got element of type File, want CcInfo"), + ) + def java_info_tests(name): test_suite( name = name, @@ -893,5 +926,6 @@ def java_info_tests(name): _with_compile_jdeps_test, _with_native_headers_test, _with_manifest_proto_test, + _sequence_parameters_are_type_checked_test, ], ) diff --git a/java/test/testutil/rules/bad_java_info_rules.bzl b/java/test/testutil/rules/bad_java_info_rules.bzl new file mode 100644 index 00000000..f486cbd7 --- /dev/null +++ b/java/test/testutil/rules/bad_java_info_rules.bzl @@ -0,0 +1,29 @@ +"""Helper rules to test errors in JavaInfo instantiation""" + +load("//java/common:java_info.bzl", "JavaInfo") + +def _make_file(ctx): + f = ctx.actions.declare_file(ctx.label.name + ".out") + ctx.actions.write(f, "out") + return f + +def _deps_impl(ctx): + f = _make_file(ctx) + return JavaInfo(output_jar = f, compile_jar = f, deps = [f]) + +def _runtime_deps_impl(ctx): + f = _make_file(ctx) + return JavaInfo(output_jar = f, compile_jar = f, runtime_deps = [f]) + +def _exports_impl(ctx): + f = _make_file(ctx) + return JavaInfo(output_jar = f, compile_jar = f, exports = [f]) + +def _nativelibs_impl(ctx): + f = _make_file(ctx) + return JavaInfo(output_jar = f, compile_jar = f, native_libraries = [f]) + +bad_deps = rule(_deps_impl) +bad_runtime_deps = rule(_runtime_deps_impl) +bad_exports = rule(_exports_impl) +bad_libs = rule(_nativelibs_impl) From e5bf455f50ec7866480865bb14e2887c8e0ce1e1 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Thu, 20 Mar 2025 02:29:12 -0700 Subject: [PATCH 207/465] Update JDKs to latest patch versions (#281) Closes #281 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/281 from fmeum:update-jdks 19fc54925cc215801e5daa566fca11a8334ae71c PiperOrigin-RevId: 738723138 Change-Id: I891cee44bffa85e464372994b749fa9844b699b6 --- java/bazel/BUILD.bazel | 2 +- java/bazel/repositories_util.bzl | 18 ++-- java/repositories.bzl | 180 +++++++++++++++---------------- 3 files changed, 100 insertions(+), 100 deletions(-) diff --git a/java/bazel/BUILD.bazel b/java/bazel/BUILD.bazel index 2c26d110..bc61f061 100644 --- a/java/bazel/BUILD.bazel +++ b/java/bazel/BUILD.bazel @@ -27,7 +27,7 @@ while read -r config; do TMP_FILE=$$(mktemp -q /tmp/remotejdk.XXXXXX) IFS=\\| read -r name version urls strip_prefix target_compatible_with primary_url <<< "$$config" echo "fetching: $$primary_url to $$TMP_FILE" > /dev/stderr - curl --silent -o $$TMP_FILE -L "$$primary_url" > /dev/stderr + curl --silent --fail -o $$TMP_FILE -L "$$primary_url" > /dev/stderr sha256=`sha256sum $$TMP_FILE | cut -d' ' -f1` echo "struct(" echo " name = \\"$$name\\"," diff --git a/java/bazel/repositories_util.bzl b/java/bazel/repositories_util.bzl index fce641dc..efe72be1 100644 --- a/java/bazel/repositories_util.bzl +++ b/java/bazel/repositories_util.bzl @@ -18,7 +18,7 @@ visibility(["//test"]) _RELEASE_CONFIGS = { "8": { "zulu": { - "release": "8.78.0.19-ca-jdk8.0.412", + "release": "8.84.0.15-ca-jdk8.0.442", "platforms": { "linux": ["aarch64", "x86_64"], "macos": ["aarch64", "x86_64"], @@ -34,7 +34,7 @@ _RELEASE_CONFIGS = { }, "11": { "zulu": { - "release": "11.72.19-ca-jdk11.0.23", + "release": "11.78.15-ca-jdk11.0.26", "platforms": { "linux": ["aarch64", "x86_64"], "macos": ["aarch64", "x86_64"], @@ -42,13 +42,13 @@ _RELEASE_CONFIGS = { }, }, "adoptium": { - "release": "11.0.15+10", + "release": "11.0.26+4", "platforms": { "linux": ["ppc", "s390x"], }, }, "microsoft": { - "release": "11.0.13.8.1", + "release": "11.0.26", "platforms": { "windows": ["arm64"], }, @@ -56,7 +56,7 @@ _RELEASE_CONFIGS = { }, "17": { "zulu": { - "release": "17.50.19-ca-jdk17.0.11", + "release": "17.56.15-ca-jdk17.0.14", "platforms": { "linux": ["aarch64", "x86_64"], "macos": ["aarch64", "x86_64"], @@ -64,7 +64,7 @@ _RELEASE_CONFIGS = { }, }, "adoptium": { - "release": "17.0.8.1+1", + "release": "17.0.14+7", "platforms": { "linux": ["ppc", "s390x"], }, @@ -72,7 +72,7 @@ _RELEASE_CONFIGS = { }, "21": { "zulu": { - "release": "21.36.17-ca-jdk21.0.4", + "release": "21.40.17-ca-jdk21.0.6", "platforms": { "linux": ["aarch64", "x86_64"], "macos": ["aarch64", "x86_64"], @@ -80,7 +80,7 @@ _RELEASE_CONFIGS = { }, }, "adoptium": { - "release": "21.0.4+7", + "release": "21.0.6+7", "platforms": { "linux": ["ppc", "riscv64", "s390x"], }, @@ -89,7 +89,7 @@ _RELEASE_CONFIGS = { } _STRIP_PREFIX_OVERRIDES = { - "remotejdk11_win_arm64": "jdk-11.0.13+8", + "remotejdk11_win_arm64": "jdk-11.0.26+4", } def _name_for_remote_jdk(version, os, cpu): diff --git a/java/repositories.bzl b/java/repositories.bzl index 9ebb660d..952b9f2f 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -80,41 +80,41 @@ _REMOTE_JDK_CONFIGS_LIST = [ struct( name = "remote_jdk8_linux_aarch64", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"], - sha256 = "82c46c65d57e187ef68fdd125ef760eaeb52ebfe1be1a6a251cf5b43cbebc78a", - strip_prefix = "zulu8.78.0.19-ca-jdk8.0.412-linux_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu8.78.0.19-ca-jdk8.0.412-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.78.0.19-ca-jdk8.0.412-linux_aarch64.tar.gz"], + sha256 = "3ae6b27727a308c0c262a99e20af29c87aad7910de423db2607c44551b598e57", + strip_prefix = "zulu8.84.0.15-ca-jdk8.0.442-linux_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-linux_aarch64.tar.gz"], version = "8", ), struct( name = "remote_jdk8_linux", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"], - sha256 = "9c0ac5ebffa61520fee78ead52add0f4edd3b1b54b01b6a17429b719515caf90", - strip_prefix = "zulu8.78.0.19-ca-jdk8.0.412-linux_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu8.78.0.19-ca-jdk8.0.412-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.78.0.19-ca-jdk8.0.412-linux_x64.tar.gz"], + sha256 = "6e3bd4d911e6eb2d14e0b48e622b6909c76add0b51c51d11f5c2c3d2a045bcf3", + strip_prefix = "zulu8.84.0.15-ca-jdk8.0.442-linux_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-linux_x64.tar.gz"], version = "8", ), struct( name = "remote_jdk8_macos_aarch64", target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"], - sha256 = "35bc35808379400e4a70e1f7ee379778881799b93c2cc9fe1ae515c03c2fb057", - strip_prefix = "zulu8.78.0.19-ca-jdk8.0.412-macosx_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu8.78.0.19-ca-jdk8.0.412-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.78.0.19-ca-jdk8.0.412-macosx_aarch64.tar.gz"], + sha256 = "effa6d1bd4b6bce68328df66e063a97c2c4afeb0aa36fda4f85c434dd8246572", + strip_prefix = "zulu8.84.0.15-ca-jdk8.0.442-macosx_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-macosx_aarch64.tar.gz"], version = "8", ), struct( name = "remote_jdk8_macos", target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"], - sha256 = "2bfa0506196962bddb21a604eaa2b0b39eaf3383d0bdad08bdbe7f42f25d8928", - strip_prefix = "zulu8.78.0.19-ca-jdk8.0.412-macosx_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu8.78.0.19-ca-jdk8.0.412-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.78.0.19-ca-jdk8.0.412-macosx_x64.tar.gz"], + sha256 = "52131294512042dd6356426202e6a4116536477281fe76cfc0a3a15fe0d6ff44", + strip_prefix = "zulu8.84.0.15-ca-jdk8.0.442-macosx_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-macosx_x64.tar.gz"], version = "8", ), struct( name = "remote_jdk8_windows", target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"], - sha256 = "ca5499c301d5b42604d8535b8c40a7f928a796247b8c66a600333dd799798ff7", - strip_prefix = "zulu8.78.0.19-ca-jdk8.0.412-win_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu8.78.0.19-ca-jdk8.0.412-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.78.0.19-ca-jdk8.0.412-win_x64.zip"], + sha256 = "551c0df372a4b01754e214c52d2bdc2e22e1582274a3ea0e4a27d77db6a9cbea", + strip_prefix = "zulu8.84.0.15-ca-jdk8.0.442-win_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-win_x64.zip"], version = "8", ), struct( @@ -128,201 +128,201 @@ _REMOTE_JDK_CONFIGS_LIST = [ struct( name = "remotejdk11_linux_aarch64", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"], - sha256 = "be7d7574253c893eb58f66e985c75adf48558c41885827d1f02f827e109530e0", - strip_prefix = "zulu11.72.19-ca-jdk11.0.23-linux_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu11.72.19-ca-jdk11.0.23-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.72.19-ca-jdk11.0.23-linux_aarch64.tar.gz"], + sha256 = "f221d794325ab04382ba52250fc8fe8c4d384841a63bc2acd62d623a5bc53eb7", + strip_prefix = "zulu11.78.15-ca-jdk11.0.26-linux_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-linux_aarch64.tar.gz"], version = "11", ), struct( name = "remotejdk11_linux", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"], - sha256 = "0a4d1bfc7a96a7f9f5329b72b9801b3c53366417b4753f1b658fa240204c7347", - strip_prefix = "zulu11.72.19-ca-jdk11.0.23-linux_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu11.72.19-ca-jdk11.0.23-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.72.19-ca-jdk11.0.23-linux_x64.tar.gz"], + sha256 = "fdf95b001d50b03bc3ce5f4fe7dc96bec9f94e561f9ec722a149bd7995600449", + strip_prefix = "zulu11.78.15-ca-jdk11.0.26-linux_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-linux_x64.tar.gz"], version = "11", ), struct( name = "remotejdk11_macos_aarch64", target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"], - sha256 = "40fb1918385e03814b67b7608c908c7f945ccbeddbbf5ed062cdfb2602e21c83", - strip_prefix = "zulu11.72.19-ca-jdk11.0.23-macosx_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu11.72.19-ca-jdk11.0.23-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.72.19-ca-jdk11.0.23-macosx_aarch64.tar.gz"], + sha256 = "3708badcc0c79fc1791e74b62478188a1f43c4f9a1e7d3e1bd4173da995479a3", + strip_prefix = "zulu11.78.15-ca-jdk11.0.26-macosx_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-macosx_aarch64.tar.gz"], version = "11", ), struct( name = "remotejdk11_macos", target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"], - sha256 = "e5b19b82045826ae09c9d17742691bc9e40312c44be7bd7598ae418a3d4edb1c", - strip_prefix = "zulu11.72.19-ca-jdk11.0.23-macosx_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu11.72.19-ca-jdk11.0.23-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.72.19-ca-jdk11.0.23-macosx_x64.tar.gz"], + sha256 = "bb3884619c6f09ec5ca3ce43810c61ade647bb896f4120a6cf076ec993b5a1a0", + strip_prefix = "zulu11.78.15-ca-jdk11.0.26-macosx_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-macosx_x64.tar.gz"], version = "11", ), struct( name = "remotejdk11_win", target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"], - sha256 = "1295b2affe498018c45f6f15187b58c4456d51dce5eb608ee73ef7665d4566d2", - strip_prefix = "zulu11.72.19-ca-jdk11.0.23-win_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu11.72.19-ca-jdk11.0.23-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.72.19-ca-jdk11.0.23-win_x64.zip"], + sha256 = "2f48346ba05d0d1a31a6797cd0fd27a0492c0df0c90730c9eeca7fc6952a075c", + strip_prefix = "zulu11.78.15-ca-jdk11.0.26-win_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-win_x64.zip"], version = "11", ), struct( name = "remotejdk11_linux_ppc64le", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc"], - sha256 = "a8fba686f6eb8ae1d1a9566821dbd5a85a1108b96ad857fdbac5c1e4649fc56f", - strip_prefix = "jdk-11.0.15+10", - urls = ["https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.15+10/OpenJDK11U-jdk_ppc64le_linux_hotspot_11.0.15_10.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.15+10/OpenJDK11U-jdk_ppc64le_linux_hotspot_11.0.15_10.tar.gz"], + sha256 = "42c63651125a149cee2ba781300d75ffa67a25032f95038d50ee6d6177cb2e41", + strip_prefix = "jdk-11.0.26+4", + urls = ["https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.26+4/OpenJDK11U-jdk_ppc64le_linux_hotspot_11.0.26_4.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.26+4/OpenJDK11U-jdk_ppc64le_linux_hotspot_11.0.26_4.tar.gz"], version = "11", ), struct( name = "remotejdk11_linux_s390x", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:s390x"], - sha256 = "a58fc0361966af0a5d5a31a2d8a208e3c9bb0f54f345596fd80b99ea9a39788b", - strip_prefix = "jdk-11.0.15+10", - urls = ["https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.15+10/OpenJDK11U-jdk_s390x_linux_hotspot_11.0.15_10.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.15+10/OpenJDK11U-jdk_s390x_linux_hotspot_11.0.15_10.tar.gz"], + sha256 = "0da13d990da34ecc666399cf0efa72a4b4e295f05c0686ea25a4a173a6f4414b", + strip_prefix = "jdk-11.0.26+4", + urls = ["https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.26+4/OpenJDK11U-jdk_s390x_linux_hotspot_11.0.26_4.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.26+4/OpenJDK11U-jdk_s390x_linux_hotspot_11.0.26_4.tar.gz"], version = "11", ), struct( name = "remotejdk11_win_arm64", target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"], - sha256 = "b8a28e6e767d90acf793ea6f5bed0bb595ba0ba5ebdf8b99f395266161e53ec2", - strip_prefix = "jdk-11.0.13+8", - urls = ["https://aka.ms/download-jdk/microsoft-jdk-11.0.13.8.1-windows-aarch64.zip", "https://mirror.bazel.build/aka.ms/download-jdk/microsoft-jdk-11.0.13.8.1-windows-aarch64.zip"], + sha256 = "1d10cf760e4e011e830ef18ab28453a742ac84c046e4e77759e81b58716e6a8b", + strip_prefix = "jdk-11.0.26+4", + urls = ["https://aka.ms/download-jdk/microsoft-jdk-11.0.26-windows-aarch64.zip", "https://mirror.bazel.build/aka.ms/download-jdk/microsoft-jdk-11.0.26-windows-aarch64.zip"], version = "11", ), struct( name = "remotejdk17_linux_aarch64", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"], - sha256 = "518cc455c0c7b49c0ae7d809c0bb87ab371bb850d46abb8efad5010c6a06faec", - strip_prefix = "zulu17.50.19-ca-jdk17.0.11-linux_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu17.50.19-ca-jdk17.0.11-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.50.19-ca-jdk17.0.11-linux_aarch64.tar.gz"], + sha256 = "9fe5d08b20546e84af517cfefc7068f7a47e98473603782264e519f935977cb3", + strip_prefix = "zulu17.56.15-ca-jdk17.0.14-linux_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-linux_aarch64.tar.gz"], version = "17", ), struct( name = "remotejdk17_linux", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"], - sha256 = "a1e8ac9ae5804b84dc07cf9d8ebe1b18247d70c92c1e0de97ea10109563f4379", - strip_prefix = "zulu17.50.19-ca-jdk17.0.11-linux_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu17.50.19-ca-jdk17.0.11-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.50.19-ca-jdk17.0.11-linux_x64.tar.gz"], + sha256 = "37ab75b2f5da0ff0db973b31e9d9f14f729137a0a110abd6472ac8c6f2feabb6", + strip_prefix = "zulu17.56.15-ca-jdk17.0.14-linux_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-linux_x64.tar.gz"], version = "17", ), struct( name = "remotejdk17_macos_aarch64", target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"], - sha256 = "dd1a82d57e80cdefb045066e5c28b5bd41e57eea9c57303ec7e012b57230bb9c", - strip_prefix = "zulu17.50.19-ca-jdk17.0.11-macosx_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu17.50.19-ca-jdk17.0.11-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.50.19-ca-jdk17.0.11-macosx_aarch64.tar.gz"], + sha256 = "c3b9bfb0a6dbe4c5d9efce6c46d3a89c92d7b07ba1bd0afc944612298ac284ec", + strip_prefix = "zulu17.56.15-ca-jdk17.0.14-macosx_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-macosx_aarch64.tar.gz"], version = "17", ), struct( name = "remotejdk17_macos", target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"], - sha256 = "b384991e93af39abe5229c7f5efbe912a7c5a6480674a6e773f3a9128f96a764", - strip_prefix = "zulu17.50.19-ca-jdk17.0.11-macosx_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu17.50.19-ca-jdk17.0.11-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.50.19-ca-jdk17.0.11-macosx_x64.tar.gz"], + sha256 = "ee1a55b6b63d62d1a24d420b1550ef1736fda36db0e612893d9d26eb1d7f1611", + strip_prefix = "zulu17.56.15-ca-jdk17.0.14-macosx_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-macosx_x64.tar.gz"], version = "17", ), struct( name = "remotejdk17_win_arm64", target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"], - sha256 = "b8833d272eb31f54f8c881139807a28a74de9deae07d2cc37688ff72043e32c9", - strip_prefix = "zulu17.50.19-ca-jdk17.0.11-win_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu17.50.19-ca-jdk17.0.11-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.50.19-ca-jdk17.0.11-win_aarch64.zip"], + sha256 = "dbf51756115f7591759b2ed6d9c0d79b3b770c1a13be476c99d64934a93ff422", + strip_prefix = "zulu17.56.15-ca-jdk17.0.14-win_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-win_aarch64.zip"], version = "17", ), struct( name = "remotejdk17_win", target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"], - sha256 = "43f0f1bdecf48ba9763d46ee7784554c95b442ffdd39ebd62dc8b297cc82e116", - strip_prefix = "zulu17.50.19-ca-jdk17.0.11-win_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu17.50.19-ca-jdk17.0.11-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.50.19-ca-jdk17.0.11-win_x64.zip"], + sha256 = "11dbe0051cea65fbfc94e0074fbb26d81897f5aff2df69fed3784f380d0d9ec9", + strip_prefix = "zulu17.56.15-ca-jdk17.0.14-win_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-win_x64.zip"], version = "17", ), struct( name = "remotejdk17_linux_ppc64le", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc"], - sha256 = "00a4c07603d0218cd678461b5b3b7e25b3253102da4022d31fc35907f21a2efd", - strip_prefix = "jdk-17.0.8.1+1", - urls = ["https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.8.1+1/OpenJDK17U-jdk_ppc64le_linux_hotspot_17.0.8.1_1.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.8.1+1/OpenJDK17U-jdk_ppc64le_linux_hotspot_17.0.8.1_1.tar.gz"], + sha256 = "f4cb9ee5906a44d110fa381310cd7181d95498d27087d449e7e9b74bddd9def2", + strip_prefix = "jdk-17.0.14+7", + urls = ["https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14+7/OpenJDK17U-jdk_ppc64le_linux_hotspot_17.0.14_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14+7/OpenJDK17U-jdk_ppc64le_linux_hotspot_17.0.14_7.tar.gz"], version = "17", ), struct( name = "remotejdk17_linux_s390x", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:s390x"], - sha256 = "ffacba69c6843d7ca70d572489d6cc7ab7ae52c60f0852cedf4cf0d248b6fc37", - strip_prefix = "jdk-17.0.8.1+1", - urls = ["https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.8.1+1/OpenJDK17U-jdk_s390x_linux_hotspot_17.0.8.1_1.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.8.1+1/OpenJDK17U-jdk_s390x_linux_hotspot_17.0.8.1_1.tar.gz"], + sha256 = "3a1d896eb3a737020e5ec95ec3206b1ca36cb365538382289d3fb46d14303648", + strip_prefix = "jdk-17.0.14+7", + urls = ["https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14+7/OpenJDK17U-jdk_s390x_linux_hotspot_17.0.14_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14+7/OpenJDK17U-jdk_s390x_linux_hotspot_17.0.14_7.tar.gz"], version = "17", ), struct( name = "remotejdk21_linux_aarch64", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"], - sha256 = "da3c2d7db33670bcf66532441aeb7f33dcf0d227c8dafe7ce35cee67f6829c4c", - strip_prefix = "zulu21.36.17-ca-jdk21.0.4-linux_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-linux_aarch64.tar.gz"], + sha256 = "2cab003bad25100a00b818ce229455d35ece03fc2e69be32c9c1c03f90b2eb89", + strip_prefix = "zulu21.40.17-ca-jdk21.0.6-linux_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-linux_aarch64.tar.gz"], version = "21", ), struct( name = "remotejdk21_linux", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"], - sha256 = "318d0c2ed3c876fb7ea2c952945cdcf7decfb5264ca51aece159e635ac53d544", - strip_prefix = "zulu21.36.17-ca-jdk21.0.4-linux_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-linux_x64.tar.gz"], + sha256 = "5daff61d307d18305a4022c56013cbaa8987a7dd103e310ebbeb75e0f3091a03", + strip_prefix = "zulu21.40.17-ca-jdk21.0.6-linux_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-linux_x64.tar.gz"], version = "21", ), struct( name = "remotejdk21_macos_aarch64", target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"], - sha256 = "bc2750f81a166cc6e9c30ae8aaba54f253a8c8ec9d8cfc04a555fe20712c7bff", - strip_prefix = "zulu21.36.17-ca-jdk21.0.4-macosx_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-macosx_aarch64.tar.gz"], + sha256 = "1d6385f17ae2dc3b57a6d1b6fd6aeadafe1c7138bc744f62a767851eececd092", + strip_prefix = "zulu21.40.17-ca-jdk21.0.6-macosx_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-macosx_aarch64.tar.gz"], version = "21", ), struct( name = "remotejdk21_macos", target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"], - sha256 = "5ce75a6a247c7029b74c4ca7cf6f60fd2b2d68ce1e8956fb448d2984316b5fea", - strip_prefix = "zulu21.36.17-ca-jdk21.0.4-macosx_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-macosx_x64.tar.gz"], + sha256 = "0b0f05e53e2b85f3881f1b8f5e3ef7e2e992796a1872afbc851b73127b16933d", + strip_prefix = "zulu21.40.17-ca-jdk21.0.6-macosx_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-macosx_x64.tar.gz"], version = "21", ), struct( name = "remotejdk21_win_arm64", target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"], - sha256 = "9f873eccf030b1d3dc879ec1eb0ff5e11bf76002dc81c5c644c3462bf6c5146b", - strip_prefix = "zulu21.36.17-ca-jdk21.0.4-win_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-win_aarch64.zip"], + sha256 = "57c568355b97d288f12b720760d802b1a19c55e9b0707a5c2ad76d34fd893db8", + strip_prefix = "zulu21.40.17-ca-jdk21.0.6-win_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-win_aarch64.zip"], version = "21", ), struct( name = "remotejdk21_win", target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"], - sha256 = "d771dad10d3f0b440c3686d1f3d2b68b320802ac97b212d87671af3f2eef8848", - strip_prefix = "zulu21.36.17-ca-jdk21.0.4-win_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.36.17-ca-jdk21.0.4-win_x64.zip"], + sha256 = "a1360d2ab3ee9932b5cb20a2386d6b0fb1518a68c89a08739736c38a4debbdae", + strip_prefix = "zulu21.40.17-ca-jdk21.0.6-win_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-win_x64.zip"], version = "21", ), struct( name = "remotejdk21_linux_ppc64le", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc"], - sha256 = "c208cd0fb90560644a90f928667d2f53bfe408c957a5e36206585ad874427761", - strip_prefix = "jdk-21.0.4+7", - urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.4_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.4_7.tar.gz"], + sha256 = "163724b70b86d5a8461f85092165a9cc5a098ed900fee90d1b0c0be9607ae3d2", + strip_prefix = "jdk-21.0.6+7", + urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.6_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.6_7.tar.gz"], version = "21", ), struct( name = "remotejdk21_linux_riscv64", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:riscv64"], - sha256 = "b04fd7f52d18268a935f1a7144dae802b25db600ec97156ddd46b3100cbd13da", - strip_prefix = "jdk-21.0.4+7", - urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_riscv64_linux_hotspot_21.0.4_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_riscv64_linux_hotspot_21.0.4_7.tar.gz"], + sha256 = "203796e4ba2689aa921b5e0cdc9e02984d88622f80fcb9acb05a118b05007be8", + strip_prefix = "jdk-21.0.6+7", + urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_riscv64_linux_hotspot_21.0.6_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_riscv64_linux_hotspot_21.0.6_7.tar.gz"], version = "21", ), struct( name = "remotejdk21_linux_s390x", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:s390x"], - sha256 = "c900c8d64fab1e53274974fa4a4c736a5a3754485a5c56f4947281480773658a", - strip_prefix = "jdk-21.0.4+7", - urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.4_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.4_7.tar.gz"], + sha256 = "5ba742c87d48fcf564def56812699f6499a1cfd3535ae43286e94e74b8165faf", + strip_prefix = "jdk-21.0.6+7", + urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.6_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.6_7.tar.gz"], version = "21", ), ] From 5a28c39a24c5ae56c5e484dab1b63b7c40c8fad8 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 20 Mar 2025 03:04:15 -0700 Subject: [PATCH 208/465] Migrate the `JavaStarlarkApiTest.javaInfo_compileJarSet` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738731692 Change-Id: I3e99232919846b8c5dc0e0fa5e1f67dd2c14abdb --- java/test/common/java_info_tests.bzl | 22 +++++++++++++++++ .../testutil/rules/custom_java_info_rule.bzl | 24 ++++++++++++------- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 21d7a6d9..57dea2f3 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -6,6 +6,7 @@ load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") +load("//java/common:java_info.bzl", "JavaInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") load("//java/test/testutil:rules/bad_java_info_rules.bzl", "bad_deps", "bad_exports", "bad_libs", "bad_runtime_deps") load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") @@ -895,6 +896,26 @@ def _sequence_parameters_are_type_checked_test_impl(env, targets): matching.str_matches("at index 0 of native_libraries, got element of type File, want CcInfo"), ) +def _with_compile_jar_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + output_jar = target_name + "/output.jar", + compile_jar = "compile.jar", + ) + + analysis_test( + name = name, + impl = _with_compile_jar_test_impl, + target = target_name, + ) + +def _with_compile_jar_test_impl(env, target): + env.expect.that_depset_of_files(target[JavaInfo].compile_jars).contains_predicate( + matching.file_basename_equals("compile.jar"), + ) + def java_info_tests(name): test_suite( name = name, @@ -926,6 +947,7 @@ def java_info_tests(name): _with_compile_jdeps_test, _with_native_headers_test, _with_manifest_proto_test, + _with_compile_jar_test, _sequence_parameters_are_type_checked_test, ], ) diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/java/test/testutil/rules/custom_java_info_rule.bzl index 55086e3e..3b61473a 100644 --- a/java/test/testutil/rules/custom_java_info_rule.bzl +++ b/java/test/testutil/rules/custom_java_info_rule.bzl @@ -7,6 +7,8 @@ load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/common:java_semantics.bzl", "semantics") def _impl(ctx): + if ctx.attr.compile_jar and (ctx.attr.use_ijar or ctx.attr.stamp_jar): + fail("Cannot set use_ijar/stamp_jar if compile_jar is set") if ctx.attr.use_ijar and ctx.attr.stamp_jar: fail("only one of use_ijar or stamp_jar may be set") ctx.actions.write(ctx.outputs.output_jar, "JavaInfo API Test", is_executable = False) @@ -24,18 +26,23 @@ def _impl(ctx): ctx.files.source_jars[0] if ctx.files.source_jars else None ) dp_libs = [dep[CcInfo] for dep in ctx.attr.cc_dep] - compile_jar = java_common.run_ijar( - ctx.actions, - jar = ctx.outputs.output_jar, - java_toolchain = semantics.find_java_toolchain(ctx), - ) if ctx.attr.use_ijar else ( - java_common.stamp_jar( + if ctx.attr.compile_jar: + compile_jar = ctx.file.compile_jar + elif ctx.attr.use_ijar: + compile_jar = java_common.run_ijar( + ctx.actions, + jar = ctx.outputs.output_jar, + java_toolchain = semantics.find_java_toolchain(ctx), + ) + elif ctx.attr.stamp_jar: + compile_jar = java_common.stamp_jar( ctx.actions, jar = ctx.outputs.output_jar, target_label = ctx.label, java_toolchain = semantics.find_java_toolchain(ctx), - ) if ctx.attr.stamp_jar else ctx.outputs.output_jar - ) + ) + else: + compile_jar = ctx.outputs.output_jar return [ JavaInfo( @@ -78,6 +85,7 @@ custom_java_info_rule = rule( "neverlink": attr.bool(default = False), "pack_sources": attr.bool(default = False), "stamp_jar": attr.bool(default = False), + "compile_jar": attr.label(allow_single_file = True), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], ) From 0351b14adb1fdb34461f56716a6878825460d418 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 20 Mar 2025 03:18:55 -0700 Subject: [PATCH 209/465] Migrate the `JavaStarlarkApiTest.javaInfo_compileJarNotSet` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738734994 Change-Id: Ib548918f0e46b88095282a79ed187a61edf55e5d --- java/test/common/java_info_tests.bzl | 18 +++++++++++++++++- .../testutil/rules/bad_java_info_rules.bzl | 5 +++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 57dea2f3..766bb09d 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -8,7 +8,7 @@ load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") -load("//java/test/testutil:rules/bad_java_info_rules.bzl", "bad_deps", "bad_exports", "bad_libs", "bad_runtime_deps") +load("//java/test/testutil:rules/bad_java_info_rules.bzl", "bad_deps", "bad_exports", "bad_libs", "bad_runtime_deps", "compile_jar_not_set") load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") def _with_output_jar_only_test(name): @@ -916,6 +916,21 @@ def _with_compile_jar_test_impl(env, target): matching.file_basename_equals("compile.jar"), ) +def _compile_jar_not_set_test(name): + util.helper_target(compile_jar_not_set, name = name + "/only_outputjar") + + analysis_test( + name = name, + impl = _compile_jar_not_set_test_impl, + target = name + "/only_outputjar", + expect_failure = True, + ) + +def _compile_jar_not_set_test_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("missing 1 required positional argument: compile_jar"), + ) + def java_info_tests(name): test_suite( name = name, @@ -949,5 +964,6 @@ def java_info_tests(name): _with_manifest_proto_test, _with_compile_jar_test, _sequence_parameters_are_type_checked_test, + _compile_jar_not_set_test, ], ) diff --git a/java/test/testutil/rules/bad_java_info_rules.bzl b/java/test/testutil/rules/bad_java_info_rules.bzl index f486cbd7..3d7f6ae6 100644 --- a/java/test/testutil/rules/bad_java_info_rules.bzl +++ b/java/test/testutil/rules/bad_java_info_rules.bzl @@ -23,7 +23,12 @@ def _nativelibs_impl(ctx): f = _make_file(ctx) return JavaInfo(output_jar = f, compile_jar = f, native_libraries = [f]) +def _compile_jar_not_set_impl(ctx): + f = _make_file(ctx) + return JavaInfo(output_jar = f) + bad_deps = rule(_deps_impl) bad_runtime_deps = rule(_runtime_deps_impl) bad_exports = rule(_exports_impl) bad_libs = rule(_nativelibs_impl) +compile_jar_not_set = rule(_compile_jar_not_set_impl) From 6f1396a1142068b2a786d4d4de81726613ac1838 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 20 Mar 2025 03:35:54 -0700 Subject: [PATCH 210/465] Migrate the `JavaStarlarkApiTest.javaInfo_compileJarSetToNone` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738738739 Change-Id: I3f39fec300879c4c12754af967ab8b56178b884d --- java/test/common/java_info_tests.bzl | 15 ++++++++++++++- java/test/testutil/rules/bad_java_info_rules.bzl | 5 +++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 766bb09d..414fe7b8 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -8,7 +8,7 @@ load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") -load("//java/test/testutil:rules/bad_java_info_rules.bzl", "bad_deps", "bad_exports", "bad_libs", "bad_runtime_deps", "compile_jar_not_set") +load("//java/test/testutil:rules/bad_java_info_rules.bzl", "bad_deps", "bad_exports", "bad_libs", "bad_runtime_deps", "compile_jar_not_set", "compile_jar_set_to_none") load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") def _with_output_jar_only_test(name): @@ -931,6 +931,18 @@ def _compile_jar_not_set_test_impl(env, target): matching.str_matches("missing 1 required positional argument: compile_jar"), ) +def _compile_jar_set_to_none_test(name): + util.helper_target(compile_jar_set_to_none, name = name + "/compilejar_none") + + analysis_test( + name = name, + impl = _compile_jar_set_to_none_test_impl, + target = name + "/compilejar_none", + ) + +def _compile_jar_set_to_none_test_impl(env, target): + env.expect.that_depset_of_files(target[JavaInfo].compile_jars).contains_exactly([]) + def java_info_tests(name): test_suite( name = name, @@ -965,5 +977,6 @@ def java_info_tests(name): _with_compile_jar_test, _sequence_parameters_are_type_checked_test, _compile_jar_not_set_test, + _compile_jar_set_to_none_test, ], ) diff --git a/java/test/testutil/rules/bad_java_info_rules.bzl b/java/test/testutil/rules/bad_java_info_rules.bzl index 3d7f6ae6..0f5bb1b5 100644 --- a/java/test/testutil/rules/bad_java_info_rules.bzl +++ b/java/test/testutil/rules/bad_java_info_rules.bzl @@ -27,8 +27,13 @@ def _compile_jar_not_set_impl(ctx): f = _make_file(ctx) return JavaInfo(output_jar = f) +def _compile_jar_set_to_none_impl(ctx): + f = _make_file(ctx) + return JavaInfo(output_jar = f, compile_jar = None) + bad_deps = rule(_deps_impl) bad_runtime_deps = rule(_runtime_deps_impl) bad_exports = rule(_exports_impl) bad_libs = rule(_nativelibs_impl) compile_jar_not_set = rule(_compile_jar_not_set_impl) +compile_jar_set_to_none = rule(_compile_jar_set_to_none_impl) From 006f3b253b2e83f6dfd865e83c3da7c495b0128d Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 20 Mar 2025 03:55:46 -0700 Subject: [PATCH 211/465] Migrate the `JavaStarlarkApiTest.javaInfoSourceJarsExposed` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738743553 Change-Id: I3193b003bd2c48385ee8748e196b0d58987de002 --- java/test/common/java_info_tests.bzl | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 414fe7b8..0aef449e 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -943,6 +943,30 @@ def _compile_jar_set_to_none_test(name): def _compile_jar_set_to_none_test_impl(env, target): env.expect.that_depset_of_files(target[JavaInfo].compile_jars).contains_exactly([]) +def _sources_jars_exposed_test(name): + util.helper_target( + java_library, + name = name + "/my_java_lib_b", + srcs = ["java/B.java"], + ) + util.helper_target( + java_library, + name = name + "/my_java_lib_a", + srcs = ["java/A.java"], + deps = [name + "/my_java_lib_b"], + ) + analysis_test( + name = name, + impl = _sources_jars_exposed_test_impl, + target = name + "/my_java_lib_a", + ) + +def _sources_jars_exposed_test_impl(env, target): + source_jars = target[JavaInfo].source_jars + env.expect.that_collection(source_jars).contains_exactly_predicates([ + matching.file_basename_equals("my_java_lib_a-src.jar"), + ]) + def java_info_tests(name): test_suite( name = name, @@ -978,5 +1002,6 @@ def java_info_tests(name): _sequence_parameters_are_type_checked_test, _compile_jar_not_set_test, _compile_jar_set_to_none_test, + _sources_jars_exposed_test, ], ) From 05fd56bb22b2de9bbc992acc5be59e615d04e902 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 20 Mar 2025 04:10:47 -0700 Subject: [PATCH 212/465] Migrate the `JavaStarlarkApiTest.testJavaInfoGetTransitiveSourceJars` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738747774 Change-Id: Ibe715325a9ae4e570a5f0183bfefdddc71b88279 --- java/test/common/java_info_tests.bzl | 40 ++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 0aef449e..d8c2f6f4 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -10,6 +10,7 @@ load("//java/common:java_info.bzl", "JavaInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") load("//java/test/testutil:rules/bad_java_info_rules.bzl", "bad_deps", "bad_exports", "bad_libs", "bad_runtime_deps", "compile_jar_not_set", "compile_jar_set_to_none") load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") +load("//java/test/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") def _with_output_jar_only_test(name): target_name = name + "/my_starlark_rule" @@ -967,6 +968,44 @@ def _sources_jars_exposed_test_impl(env, target): matching.file_basename_equals("my_java_lib_a-src.jar"), ]) +def _transitive_source_jars_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_c", + srcs = ["java/C.java"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_b", + srcs = ["java/B.java"], + deps = [target_name + "/my_java_lib_c"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_a", + srcs = ["java/A.java"], + deps = [target_name + "/my_java_lib_b"], + ) + util.helper_target( + java_info_forwarding_rule, + name = target_name, + dep = target_name + "/my_java_lib_a", + ) + analysis_test( + name = name, + impl = _transitive_source_jars_test_impl, + target = target_name, + ) + +def _transitive_source_jars_test_impl(env, target): + assert_transitive_source_jars = java_info_subject.from_target(env, target).transitive_source_jars() + assert_transitive_source_jars.contains_exactly([ + "{package}/lib{name}/my_java_lib_a-src.jar", + "{package}/lib{name}/my_java_lib_b-src.jar", + "{package}/lib{name}/my_java_lib_c-src.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -1003,5 +1042,6 @@ def java_info_tests(name): _compile_jar_not_set_test, _compile_jar_set_to_none_test, _sources_jars_exposed_test, + _transitive_source_jars_test, ], ) From 118a03717baf151ff6a88d7fd969a8b40b02eabe Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 20 Mar 2025 04:25:44 -0700 Subject: [PATCH 213/465] Migrate the `JavaStarlarkApiTest.testJavaInfoGetTransitiveDeps` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738750930 Change-Id: I20860ca019a0b4fc99cb37f601101d70eb4ebee3 --- java/test/common/java_info_tests.bzl | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index d8c2f6f4..a0cda234 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -1006,6 +1006,44 @@ def _transitive_source_jars_test_impl(env, target): "{package}/lib{name}/my_java_lib_c-src.jar", ]) +def _transitive_compile_time_jars_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_c", + srcs = ["java/C.java"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_b", + srcs = ["java/B.java"], + deps = [target_name + "/my_java_lib_c"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_a", + srcs = ["java/A.java"], + deps = [target_name + "/my_java_lib_b"], + ) + util.helper_target( + java_info_forwarding_rule, + name = target_name, + dep = target_name + "/my_java_lib_a", + ) + analysis_test( + name = name, + impl = transitive_compile_time_jars_impl, + target = target_name, + ) + +def transitive_compile_time_jars_impl(env, target): + assert_transitive_compile_time_jars = java_info_subject.from_target(env, target).compilation_args().transitive_compile_time_jars() + assert_transitive_compile_time_jars.contains_exactly([ + "{package}/lib{name}/my_java_lib_a-hjar.jar", + "{package}/lib{name}/my_java_lib_b-hjar.jar", + "{package}/lib{name}/my_java_lib_c-hjar.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -1043,5 +1081,6 @@ def java_info_tests(name): _compile_jar_set_to_none_test, _sources_jars_exposed_test, _transitive_source_jars_test, + _transitive_compile_time_jars_test, ], ) From 8280a4b2008cec1a11061df3b8b8ab1442bc568b Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 20 Mar 2025 04:40:45 -0700 Subject: [PATCH 214/465] Migrate the `JavaStarlarkApiTest.testJavaInfoGetTransitiveRuntimeDeps` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738754200 Change-Id: I258295c8158f1be02dc1d81a0c89daea828ffde6 --- java/test/common/java_info_tests.bzl | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index a0cda234..4e4d6c14 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -1044,6 +1044,44 @@ def transitive_compile_time_jars_impl(env, target): "{package}/lib{name}/my_java_lib_c-hjar.jar", ]) +def _transitive_runtime_jars_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + java_library, + name = target_name + "/my_java_lib_c", + srcs = ["java/C.java"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_b", + srcs = ["java/B.java"], + deps = [target_name + "/my_java_lib_c"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_a", + srcs = ["java/A.java"], + deps = [target_name + "/my_java_lib_b"], + ) + util.helper_target( + java_info_forwarding_rule, + name = target_name, + dep = target_name + "/my_java_lib_a", + ) + analysis_test( + name = name, + impl = transitive_runtime_jars_impl, + target = target_name, + ) + +def transitive_runtime_jars_impl(env, target): + assert_transitive_runtime_jars = java_info_subject.from_target(env, target).compilation_args().transitive_runtime_jars() + assert_transitive_runtime_jars.contains_exactly([ + "{package}/lib{name}/my_java_lib_a.jar", + "{package}/lib{name}/my_java_lib_b.jar", + "{package}/lib{name}/my_java_lib_c.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -1082,5 +1120,6 @@ def java_info_tests(name): _sources_jars_exposed_test, _transitive_source_jars_test, _transitive_compile_time_jars_test, + _transitive_runtime_jars_test, ], ) From 7366c04c6087260a63affce121b3fea7adbe07ca Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 20 Mar 2025 04:55:46 -0700 Subject: [PATCH 215/465] Migrate the `JavaStarlarkApiTest.javaInfo_getTransitiveNativeLibraries` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738757119 Change-Id: I51e0d9e1fc02b7b79ed8dd707f340bb1ae879769 --- java/test/common/java_info_tests.bzl | 61 ++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 4e4d6c14..01f5d747 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -1082,6 +1082,66 @@ def transitive_runtime_jars_impl(env, target): "{package}/lib{name}/my_java_lib_c.jar", ]) +def _transitive_native_libraries_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + cc_library, + name = target_name + "/my_cc_lib_c.so", + srcs = ["cc/c.cc"], + ) + util.helper_target( + cc_library, + name = target_name + "/my_cc_lib_b.so", + srcs = ["cc/b.cc"], + ) + util.helper_target( + cc_library, + name = target_name + "/my_cc_lib_a.so", + srcs = ["cc/a.cc"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_c", + srcs = ["java/C.java"], + deps = [target_name + "/my_cc_lib_c.so"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_b", + srcs = ["java/B.java"], + deps = [target_name + "/my_cc_lib_b.so"], + ) + util.helper_target( + java_library, + name = target_name + "/my_java_lib_a", + srcs = ["java/A.java"], + deps = [ + target_name + "/my_cc_lib_a.so", + target_name + "/my_java_lib_b", + target_name + "/my_java_lib_c", + ], + ) + util.helper_target( + java_info_forwarding_rule, + name = target_name, + dep = target_name + "/my_java_lib_a", + ) + analysis_test( + name = name, + impl = _transitive_native_libraries_test_impl, + target = target_name, + # LibraryToLink.library_indentifier only available from Bazel 8 + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _transitive_native_libraries_test_impl(env, target): + assert_transitive_native_libraries = java_info_subject.from_target(env, target).transitive_native_libraries() + assert_transitive_native_libraries.identifiers().contains_exactly_predicates([ + matching.str_endswith("my_cc_lib_a.so"), + matching.str_endswith("my_cc_lib_b.so"), + matching.str_endswith("my_cc_lib_c.so"), + ]) + def java_info_tests(name): test_suite( name = name, @@ -1121,5 +1181,6 @@ def java_info_tests(name): _transitive_source_jars_test, _transitive_compile_time_jars_test, _transitive_runtime_jars_test, + _transitive_native_libraries_test, ], ) From cb64303521bc6dafe230ff7e0121290a0a7f20e0 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 20 Mar 2025 05:10:53 -0700 Subject: [PATCH 216/465] Migrate the `JavaStarlarkApiTest.javaLibrary_propagatesDirectNativeLibrariesInJavaInfo` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738760528 Change-Id: I11ce3ef5388db671ba522eae3544c42a9fa58233 --- java/test/common/rules/java_library_tests.bzl | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/java/test/common/rules/java_library_tests.bzl b/java/test/common/rules/java_library_tests.bzl index e9c9b4e0..4381dfbe 100644 --- a/java/test/common/rules/java_library_tests.bzl +++ b/java/test/common/rules/java_library_tests.bzl @@ -1,5 +1,6 @@ """Tests for the java_library rule""" +load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") @@ -7,6 +8,7 @@ load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") load("//java/test/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") load("//java/test/testutil:rules/wrap_java_info.bzl", "JavaInfoWrappingInfo", "java_info_wrapping_rule") @@ -228,6 +230,53 @@ def _test_java_library_attributes_impl(env, targets): matching.file_basename_equals("jl_bottom_for_exports.jar"), ) +def _test_propagates_direct_native_libraries(name): + target_name = name + "/jl_top" + util.helper_target( + cc_library, + name = target_name + "/native", + srcs = ["cc/x.cc"], + ) + util.helper_target( + java_library, + name = target_name + "/jl", + srcs = ["java/A.java"], + deps = [target_name + "/native"], + ) + util.helper_target( + cc_library, + name = target_name + "/ccl", + srcs = ["cc/x.cc"], + ) + util.helper_target( + custom_java_info_rule, + name = target_name + "/r", + output_jar = target_name + "-out.jar", + cc_dep = [target_name + "/ccl"], + dep = [target_name + "/jl"], + ) + util.helper_target( + java_library, + name = target_name, + srcs = ["java/C.java"], + deps = [target_name + "/r"], + ) + + analysis_test( + name = name, + impl = _test_propagates_direct_native_libraries_impl, + target = target_name, + # LibraryToLink.library_indentifier only available from Bazel 8 + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _test_propagates_direct_native_libraries_impl(env, target): + assert_transitive_native_libraries = java_info_subject.from_target(env, target).transitive_native_libraries() + assert_transitive_native_libraries.identifiers().contains_exactly_predicates([ + matching.str_endswith("native"), + matching.str_endswith("ccl"), + ]).in_order() + def java_library_tests(name): test_suite( name = name, @@ -236,5 +285,6 @@ def java_library_tests(name): _test_exposes_java_info, _test_java_info_propagation, _test_java_library_attributes, + _test_propagates_direct_native_libraries, ], ) From 156f09a0d31a67b158af4b3d4462faf7ce9cacf3 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 20 Mar 2025 06:24:21 -0700 Subject: [PATCH 217/465] Migrate the `JavaStarlarkApiTest.javaBinary_propagatesDirectNativeLibrariesInJavaInfo` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738776974 Change-Id: I6fa09dd0ce434be32c710fe78158c8d6b366b9fb --- .bazelrc | 5 ++ java/test/common/rules/java_binary_tests.bzl | 74 +++++++++++++++++++- 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/.bazelrc b/.bazelrc index 526b36d8..b71e7a14 100644 --- a/.bazelrc +++ b/.bazelrc @@ -8,3 +8,8 @@ common --tool_java_runtime_version=remotejdk_8 # Hide Java 8 deprecation warnings. common --javacopt=-Xlint:-options + +# Some tests relies on dynamic libs that are not interface libs +# the latter are always enabled on Windows: https://github.com/bazelbuild/bazel/blob/1f5414408467171581b6142e93f67fe730d722cf/src/main/java/com/google/devtools/build/lib/rules/cpp/CcModule.java#L2430 +# we can't use a transition because toolchain deps exceed the default --analysis_testing_deps_limit. +test --nointerface_shared_objects \ No newline at end of file diff --git a/java/test/common/rules/java_binary_tests.bzl b/java/test/common/rules/java_binary_tests.bzl index 3b763f99..f16898d9 100644 --- a/java/test/common/rules/java_binary_tests.bzl +++ b/java/test/common/rules/java_binary_tests.bzl @@ -1,11 +1,14 @@ """Tests for the java_binary rule""" +load("@rules_cc//cc:cc_binary.bzl", "cc_binary") +load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") -load("@rules_testing//lib:truth.bzl", "matching") +load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") load("//java/test/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") def _test_java_binary_provides_binary_java_info(name): @@ -100,6 +103,74 @@ def _test_java_binary_attributes_impl(env, target): matching.file_basename_equals("jl_bottom_for_runtime_deps.jar"), ]) +def _test_java_binary_propagates_direct_native_libraries(name): + util.helper_target( + cc_library, + name = name + "/cclib", + srcs = ["z.cc"], + ) + util.helper_target( + cc_binary, + name = name + "/native", + srcs = ["cc/x.cc"], + deps = [name + "/cclib"], + linkshared = 1, + linkstatic = 1, + ) + util.helper_target( + java_library, + name = name + "/jl", + srcs = ["java/A.java"], + deps = [name + "/native"], + ) + util.helper_target( + cc_binary, + name = name + "/ccl", + srcs = ["cc/x.cc"], + deps = [name + "/cclib"], + linkshared = 1, + linkstatic = 1, + ) + util.helper_target( + custom_java_info_rule, + name = name + "/r", + output_jar = name + "-out.jar", + cc_dep = [name + "/ccl"], + dep = [name + "/jl"], + ) + util.helper_target( + java_binary, + name = name + "/binary", + srcs = ["java/C.java"], + deps = [name + "/r"], + main_class = "C", + ) + + analysis_test( + name = name, + impl = _test_java_binary_propagates_direct_native_libraries_impl, + target = name + "/binary", + # in Bazel 6, the windows stub was created by a bespoke, native and + # opaque-to-Starlark LauncherFileWriteAction + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_java_binary_propagates_direct_native_libraries_impl(env, target): + executable = target[DefaultInfo].files_to_run.executable.short_path + assert_action = env.expect.that_target(target).action_generating(executable) + if assert_action.actual.substitutions: + # TemplateExpansion action on linux/mac + assert_jvm_flags = assert_action.substitutions().get( + "%jvm_flags%", + factory = lambda v, meta: subjects.collection([v], meta), + ) + else: + # windows + assert_jvm_flags = assert_action.argv() + assert_jvm_flags.contains_predicate( + matching.str_matches("-Djava.library.path=${JAVA_RUNFILES}/*/test_java_binary_propagates_direct_native_libraries"), + ) + def java_binary_tests(name): test_suite( name = name, @@ -107,5 +178,6 @@ def java_binary_tests(name): _test_java_binary_provides_binary_java_info, _test_stamp_conversion_does_not_override_int, _test_java_binary_attributes, + _test_java_binary_propagates_direct_native_libraries, ], ) From 4088bec341c1816585839804fbebb221c59ff877 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 20 Mar 2025 06:42:50 -0700 Subject: [PATCH 218/465] Migrate the `JavaStarlarkApiTest.javaTest_propagatesDirectNativeLibrariesInJavaInfo` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 738781618 Change-Id: Id0416d35cb3ff53afbe5531b56d02d40ffa8b1bf --- java/test/common/rules/BUILD | 3 + java/test/common/rules/java_test_tests.bzl | 86 ++++++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 java/test/common/rules/java_test_tests.bzl diff --git a/java/test/common/rules/BUILD b/java/test/common/rules/BUILD index 0639d292..8ba67604 100644 --- a/java/test/common/rules/BUILD +++ b/java/test/common/rules/BUILD @@ -2,6 +2,7 @@ load(":java_binary_tests.bzl", "java_binary_tests") load(":java_import_tests.bzl", "java_import_tests") load(":java_library_tests.bzl", "java_library_tests") load(":java_plugin_tests.bzl", "java_plugin_tests") +load(":java_test_tests.bzl", "java_test_tests") load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") merge_attrs_test_suite(name = "merge_attrs_tests") @@ -13,3 +14,5 @@ java_plugin_tests(name = "java_plugin_tests") java_library_tests(name = "java_library_tests") java_import_tests(name = "java_import_tests") + +java_test_tests(name = "java_test_tests") diff --git a/java/test/common/rules/java_test_tests.bzl b/java/test/common/rules/java_test_tests.bzl new file mode 100644 index 00000000..5a6a9a8f --- /dev/null +++ b/java/test/common/rules/java_test_tests.bzl @@ -0,0 +1,86 @@ +"""Tests for the java_test rule""" + +load("@rules_cc//cc:cc_binary.bzl", "cc_binary") +load("@rules_cc//cc:cc_library.bzl", "cc_library") +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching", "subjects") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_library.bzl", "java_library") +load("//java:java_test.bzl", "java_test") +load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") + +def _test_java_test_propagates_direct_native_libraries(name): + util.helper_target( + cc_library, + name = name + "/cclib", + srcs = ["z.cc"], + ) + util.helper_target( + cc_binary, + name = name + "/native", + srcs = ["cc/x.cc"], + deps = [name + "/cclib"], + linkshared = 1, + linkstatic = 1, + ) + util.helper_target( + java_library, + name = name + "/jl", + srcs = ["java/A.java"], + deps = [name + "/native"], + ) + util.helper_target( + cc_binary, + name = name + "/ccl", + srcs = ["cc/x.cc"], + deps = [name + "/cclib"], + linkshared = 1, + linkstatic = 1, + ) + util.helper_target( + custom_java_info_rule, + name = name + "/r", + output_jar = name + "-out.jar", + cc_dep = [name + "/ccl"], + dep = [name + "/jl"], + ) + util.helper_target( + java_test, + name = name + "/binary", + srcs = ["java/C.java"], + deps = [name + "/r"], + main_class = "C", + ) + + analysis_test( + name = name, + impl = _test_java_test_propagates_direct_native_libraries_impl, + target = name + "/binary", + # in Bazel 6, the windows stub was created by a bespoke, native and + # opaque-to-Starlark LauncherFileWriteAction + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_java_test_propagates_direct_native_libraries_impl(env, target): + executable = target[DefaultInfo].files_to_run.executable.short_path + assert_action = env.expect.that_target(target).action_generating(executable) + if assert_action.actual.substitutions: + # TemplateExpansion action on linux/mac + assert_jvm_flags = assert_action.substitutions().get( + "%jvm_flags%", + factory = lambda v, meta: subjects.collection([v], meta), + ) + else: + # windows + assert_jvm_flags = assert_action.argv() + assert_jvm_flags.contains_predicate( + matching.str_matches("-Djava.library.path=${JAVA_RUNFILES}/*/test_java_test_propagates_direct_native_libraries"), + ) + +def java_test_tests(name): + test_suite( + name = name, + tests = [ + _test_java_test_propagates_direct_native_libraries, + ], + ) From 13263bb478183abf2946a32e197b5a313aa6d403 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 21 Mar 2025 10:37:36 -0700 Subject: [PATCH 219/465] Migrate the `JavaStarlarkApiTest.javaToolchainInfo_jacocoRunnerAttribute` test to Starlark The test is removed from Bazel and added to rules_java. PiperOrigin-RevId: 739229477 Change-Id: I954643254669f4b85a222325c9351dd18eca9809 --- MODULE.bazel | 6 +++ WORKSPACE | 6 +-- .../testutil/java_toolchain_info_subject.bzl | 22 +++++++++ java/test/toolchains/BUILD | 3 ++ java/test/toolchains/java_toolchain_tests.bzl | 47 +++++++++++++++++++ 5 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 java/test/testutil/java_toolchain_info_subject.bzl create mode 100644 java/test/toolchains/java_toolchain_tests.bzl diff --git a/MODULE.bazel b/MODULE.bazel index f60025ad..752b4b04 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -99,6 +99,12 @@ bazel_dep(name = "rules_pkg", version = "0.9.1", dev_dependency = True) bazel_dep(name = "stardoc", version = "0.7.1", dev_dependency = True) bazel_dep(name = "rules_shell", version = "0.2.0", dev_dependency = True) bazel_dep(name = "rules_testing", version = "0.7.0", dev_dependency = True) +archive_override( + module_name = "rules_testing", + integrity = "sha256-SWd6sSJvbYUqFLlm4eXelz+77ovBkOa/DolcXyZ/ldQ=", + strip_prefix = "rules_testing-3909cc0b0e41141bdfe2862a7950ef9f9372d6f8", + urls = ["https://github.com/bazelbuild/rules_testing/archive/3909cc0b0e41141bdfe2862a7950ef9f9372d6f8.tar.gz"], +) test_repositories = use_extension("//test:repositories.bzl", "test_repositories_ext", dev_dependency = True) use_repo(test_repositories, "guava", "truth") diff --git a/WORKSPACE b/WORKSPACE index 161fa9cc..5389a0dd 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -55,9 +55,9 @@ stardoc_repositories() http_archive( name = "rules_testing", - sha256 = "28c2d174471b587bf0df1fd3a10313f22c8906caf4050f8b46ec4648a79f90c3", - strip_prefix = "rules_testing-0.7.0", - url = "https://github.com/bazelbuild/rules_testing/releases/download/v0.7.0/rules_testing-v0.7.0.tar.gz", + sha256 = "49677ab1226f6d852a14b966e1e5de973fbbee8bc190e6bf0e895c5f267f95d4", + strip_prefix = "rules_testing-3909cc0b0e41141bdfe2862a7950ef9f9372d6f8", + urls = ["https://github.com/bazelbuild/rules_testing/archive/3909cc0b0e41141bdfe2862a7950ef9f9372d6f8.tar.gz"], ) load("//test:repositories.bzl", "test_repositories") diff --git a/java/test/testutil/java_toolchain_info_subject.bzl b/java/test/testutil/java_toolchain_info_subject.bzl new file mode 100644 index 00000000..af6934b1 --- /dev/null +++ b/java/test/testutil/java_toolchain_info_subject.bzl @@ -0,0 +1,22 @@ +"""Custom @rules_testing subject for the JavaToolchainInfo provider""" + +load("@rules_testing//lib:truth.bzl", "subjects") +load("//java/common:java_common.bzl", "java_common") + +def _new_java_toolchain_info_subject(info, meta): + public = struct( + jacocorunner = lambda: subjects.file(info.jacocorunner.executable, meta.derive("jacocorunner.executable")), + ) + return public + +def _from_target(env, target): + return env.expect.that_target(target).provider( + java_common.JavaToolchainInfo, + factory = _new_java_toolchain_info_subject, + provider_name = "JavaToolchainInfo", + ) + +java_toolchain_info_subject = struct( + new = _new_java_toolchain_info_subject, + from_target = _from_target, +) diff --git a/java/test/toolchains/BUILD b/java/test/toolchains/BUILD index 44f223bd..440cb341 100644 --- a/java/test/toolchains/BUILD +++ b/java/test/toolchains/BUILD @@ -1,3 +1,6 @@ load(":java_runtime_tests.bzl", "java_runtime_tests") +load(":java_toolchain_tests.bzl", "java_toolchain_tests") java_runtime_tests(name = "java_runtime_tests") + +java_toolchain_tests(name = "java_toolchain_tests") diff --git a/java/test/toolchains/java_toolchain_tests.bzl b/java/test/toolchains/java_toolchain_tests.bzl new file mode 100644 index 00000000..2c4e1000 --- /dev/null +++ b/java/test/toolchains/java_toolchain_tests.bzl @@ -0,0 +1,47 @@ +"""Tests for the java_toolchain rule""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java/test/testutil:java_toolchain_info_subject.bzl", "java_toolchain_info_subject") +load("//java/toolchains:java_runtime.bzl", "java_runtime") +load("//java/toolchains:java_toolchain.bzl", "java_toolchain") + +def _declare_java_toolchain(*, name, **kwargs): + if "java_runtime" not in kwargs: + kwargs["java_runtime"] = name + "/runtime" + java_runtime(name = name + "/runtime") + util.helper_target( + java_toolchain, + name = name, + genclass = [kwargs.get("genclass", "default_genclass.jar")], + jacocorunner = kwargs.get("jacocorunner", None), + javabuilder = [kwargs.get("javabuilder", "default_javabuilder.jar")], + java_runtime = kwargs["java_runtime"], + ijar = [kwargs.get("ijar", "default_ijar.jar")], + singlejar = [kwargs.get("singlejar", "default_singlejar.jar")], + ) + +def _test_jacocorunner(name): + _declare_java_toolchain( + name = name + "/java_toolchain", + jacocorunner = "myjacocorunner.jar", + ) + + analysis_test( + name = name, + impl = _test_jacocorunner_impl, + target = name + "/java_toolchain", + ) + +def _test_jacocorunner_impl(env, target): + assert_toolchain = java_toolchain_info_subject.from_target(env, target) + + assert_toolchain.jacocorunner().short_path_equals("{package}/myjacocorunner.jar") + +def java_toolchain_tests(name): + test_suite( + name = name, + tests = [ + _test_jacocorunner, + ], + ) From 69395ee778c60be40d44a1c4564a1745fd33f345 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 25 Mar 2025 02:38:03 -0700 Subject: [PATCH 220/465] Migrate the `JavaStarlarkApiTest.javaLibrary_exposesNativeLibraryInfoToStarlark` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 740264161 Change-Id: Iadc99b89d08b9a1fbfce7baf72e79a19838bcd8d --- MODULE.bazel | 6 ++-- WORKSPACE | 6 ++-- java/test/common/rules/java_library_tests.bzl | 35 +++++++++++++++++++ java/test/testutil/cc_info_subject.bzl | 12 +++++++ 4 files changed, 53 insertions(+), 6 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 752b4b04..2eed88ac 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -101,9 +101,9 @@ bazel_dep(name = "rules_shell", version = "0.2.0", dev_dependency = True) bazel_dep(name = "rules_testing", version = "0.7.0", dev_dependency = True) archive_override( module_name = "rules_testing", - integrity = "sha256-SWd6sSJvbYUqFLlm4eXelz+77ovBkOa/DolcXyZ/ldQ=", - strip_prefix = "rules_testing-3909cc0b0e41141bdfe2862a7950ef9f9372d6f8", - urls = ["https://github.com/bazelbuild/rules_testing/archive/3909cc0b0e41141bdfe2862a7950ef9f9372d6f8.tar.gz"], + integrity = "sha256-0+3pLjeZCqn+K1qS7HNr7HbwMXBjxLvJm+pMSUhDel8=", + strip_prefix = "rules_testing-db007bfee840cebcb6f955b80973ba866de38947", + urls = ["https://github.com/bazelbuild/rules_testing/archive/db007bfee840cebcb6f955b80973ba866de38947.tar.gz"], ) test_repositories = use_extension("//test:repositories.bzl", "test_repositories_ext", dev_dependency = True) diff --git a/WORKSPACE b/WORKSPACE index 5389a0dd..cf3fa50c 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -55,9 +55,9 @@ stardoc_repositories() http_archive( name = "rules_testing", - sha256 = "49677ab1226f6d852a14b966e1e5de973fbbee8bc190e6bf0e895c5f267f95d4", - strip_prefix = "rules_testing-3909cc0b0e41141bdfe2862a7950ef9f9372d6f8", - urls = ["https://github.com/bazelbuild/rules_testing/archive/3909cc0b0e41141bdfe2862a7950ef9f9372d6f8.tar.gz"], + sha256 = "d3ede92e37990aa9fe2b5a92ec736bec76f0317063c4bbc99bea4c4948437a5f", + strip_prefix = "rules_testing-db007bfee840cebcb6f955b80973ba866de38947", + urls = ["https://github.com/bazelbuild/rules_testing/archive/db007bfee840cebcb6f955b80973ba866de38947.tar.gz"], ) load("//test:repositories.bzl", "test_repositories") diff --git a/java/test/common/rules/java_library_tests.bzl b/java/test/common/rules/java_library_tests.bzl index 4381dfbe..283cf57d 100644 --- a/java/test/common/rules/java_library_tests.bzl +++ b/java/test/common/rules/java_library_tests.bzl @@ -1,5 +1,6 @@ """Tests for the java_library rule""" +load("@rules_cc//cc:cc_binary.bzl", "cc_binary") load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching") @@ -277,6 +278,39 @@ def _test_propagates_direct_native_libraries_impl(env, target): matching.str_endswith("ccl"), ]).in_order() +def _test_exposes_native_library_info(name): + target_name = name + "/jl" + util.helper_target( + cc_library, + name = target_name + "/mynativedep_lib", + srcs = ["cc/x.cc"], + ) + util.helper_target( + cc_binary, + name = target_name + "/mynativedep_bin", + srcs = ["cc/x.cc"], + linkshared = 1, + ) + util.helper_target( + java_library, + name = target_name, + srcs = ["java/A.java"], + deps = select({ + "@platforms//os:windows": [target_name + "/mynativedep_lib"], + "//conditions:default": [target_name + "/mynativedep_bin"], + }), + ) + analysis_test( + name = name, + impl = _test_exposes_native_library_info_impl, + target = target_name, + ) + +def _test_exposes_native_library_info_impl(env, target): + assert_lib = java_info_subject.from_target(env, target).transitive_native_libraries().singleton() + + assert_lib.dynamic_library().basename().contains("mynativedep") + def java_library_tests(name): test_suite( name = name, @@ -286,5 +320,6 @@ def java_library_tests(name): _test_java_info_propagation, _test_java_library_attributes, _test_propagates_direct_native_libraries, + _test_exposes_native_library_info, ], ) diff --git a/java/test/testutil/cc_info_subject.bzl b/java/test/testutil/cc_info_subject.bzl index a2ab6706..cf877a22 100644 --- a/java/test/testutil/cc_info_subject.bzl +++ b/java/test/testutil/cc_info_subject.bzl @@ -60,6 +60,13 @@ def _new_cc_info_libraries_to_link_subject(libraries_to_link, meta): ) public = struct( identifiers = lambda: _new_library_to_link_identifiers_subject(self.actual, self.meta), + singleton = lambda: _new_library_to_link_subject(_get_singleton(self.actual), self.meta.derive("[0]")), + ) + return public + +def _new_library_to_link_subject(library_to_link, meta): + public = struct( + dynamic_library = lambda: subjects.file(library_to_link.dynamic_library, meta.derive("dynamic_library")), ) return public @@ -74,6 +81,11 @@ def _new_library_to_link_identifiers_subject(libraries_to_link, meta): ) return public +def _get_singleton(seq): + if len(seq) != 1: + fail("expected singleton, got:", seq) + return seq[0] + cc_info_subject = struct( new_from_java_info = lambda java_info, meta: _new_cc_info_subject(java_info.cc_link_params_info, meta.derive("cc_link_params_info")), libraries_to_link = _new_cc_info_libraries_to_link_subject, From 91e505cd72cedd1fab099f2f5e753c9439644008 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 25 Mar 2025 02:55:54 -0700 Subject: [PATCH 221/465] Migrate the `JavaStarlarkApiTest.javaInfo_nativeLibrariesPropagate` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 740268430 Change-Id: Ia77c7d385aa9883aeb6a095e57da0e8d2cb1627b --- java/test/common/java_info_tests.bzl | 62 ++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 01f5d747..35077a7c 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -1142,6 +1142,67 @@ def _transitive_native_libraries_test_impl(env, target): matching.str_endswith("my_cc_lib_c.so"), ]) +def _native_libraries_propagation_test(name): + target_name = name + "/custom" + util.helper_target( + custom_java_info_rule, + name = target_name, + sources = ["A.java"], + dep_exports = [target_name + "/lib_exports"], + dep_runtime = [target_name + "/lib_runtime_deps"], + dep = [target_name + "/lib_deps"], + output_jar = target_name + ".out", + ) + util.helper_target( + java_library, + name = target_name + "/lib_deps", + srcs = ["B.java"], + deps = [target_name + "/native_deps1.so"], + ) + util.helper_target( + cc_library, + name = target_name + "/native_deps1.so", + srcs = ["a.cc"], + ) + util.helper_target( + java_library, + name = target_name + "/lib_runtime_deps", + srcs = ["C.java"], + deps = [target_name + "/native_rdeps1.so"], + ) + util.helper_target( + cc_library, + name = target_name + "/native_rdeps1.so", + srcs = ["c.cc"], + ) + util.helper_target( + java_library, + name = target_name + "/lib_exports", + srcs = ["D.java"], + deps = [target_name + "/native_exports1.so"], + ) + util.helper_target( + cc_library, + name = target_name + "/native_exports1.so", + srcs = ["e.cc"], + ) + + analysis_test( + name = name, + impl = _native_libraries_propagation_test_impl, + target = target_name, + # LibraryToLink.library_identifier only available from Bazel 8 + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _native_libraries_propagation_test_impl(env, target): + assert_transitive_native_libraries = java_info_subject.from_target(env, target).transitive_native_libraries() + assert_transitive_native_libraries.identifiers().contains_exactly_predicates([ + matching.str_endswith("native_rdeps1.so"), + matching.str_endswith("native_exports1.so"), + matching.str_endswith("native_deps1.so"), + ]).in_order() + def java_info_tests(name): test_suite( name = name, @@ -1182,5 +1243,6 @@ def java_info_tests(name): _transitive_compile_time_jars_test, _transitive_runtime_jars_test, _transitive_native_libraries_test, + _native_libraries_propagation_test, ], ) From 000a90bdf93890e55aa9dba2bef6493a0ac236fc Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 25 Mar 2025 03:13:43 -0700 Subject: [PATCH 222/465] Migrate the `JavaStarlarkApiTest.testJavaInfoGetGenJarsProvider` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 740273419 Change-Id: I45ff70fbe65a3cba36291bcf2d19a8c1ac4ba62d --- java/test/common/java_info_tests.bzl | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 35077a7c..2b4208e5 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -1203,6 +1203,27 @@ def _native_libraries_propagation_test_impl(env, target): matching.str_endswith("native_deps1.so"), ]).in_order() +def _annotation_processing_test(name): + target_name = name + "/my_java_lib_a" + util.helper_target( + java_library, + name = target_name, + srcs = ["java/A.java"], + javacopts = ["-processor com.google.process.Processor"], + ) + + analysis_test( + name = name, + impl = _annotation_processing_test_impl, + target = target_name, + ) + +def _annotation_processing_test_impl(env, target): + assert_info = java_info_subject.from_target(env, target).annotation_processing() + + assert_info.class_jar().short_path_equals("{package}/lib{name}-gen.jar") + assert_info.source_jar().short_path_equals("{package}/lib{name}-gensrc.jar") + def java_info_tests(name): test_suite( name = name, @@ -1244,5 +1265,6 @@ def java_info_tests(name): _transitive_runtime_jars_test, _transitive_native_libraries_test, _native_libraries_propagation_test, + _annotation_processing_test, ], ) From 14e2ca65dc39ea8fb9c269db1107dd4eb3b88f41 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 25 Mar 2025 03:41:50 -0700 Subject: [PATCH 223/465] Migrate the `JavaStarlarkApiTest.javaInfoGetCompilationInfoProvider` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 740280487 Change-Id: Ie6227c8b3caf77f16e50f913e1f1fbfd520cf398 --- java/test/common/java_info_tests.bzl | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index 2b4208e5..cea6a11f 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -1224,6 +1224,26 @@ def _annotation_processing_test_impl(env, target): assert_info.class_jar().short_path_equals("{package}/lib{name}-gen.jar") assert_info.source_jar().short_path_equals("{package}/lib{name}-gensrc.jar") +def _compilation_info_test(name): + target_name = name + "/my_java_lib_a" + util.helper_target( + java_library, + name = target_name, + srcs = ["java/A.java"], + javacopts = ["opt1"], + ) + analysis_test( + name = name, + impl = _compilation_info_test_impl, + target = target_name, + ) + +def _compilation_info_test_impl(env, target): + assert_info = java_info_subject.from_target(env, target).compilation_info() + + assert_info.runtime_classpath().contains_exactly(["{package}/lib{name}.jar"]) + assert_info.javac_options().contains("opt1") + def java_info_tests(name): test_suite( name = name, @@ -1266,5 +1286,6 @@ def java_info_tests(name): _transitive_native_libraries_test, _native_libraries_propagation_test, _annotation_processing_test, + _compilation_info_test, ], ) From 4b4b80a63ae00b426453421418d4a84d7779d1b3 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 25 Mar 2025 03:56:19 -0700 Subject: [PATCH 224/465] Migrate the `JavaStarlarkApiTest.javaInfoStarlarkCompilationInfoJavacOpts` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 740284352 Change-Id: I94e4daf57f6dfe50d1967b70b430b43546c717b7 --- java/test/common/java_info_tests.bzl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index cea6a11f..bd77c6bc 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -1230,7 +1230,7 @@ def _compilation_info_test(name): java_library, name = target_name, srcs = ["java/A.java"], - javacopts = ["opt1"], + javacopts = ["opt1", "opt2"], ) analysis_test( name = name, @@ -1242,7 +1242,7 @@ def _compilation_info_test_impl(env, target): assert_info = java_info_subject.from_target(env, target).compilation_info() assert_info.runtime_classpath().contains_exactly(["{package}/lib{name}.jar"]) - assert_info.javac_options().contains("opt1") + assert_info.javac_options().contains_at_least(["opt1", "opt2"]).in_order() def java_info_tests(name): test_suite( From aebb04660c9dbf15aaf1d1271b4675a7bb12067e Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 25 Mar 2025 04:13:23 -0700 Subject: [PATCH 225/465] Migrate the `JavaStarlarkApiTest.javaCommonCompileNeverlink` test to Starlark The test is removed from Bazel and added in `@rules_java` PiperOrigin-RevId: 740289678 Change-Id: Ib43951dcf6180ee50e5b571c27ba3cd119d359d2 --- java/test/common/java_common_tests.bzl | 53 ++++++++++++++++++++ java/test/testutil/artifact_closure.bzl | 55 +++++++++++++++++++++ java/test/testutil/rules/custom_library.bzl | 2 + 3 files changed, 110 insertions(+) create mode 100644 java/test/testutil/artifact_closure.bzl diff --git a/java/test/common/java_common_tests.bzl b/java/test/common/java_common_tests.bzl index 02ee1812..8a37f677 100644 --- a/java/test/common/java_common_tests.bzl +++ b/java/test/common/java_common_tests.bzl @@ -3,11 +3,13 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") +load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") +load("//java/test/testutil:artifact_closure.bzl", "artifact_closure") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") load("//java/test/testutil:rules/custom_library.bzl", "custom_library") load("//java/test/testutil:rules/custom_library_extended_compile_jdeps.bzl", "CompileJdepsInfo", "custom_library_extended_jdeps") @@ -652,6 +654,56 @@ def _test_compile_additional_inputs_and_outputs_impl(env, target): matching.file_basename_equals("custom_additional_output"), ) +def _test_compile_neverlink(name): + target_name = name + "/plugin" + util.helper_target( + java_binary, + name = target_name, + srcs = ["Plugin.java"], + main_class = "plugin.start", + deps = [target_name + "/somedep"], + ) + util.helper_target( + custom_library, + name = target_name + "/somedep", + srcs = ["Dependency.java"], + deps = [target_name + "/eclipse"], + ) + util.helper_target( + custom_library, + name = target_name + "/eclipse", + srcs = ["EclipseDependency.java"], + neverlink = 1, + ) + analysis_test( + name = name, + impl = _test_compile_neverlink_impl, + target = target_name, + extra_target_under_test_aspects = [artifact_closure.aspect], + ) + +def _test_compile_neverlink_impl(env, target): + java_source_basenames = [ + f.basename + for f in artifact_closure.of_target(target) + if f.extension == "java" + ] + env.expect.that_collection(java_source_basenames).contains_exactly([ + "Plugin.java", + "Dependency.java", + "EclipseDependency.java", + ]) + jars_in_runfiles = [ + f.basename + for f in target[DefaultInfo].default_runfiles.files.to_list() + if f.extension == "jar" and + f.short_path.startswith(target.label.package) # exclude toolchain + ] + env.expect.that_collection(jars_in_runfiles).contains_exactly([ + "plugin.jar", + "somedep.jar", + ]).in_order() + def java_common_tests(name): test_suite( name = name, @@ -677,5 +729,6 @@ def java_common_tests(name): _test_compile_no_sources, _test_compile_custom_output_source_jar, _test_compile_additional_inputs_and_outputs, + _test_compile_neverlink, ], ) diff --git a/java/test/testutil/artifact_closure.bzl b/java/test/testutil/artifact_closure.bzl new file mode 100644 index 00000000..129b5884 --- /dev/null +++ b/java/test/testutil/artifact_closure.bzl @@ -0,0 +1,55 @@ +"""Helper for computing the artifact closure of a target""" + +# TODO: consider upstreaming this to @rules_testing + +def _of_target(target): + to_process = target[DefaultInfo].files.to_list() + if _ArtifactActionMapInfo not in target: + fail("Did you forget to add the aspect to analysis_test(extra_target_under_test_aspects = )?") + map = target[_ArtifactActionMapInfo].map + result = [] + visited = {} + for __ in range(len(map)): + if not to_process: + break + next_to_process = [] + for x in to_process: + if x in visited: + continue + visited[x] = None + result.append(x) + if x not in map: + # source file or not visible to us (toolchain?) + continue + a = map[x] + next_to_process.extend([f for f in a.inputs.to_list() if f not in visited]) + to_process = next_to_process + return result + +_ArtifactActionMapInfo = provider( + "Map of artifacts to actions", + fields = ["map"], +) + +def _aspect_impl(target, ctx): + map = {} + for action in target.actions: + for output in action.outputs.to_list(): + map[output] = action + + # Rollup from all dep attributes + for attr_name in dir(ctx.rule.attr): + attr = getattr(ctx.rule.attr, attr_name) + if type(attr) != "list": + attr = [attr] + for val in attr: + if type(val) == "Target" and _ArtifactActionMapInfo in val: + map = map | val[_ArtifactActionMapInfo].map + return _ArtifactActionMapInfo(map = map) + +_aspect = aspect(_aspect_impl, attr_aspects = ["*"]) + +artifact_closure = struct( + aspect = _aspect, + of_target = _of_target, +) diff --git a/java/test/testutil/rules/custom_library.bzl b/java/test/testutil/rules/custom_library.bzl index 500ad2b5..024c05d9 100644 --- a/java/test/testutil/rules/custom_library.bzl +++ b/java/test/testutil/rules/custom_library.bzl @@ -14,6 +14,7 @@ def _custom_library_impl(ctx): source_files = ctx.files.srcs, source_jars = ctx.files.source_jars, output = output_jar, + neverlink = ctx.attr.neverlink, deps = deps, runtime_deps = runtime_deps, exports = [e[JavaInfo] for e in ctx.attr.exports], @@ -33,6 +34,7 @@ custom_library = rule( "exports": attr.label_list(), "plugins": attr.label_list(), "javac_opts": attr.string_list(), + "neverlink": attr.bool(), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], fragments = ["java"], From 8c7993ff46b399ebadb73f8bda446d8770ebf012 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 26 Mar 2025 03:11:45 -0700 Subject: [PATCH 226/465] Update the `@rules_java` release notes generator - Pick baseline as latest ancestor tag of the current commit instead of the globally latest release - Compute diff between last tag and current HEAD, rather than assuming we're always releasing from tip of `master` - Add filtering support to exclude internal-only changes (ignore-relnotes) PiperOrigin-RevId: 740696166 Change-Id: Id8d9a2eb3acd0812b4d2e0cab5808ec793a5f7a7 --- distro/relnotes.bzl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/distro/relnotes.bzl b/distro/relnotes.bzl index ba128833..71f3d830 100644 --- a/distro/relnotes.bzl +++ b/distro/relnotes.bzl @@ -5,8 +5,8 @@ def print_rel_notes(*, name, version, archive): name = name, outs = [name + ".txt"], cmd = """ - last_rel=$$(curl -s https://api.github.com/repos/bazelbuild/rules_java/releases/latest | grep 'tag_name' | cut -d: -f2 | tr -cd '[:alnum:].') - changelog=$$(/usr/bin/git log tags/$$last_rel..origin/master --format=oneline --) + last_rel=$$(git describe --tags --abbrev=0) + changelog=$$(/usr/bin/git log tags/$$last_rel..HEAD --format=oneline --invert-grep --grep 'ignore-relnotes' --) sha=$$(/usr/bin/sha256sum $(SRCS) | cut -d ' ' -f1) cat > $@ < Date: Wed, 26 Mar 2025 07:06:18 -0700 Subject: [PATCH 227/465] Add a test for the `@rules_java` release notes generator PiperOrigin-RevId: 740752942 Change-Id: I01455d2ef20f027f4c253324eda650694c9254f6 --- .bazelci/presubmit.yml | 7 +++++-- distro/relnotes.bzl | 1 + test/BUILD.bazel | 12 +++++++++++ test/check_release_notes_test.sh | 35 ++++++++++++++++++++++++++++++++ 4 files changed, 53 insertions(+), 2 deletions(-) create mode 100755 test/check_release_notes_test.sh diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index de1be01f..a1dddbba 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -22,8 +22,6 @@ build_targets_integration: &build_targets_integration test_targets: &test_targets - "//test/..." - "//java/test/..." - # linux-only tests - - "-//test:check_remote_jdk_configs_test" # TODO: re-enable docs after moving them out of https://bazel.build/reference/be/java - "-//test:docs_up_to_date_test" @@ -108,5 +106,10 @@ tasks: name: "Extra tests w/ Bazel {bazel}" bazel: ${{ bazel }} platform: "ubuntu2004" + shell_commands: + - "git config user.name 'fake-user-for-testing'" + - "git tag -a 'fake-tag-for-testing' -m 'ignore'" + - "git commit --allow-empty -m 'Fake commit message for testing'" test_targets: - "//test:check_remote_jdk_configs_test" + - "//test:check_release_notes_test" diff --git a/distro/relnotes.bzl b/distro/relnotes.bzl index 71f3d830..5641bf7b 100644 --- a/distro/relnotes.bzl +++ b/distro/relnotes.bzl @@ -48,4 +48,5 @@ EOF """.format(ARCHIVE = archive, VERSION = version), srcs = [archive], tags = ["local", "manual"], + visibility = ["//test:__pkg__"], ) diff --git a/test/BUILD.bazel b/test/BUILD.bazel index c9dd65b9..70e62b53 100644 --- a/test/BUILD.bazel +++ b/test/BUILD.bazel @@ -31,6 +31,7 @@ sh_test( for configs in REMOTE_JDK_CONFIGS.values() for config in configs ], + tags = ["manual"], # explicitly tested only on Linux ) sh_test( @@ -47,6 +48,17 @@ sh_test( ], ) +sh_test( + name = "check_release_notes_test", + srcs = ["check_release_notes_test.sh"], + args = [ + "$(location //distro:relnotes.txt)", + module_version(), + ], + data = ["//distro:relnotes.txt"], + tags = ["manual"], # explicitly tested only on Linux +) + diff_test( name = "docs_up_to_date_test", failure_message = """ diff --git a/test/check_release_notes_test.sh b/test/check_release_notes_test.sh new file mode 100755 index 00000000..86f0288d --- /dev/null +++ b/test/check_release_notes_test.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# 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. + +RELNOTES_FILE=$1 +VERSION=$2 + +function fail() { + echo "ERROR: ${1}" + echo "Release notes content:" + echo "--------------------------------------" + cat ${RELNOTES_FILE} + echo "--------------------------------------" + exit 1 +} + +echo "Checking generated release notes: ${RELNOTES_FILE}" + +grep -q '**Changes since fake-tag-for-tests**' ${RELNOTES_FILE} || fail "No changelog header" +grep -q 'Fake commit message for testing' ${RELNOTES_FILE} || fail "No changelog commit" +grep -q '**MODULE.bazel setup**' ${RELNOTES_FILE} || fail "No bzlmod setup header" +grep -q "bazel_dep(name = \"rules_java\", version = \"${VERSION}\")" ${RELNOTES_FILE} || fail "No bzlmod dep stanza" +grep -q '**WORKSPACE setup**' ${RELNOTES_FILE} || fail "No WORKSPACE setup header" +grep -q '**Using the rules**' ${RELNOTES_FILE} || fail "No using the rules header" From ea611cfc6951dd734e2acfd56bd6338490101ef1 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 27 Mar 2025 08:34:18 -0700 Subject: [PATCH 228/465] Fix setup for `@rules_java` `linux_only_tests` This is also executed while running `bazel-diff` in a non-git directory PiperOrigin-RevId: 741164819 Change-Id: I8ae93276ff8474e380cbbc7fb72d97f6b42cdeef --- .bazelci/presubmit.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index a1dddbba..92f12c65 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -107,6 +107,7 @@ tasks: bazel: ${{ bazel }} platform: "ubuntu2004" shell_commands: + - "git init" - "git config user.name 'fake-user-for-testing'" - "git tag -a 'fake-tag-for-testing' -m 'ignore'" - "git commit --allow-empty -m 'Fake commit message for testing'" From 4e83620b038575b4f9e20f3dc581072035c081a0 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 28 Mar 2025 02:28:20 -0700 Subject: [PATCH 229/465] Actually fix the setup for `@rules_java` `linux_only_tests` The `git tag` command fails without any commits so we just add an intial empty one. Aside, as it turns out, `bazel-diff` is skipped when the presubmit.yml file is changed. So this time I made sure to manually verify that this works. (ignore-relnotes) PiperOrigin-RevId: 741451520 Change-Id: I255a643dce6d3c40d66d61d125094c8957d880bb --- .bazelci/presubmit.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 92f12c65..bf63f3c7 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -109,6 +109,7 @@ tasks: shell_commands: - "git init" - "git config user.name 'fake-user-for-testing'" + - "git commit --allow-empty -m 'Fake init commit'" - "git tag -a 'fake-tag-for-testing' -m 'ignore'" - "git commit --allow-empty -m 'Fake commit message for testing'" test_targets: From 1b5a8b24a7d87298fdaeb5e28a8d84c1c2337d82 Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Fri, 28 Mar 2025 08:55:01 -0700 Subject: [PATCH 230/465] Set use_default_shell_env = True consistently. (#276) About half the action registrations in rules_java formerly set this. Be consistent. Closes #276 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/276 from benjaminp:use_default_shell_env 84ad1c1546dcff852bfd015969187f2d1297f8e1 PiperOrigin-RevId: 741540811 Change-Id: I75b5828b64af5de3b01deef29859101eac6c556a --- java/common/rules/android_lint.bzl | 1 + java/common/rules/impl/import_deps_check.bzl | 1 + java/common/rules/impl/java_binary_impl.bzl | 1 + java/common/rules/impl/java_helper.bzl | 1 + java/common/rules/impl/proguard_validation.bzl | 1 + java/java_single_jar.bzl | 1 + toolchains/bootclasspath.bzl | 2 ++ 7 files changed, 8 insertions(+) diff --git a/java/common/rules/android_lint.bzl b/java/common/rules/android_lint.bzl index 5275ec20..f0a04328 100644 --- a/java/common/rules/android_lint.bzl +++ b/java/common/rules/android_lint.bzl @@ -136,6 +136,7 @@ def _android_lint_action(ctx, source_files, source_jars, compilation_info): tools = tools, arguments = args_list, execution_requirements = {"supports-workers": "1"}, + use_default_shell_env = True, ) return android_lint_out diff --git a/java/common/rules/impl/import_deps_check.bzl b/java/common/rules/impl/import_deps_check.bzl index 306a40ca..68d52145 100644 --- a/java/common/rules/impl/import_deps_check.bzl +++ b/java/common/rules/impl/import_deps_check.bzl @@ -76,6 +76,7 @@ def import_deps_check( outputs = [jdeps_output], tools = tools, toolchain = semantics.JAVA_TOOLCHAIN_TYPE, + use_default_shell_env = True, ) return jdeps_output diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl index a5a14d04..a41a125b 100644 --- a/java/common/rules/impl/java_binary_impl.bzl +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -364,6 +364,7 @@ def _create_one_version_check(ctx, inputs, is_test_rule_class): tools = [tool], outputs = [output], arguments = [args], + use_default_shell_env = True, ) return output diff --git a/java/common/rules/impl/java_helper.bzl b/java/common/rules/impl/java_helper.bzl index fa828986..d491dfc6 100644 --- a/java/common/rules/impl/java_helper.bzl +++ b/java/common/rules/impl/java_helper.bzl @@ -366,6 +366,7 @@ def _create_single_jar( tools = [toolchain.single_jar], outputs = [output], arguments = [args], + use_default_shell_env = True, ) return output diff --git a/java/common/rules/impl/proguard_validation.bzl b/java/common/rules/impl/proguard_validation.bzl index 18142b35..c31b3575 100644 --- a/java/common/rules/impl/proguard_validation.bzl +++ b/java/common/rules/impl/proguard_validation.bzl @@ -43,6 +43,7 @@ def _validate_spec(ctx, spec_file): inputs = [spec_file], outputs = [validated_proguard_spec], toolchain = Label(semantics.JAVA_TOOLCHAIN_TYPE), + use_default_shell_env = True, ) return validated_proguard_spec diff --git a/java/java_single_jar.bzl b/java/java_single_jar.bzl index 6e85bdef..6812fcff 100644 --- a/java/java_single_jar.bzl +++ b/java/java_single_jar.bzl @@ -62,6 +62,7 @@ def _java_single_jar(ctx): progress_message = "Merging into %s" % ctx.outputs.jar.short_path, mnemonic = "JavaSingleJar", executable = ctx.executable._singlejar, + use_default_shell_env = True, ) files = depset([ctx.outputs.jar]) diff --git a/toolchains/bootclasspath.bzl b/toolchains/bootclasspath.bzl index b6f57e00..1a2f5536 100644 --- a/toolchains/bootclasspath.bzl +++ b/toolchains/bootclasspath.bzl @@ -135,6 +135,7 @@ def _bootclasspath_impl(ctx): arguments = [args], env = env, execution_requirements = _SUPPORTS_PATH_MAPPING, + use_default_shell_env = True, ) bootclasspath = ctx.outputs.output_jar @@ -202,6 +203,7 @@ Rerun with --toolchain_resolution_debug='@bazel_tools//tools/jdk:bootstrap_runti arguments = [args], env = env, execution_requirements = _SUPPORTS_PATH_MAPPING, + use_default_shell_env = True, ) return [ DefaultInfo(files = depset([bootclasspath])), From 05ee69248c4ac3014399fbcc4052f9c17497ba2e Mon Sep 17 00:00:00 2001 From: James Jenkins Date: Fri, 28 Mar 2025 10:17:21 -0700 Subject: [PATCH 231/465] Add ppc64le platform support (#274) The platforms bazel module now defines a separate constraint for ppc6l4e. Utilize the new constraint value for the ppc64le architecture. Closes #274 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/274 from Jenkins-J:ppc64le-platforms-support a12036ea1cbe9212673b0dfb1b41f82035e61724 PiperOrigin-RevId: 741565913 Change-Id: Iaf58016a69c5a170b2508489ae9a2156c8dc7d3b --- MODULE.bazel | 2 +- java/bazel/repositories_util.bzl | 10 +++------- java/repositories.bzl | 6 +++--- java/rules_java_deps.bzl | 9 +++++++++ 4 files changed, 16 insertions(+), 11 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 2eed88ac..e83b4687 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -5,7 +5,7 @@ module( compatibility_level = 1, ) -bazel_dep(name = "platforms", version = "0.0.4") +bazel_dep(name = "platforms", version = "0.0.11") bazel_dep(name = "rules_cc", version = "0.0.15") bazel_dep(name = "bazel_features", version = "1.11.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") diff --git a/java/bazel/repositories_util.bzl b/java/bazel/repositories_util.bzl index efe72be1..38170c13 100644 --- a/java/bazel/repositories_util.bzl +++ b/java/bazel/repositories_util.bzl @@ -44,7 +44,7 @@ _RELEASE_CONFIGS = { "adoptium": { "release": "11.0.26+4", "platforms": { - "linux": ["ppc", "s390x"], + "linux": ["ppc64le", "s390x"], }, }, "microsoft": { @@ -66,7 +66,7 @@ _RELEASE_CONFIGS = { "adoptium": { "release": "17.0.14+7", "platforms": { - "linux": ["ppc", "s390x"], + "linux": ["ppc64le", "s390x"], }, }, }, @@ -82,7 +82,7 @@ _RELEASE_CONFIGS = { "adoptium": { "release": "21.0.6+7", "platforms": { - "linux": ["ppc", "riscv64", "s390x"], + "linux": ["ppc64le", "riscv64", "s390x"], }, }, }, @@ -97,8 +97,6 @@ def _name_for_remote_jdk(version, os, cpu): os_part = "win" if (os == "windows" and version != "8") else os if cpu == "x86_64": suffix = "" - elif cpu == "ppc": - suffix = "_ppc64le" else: suffix = "_" + cpu return prefix + version + "_" + os_part + suffix @@ -126,8 +124,6 @@ def _zulu_remote_jdk_repo(os, cpu, release): def _adoptium_linux_remote_jdk_repo(version, cpu, release): os = "linux" arch = cpu - if cpu == "ppc": - arch = "ppc64le" archive_name = "OpenJDK" + version + "U-jdk_" + arch + "_" + os + "_hotspot_" + release.replace("+", "_") + ".tar.gz" primary_url = "github.com/adoptium/temurin" + version + "-binaries/releases/download/jdk-" + release + "/" + archive_name urls = [ diff --git a/java/repositories.bzl b/java/repositories.bzl index 952b9f2f..edc7a2da 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -167,7 +167,7 @@ _REMOTE_JDK_CONFIGS_LIST = [ ), struct( name = "remotejdk11_linux_ppc64le", - target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc"], + target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc64le"], sha256 = "42c63651125a149cee2ba781300d75ffa67a25032f95038d50ee6d6177cb2e41", strip_prefix = "jdk-11.0.26+4", urls = ["https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.26+4/OpenJDK11U-jdk_ppc64le_linux_hotspot_11.0.26_4.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.26+4/OpenJDK11U-jdk_ppc64le_linux_hotspot_11.0.26_4.tar.gz"], @@ -239,7 +239,7 @@ _REMOTE_JDK_CONFIGS_LIST = [ ), struct( name = "remotejdk17_linux_ppc64le", - target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc"], + target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc64le"], sha256 = "f4cb9ee5906a44d110fa381310cd7181d95498d27087d449e7e9b74bddd9def2", strip_prefix = "jdk-17.0.14+7", urls = ["https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14+7/OpenJDK17U-jdk_ppc64le_linux_hotspot_17.0.14_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14+7/OpenJDK17U-jdk_ppc64le_linux_hotspot_17.0.14_7.tar.gz"], @@ -303,7 +303,7 @@ _REMOTE_JDK_CONFIGS_LIST = [ ), struct( name = "remotejdk21_linux_ppc64le", - target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc"], + target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc64le"], sha256 = "163724b70b86d5a8461f85092165a9cc5a098ed900fee90d1b0c0be9607ae3d2", strip_prefix = "jdk-21.0.6+7", urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.6_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.6_7.tar.gz"], diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl index b088f4de..3bc8b8ba 100644 --- a/java/rules_java_deps.bzl +++ b/java/rules_java_deps.bzl @@ -156,6 +156,14 @@ def bazel_skylib_repo(): ], ) +def platforms_repo(): + maybe( + http_archive, + name = "platforms", + sha256 = "29742e87275809b5e598dc2f04d86960cc7a55b3067d97221c9abbc9926bff0f", + urls = ["https://github.com/bazelbuild/platforms/releases/download/0.0.11/platforms-0.0.11.tar.gz"], + ) + def rules_java_dependencies(): """An utility method to load non-toolchain dependencies of rules_java. @@ -165,3 +173,4 @@ def rules_java_dependencies(): bazel_skylib_repo() rules_cc_repo() protobuf_repo() + platforms_repo() From 1ae8105df1a007cede86692a216c596015be8d3b Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 2 Apr 2025 02:46:40 -0700 Subject: [PATCH 232/465] Migrate the `JavaInfoStarlarkApiTest.javaOutputSourceJarsReturnsDepsetWithIncompatibleFlagEnabled` test to Starlark The test is removed from Bazel and added to `@rules_java` PiperOrigin-RevId: 743049290 Change-Id: I482348db828e26d20eb798eabbf45ce8f5935168 --- java/test/common/java_info_tests.bzl | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/java/test/common/java_info_tests.bzl b/java/test/common/java_info_tests.bzl index bd77c6bc..f3dd3f23 100644 --- a/java/test/common/java_info_tests.bzl +++ b/java/test/common/java_info_tests.bzl @@ -1244,6 +1244,24 @@ def _compilation_info_test_impl(env, target): assert_info.runtime_classpath().contains_exactly(["{package}/lib{name}.jar"]) assert_info.javac_options().contains_at_least(["opt1", "opt2"]).in_order() +def _output_source_jars_returns_depset_test(name): + target_name = name + "/lib" + util.helper_target( + java_library, + name = target_name, + ) + + analysis_test( + name = name, + impl = _output_source_jars_returns_depset_test_impl, + target = target_name, + attr_values = {"tags": ["min_bazel_7"]}, # changed in Bazel 7 + ) + +def _output_source_jars_returns_depset_test_impl(env, target): + source_jars = target[JavaInfo].java_outputs[0].source_jars + env.expect.that_str(type(source_jars)).equals(type(depset())) + def java_info_tests(name): test_suite( name = name, @@ -1287,5 +1305,6 @@ def java_info_tests(name): _native_libraries_propagation_test, _annotation_processing_test, _compilation_info_test, + _output_source_jars_returns_depset_test, ], ) From 881ad6a859ee2fdd97922667cc72867e28cf46d4 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 3 Apr 2025 05:47:18 -0700 Subject: [PATCH 233/465] Move `@rules_java//java/test` to `@rules_java//test/java` (ignore-relnotes) PiperOrigin-RevId: 743526819 Change-Id: I0cb265b60b5f040144e85f0571d3aedd2024b64b --- .bazelci/presubmit.yml | 7 +++---- java/common/rules/impl/java_helper.bzl | 2 +- java/common/rules/rule_util.bzl | 2 +- {java/test => test/java}/BUILD | 0 {java/test => test/java}/common/BUILD | 0 {java/test => test/java}/common/java_common_tests.bzl | 0 {java/test => test/java}/common/java_info_tests.bzl | 0 {java/test => test/java}/common/java_plugin_info_tests.bzl | 0 {java/test => test/java}/common/rules/BUILD | 0 .../test => test/java}/common/rules/java_binary_tests.bzl | 0 .../test => test/java}/common/rules/java_import_tests.bzl | 0 .../test => test/java}/common/rules/java_library_tests.bzl | 0 .../test => test/java}/common/rules/java_plugin_tests.bzl | 0 {java/test => test/java}/common/rules/java_test_tests.bzl | 0 .../test => test/java}/common/rules/merge_attrs_tests.bzl | 0 {java/test => test/java}/private/BUILD | 0 {java/test => test/java}/private/android_support_tests.bzl | 2 +- .../java/com/google/devtools/build/runfiles/BUILD.bazel | 0 .../com/google/devtools/build/runfiles/RunfilesTest.java | 0 .../java/com/google/devtools/build/runfiles/UtilTest.java | 0 {java/test => test/java}/toolchains/BUILD | 0 {java/test => test/java}/toolchains/java_runtime_tests.bzl | 0 .../test => test/java}/toolchains/java_toolchain_tests.bzl | 0 23 files changed, 6 insertions(+), 7 deletions(-) rename {java/test => test/java}/BUILD (100%) rename {java/test => test/java}/common/BUILD (100%) rename {java/test => test/java}/common/java_common_tests.bzl (100%) rename {java/test => test/java}/common/java_info_tests.bzl (100%) rename {java/test => test/java}/common/java_plugin_info_tests.bzl (100%) rename {java/test => test/java}/common/rules/BUILD (100%) rename {java/test => test/java}/common/rules/java_binary_tests.bzl (100%) rename {java/test => test/java}/common/rules/java_import_tests.bzl (100%) rename {java/test => test/java}/common/rules/java_library_tests.bzl (100%) rename {java/test => test/java}/common/rules/java_plugin_tests.bzl (100%) rename {java/test => test/java}/common/rules/java_test_tests.bzl (100%) rename {java/test => test/java}/common/rules/merge_attrs_tests.bzl (100%) rename {java/test => test/java}/private/BUILD (100%) rename {java/test => test/java}/private/android_support_tests.bzl (96%) rename {java/test => test/java}/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel (100%) rename {java/test => test/java}/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java (100%) rename {java/test => test/java}/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java (100%) rename {java/test => test/java}/toolchains/BUILD (100%) rename {java/test => test/java}/toolchains/java_runtime_tests.bzl (100%) rename {java/test => test/java}/toolchains/java_toolchain_tests.bzl (100%) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index bf63f3c7..ab032307 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -2,7 +2,7 @@ build_targets: &build_targets - "//..." # can't build some analysis tests on older Bazel versions - - "-//java/test/..." + - "-//test/java/..." - "@remote_java_tools//java_tools/..." # can't build @remote_java_tools_X repos for other platforms - "-//toolchains/..." @@ -21,13 +21,12 @@ build_targets_integration: &build_targets_integration test_targets: &test_targets - "//test/..." - - "//java/test/..." # TODO: re-enable docs after moving them out of https://bazel.build/reference/be/java - "-//test:docs_up_to_date_test" test_targets_bazel6: &test_targets_bazel6 - - "//java/test/..." - - "-//java/test/private/..." + - "//test/java/..." + - "-//test/java/private/..." test_target_integration: &test_target_integration - "//:MyTest" diff --git a/java/common/rules/impl/java_helper.bzl b/java/common/rules/impl/java_helper.bzl index d491dfc6..c97d0060 100644 --- a/java/common/rules/impl/java_helper.bzl +++ b/java/common/rules/impl/java_helper.bzl @@ -20,7 +20,7 @@ load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_helper.bzl", "cc_helper") load("//java/common:java_semantics.bzl", "semantics") -# copybara: default visibility +# copybara: rules_java visibility def _collect_all_targets_as_deps(ctx, classpath_type = "all"): deps = [] diff --git a/java/common/rules/rule_util.bzl b/java/common/rules/rule_util.bzl index dc62252c..724b2784 100644 --- a/java/common/rules/rule_util.bzl +++ b/java/common/rules/rule_util.bzl @@ -13,7 +13,7 @@ # limitations under the License. """Defines rule utilities.""" -# copybara: default visibility +# copybara: rules_java visibility def merge_attrs(*attribute_dicts, override_attrs = {}, remove_attrs = []): """Merges attributes together. diff --git a/java/test/BUILD b/test/java/BUILD similarity index 100% rename from java/test/BUILD rename to test/java/BUILD diff --git a/java/test/common/BUILD b/test/java/common/BUILD similarity index 100% rename from java/test/common/BUILD rename to test/java/common/BUILD diff --git a/java/test/common/java_common_tests.bzl b/test/java/common/java_common_tests.bzl similarity index 100% rename from java/test/common/java_common_tests.bzl rename to test/java/common/java_common_tests.bzl diff --git a/java/test/common/java_info_tests.bzl b/test/java/common/java_info_tests.bzl similarity index 100% rename from java/test/common/java_info_tests.bzl rename to test/java/common/java_info_tests.bzl diff --git a/java/test/common/java_plugin_info_tests.bzl b/test/java/common/java_plugin_info_tests.bzl similarity index 100% rename from java/test/common/java_plugin_info_tests.bzl rename to test/java/common/java_plugin_info_tests.bzl diff --git a/java/test/common/rules/BUILD b/test/java/common/rules/BUILD similarity index 100% rename from java/test/common/rules/BUILD rename to test/java/common/rules/BUILD diff --git a/java/test/common/rules/java_binary_tests.bzl b/test/java/common/rules/java_binary_tests.bzl similarity index 100% rename from java/test/common/rules/java_binary_tests.bzl rename to test/java/common/rules/java_binary_tests.bzl diff --git a/java/test/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl similarity index 100% rename from java/test/common/rules/java_import_tests.bzl rename to test/java/common/rules/java_import_tests.bzl diff --git a/java/test/common/rules/java_library_tests.bzl b/test/java/common/rules/java_library_tests.bzl similarity index 100% rename from java/test/common/rules/java_library_tests.bzl rename to test/java/common/rules/java_library_tests.bzl diff --git a/java/test/common/rules/java_plugin_tests.bzl b/test/java/common/rules/java_plugin_tests.bzl similarity index 100% rename from java/test/common/rules/java_plugin_tests.bzl rename to test/java/common/rules/java_plugin_tests.bzl diff --git a/java/test/common/rules/java_test_tests.bzl b/test/java/common/rules/java_test_tests.bzl similarity index 100% rename from java/test/common/rules/java_test_tests.bzl rename to test/java/common/rules/java_test_tests.bzl diff --git a/java/test/common/rules/merge_attrs_tests.bzl b/test/java/common/rules/merge_attrs_tests.bzl similarity index 100% rename from java/test/common/rules/merge_attrs_tests.bzl rename to test/java/common/rules/merge_attrs_tests.bzl diff --git a/java/test/private/BUILD b/test/java/private/BUILD similarity index 100% rename from java/test/private/BUILD rename to test/java/private/BUILD diff --git a/java/test/private/android_support_tests.bzl b/test/java/private/android_support_tests.bzl similarity index 96% rename from java/test/private/android_support_tests.bzl rename to test/java/private/android_support_tests.bzl index 13227f75..11aab593 100644 --- a/java/test/private/android_support_tests.bzl +++ b/test/java/private/android_support_tests.bzl @@ -17,7 +17,7 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") load("//java:defs.bzl", "java_library", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") -load("//java/private:android_support.bzl", "android_support") +load("//java/private:android_support.bzl", "android_support") # buildifier: disable=bzl-visibility load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") def _impl(ctx): diff --git a/java/test/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel b/test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel similarity index 100% rename from java/test/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel rename to test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel diff --git a/java/test/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java b/test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java similarity index 100% rename from java/test/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java rename to test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java diff --git a/java/test/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java b/test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java similarity index 100% rename from java/test/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java rename to test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java diff --git a/java/test/toolchains/BUILD b/test/java/toolchains/BUILD similarity index 100% rename from java/test/toolchains/BUILD rename to test/java/toolchains/BUILD diff --git a/java/test/toolchains/java_runtime_tests.bzl b/test/java/toolchains/java_runtime_tests.bzl similarity index 100% rename from java/test/toolchains/java_runtime_tests.bzl rename to test/java/toolchains/java_runtime_tests.bzl diff --git a/java/test/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl similarity index 100% rename from java/test/toolchains/java_toolchain_tests.bzl rename to test/java/toolchains/java_toolchain_tests.bzl From fe4c5ac35b273c539a2cefbfd21edc2e3cc17922 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 4 Apr 2025 05:23:52 -0700 Subject: [PATCH 234/465] Move `@rules_java//java/test/testutil/rules` to `@rules_java//test/java/testutil/rules` (ignore-relnotes) PiperOrigin-RevId: 743905715 Change-Id: Ic1333ee174d84781eba0236152b44b4ffcd47de3 --- test/java/common/java_common_tests.bzl | 18 +++++++++--------- test/java/common/java_info_tests.bzl | 6 +++--- test/java/common/java_plugin_info_tests.bzl | 2 +- test/java/common/rules/java_binary_tests.bzl | 4 ++-- test/java/common/rules/java_import_tests.bzl | 2 +- test/java/common/rules/java_library_tests.bzl | 6 +++--- test/java/common/rules/java_test_tests.bzl | 2 +- test/java/testutil/BUILD | 0 .../testutil/rules/bad_java_info_rules.bzl | 0 .../testutil/rules/custom_java_info_rule.bzl | 0 .../java}/testutil/rules/custom_library.bzl | 0 .../custom_library_extended_compile_jdeps.bzl | 0 .../custom_library_with_additional_inputs.bzl | 0 .../custom_library_with_bootclasspath.bzl | 0 ...m_library_with_custom_output_source_jar.bzl | 0 .../rules/custom_library_with_exports.bzl | 0 .../custom_library_with_named_outputs.bzl | 0 .../rules/custom_library_with_sourcepaths.bzl | 0 .../custom_library_with_wrong_plugins_type.bzl | 0 .../java}/testutil/rules/custom_plugin.bzl | 0 .../java}/testutil/rules/forward_java_info.bzl | 0 .../rules/forward_java_runtime_info.bzl | 0 .../java}/testutil/rules/wrap_java_info.bzl | 0 test/java/toolchains/java_runtime_tests.bzl | 2 +- 24 files changed, 21 insertions(+), 21 deletions(-) create mode 100644 test/java/testutil/BUILD rename {java/test => test/java}/testutil/rules/bad_java_info_rules.bzl (100%) rename {java/test => test/java}/testutil/rules/custom_java_info_rule.bzl (100%) rename {java/test => test/java}/testutil/rules/custom_library.bzl (100%) rename {java/test => test/java}/testutil/rules/custom_library_extended_compile_jdeps.bzl (100%) rename {java/test => test/java}/testutil/rules/custom_library_with_additional_inputs.bzl (100%) rename {java/test => test/java}/testutil/rules/custom_library_with_bootclasspath.bzl (100%) rename {java/test => test/java}/testutil/rules/custom_library_with_custom_output_source_jar.bzl (100%) rename {java/test => test/java}/testutil/rules/custom_library_with_exports.bzl (100%) rename {java/test => test/java}/testutil/rules/custom_library_with_named_outputs.bzl (100%) rename {java/test => test/java}/testutil/rules/custom_library_with_sourcepaths.bzl (100%) rename {java/test => test/java}/testutil/rules/custom_library_with_wrong_plugins_type.bzl (100%) rename {java/test => test/java}/testutil/rules/custom_plugin.bzl (100%) rename {java/test => test/java}/testutil/rules/forward_java_info.bzl (100%) rename {java/test => test/java}/testutil/rules/forward_java_runtime_info.bzl (100%) rename {java/test => test/java}/testutil/rules/wrap_java_info.bzl (100%) diff --git a/test/java/common/java_common_tests.bzl b/test/java/common/java_common_tests.bzl index 8a37f677..94d58b98 100644 --- a/test/java/common/java_common_tests.bzl +++ b/test/java/common/java_common_tests.bzl @@ -11,15 +11,15 @@ load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/test/testutil:artifact_closure.bzl", "artifact_closure") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") -load("//java/test/testutil:rules/custom_library.bzl", "custom_library") -load("//java/test/testutil:rules/custom_library_extended_compile_jdeps.bzl", "CompileJdepsInfo", "custom_library_extended_jdeps") -load("//java/test/testutil:rules/custom_library_with_additional_inputs.bzl", "custom_library_with_additional_inputs") -load("//java/test/testutil:rules/custom_library_with_bootclasspath.bzl", "custom_bootclasspath", "custom_library_with_bootclasspath") -load("//java/test/testutil:rules/custom_library_with_custom_output_source_jar.bzl", "custom_library_with_custom_output_source_jar") -load("//java/test/testutil:rules/custom_library_with_exports.bzl", "custom_library_with_exports") -load("//java/test/testutil:rules/custom_library_with_named_outputs.bzl", "custom_library_with_named_outputs") -load("//java/test/testutil:rules/custom_library_with_sourcepaths.bzl", "custom_library_with_sourcepaths") -load("//java/test/testutil:rules/custom_library_with_wrong_plugins_type.bzl", "custom_library_with_wrong_plugins_type") +load("//test/java/testutil:rules/custom_library.bzl", "custom_library") +load("//test/java/testutil:rules/custom_library_extended_compile_jdeps.bzl", "CompileJdepsInfo", "custom_library_extended_jdeps") +load("//test/java/testutil:rules/custom_library_with_additional_inputs.bzl", "custom_library_with_additional_inputs") +load("//test/java/testutil:rules/custom_library_with_bootclasspath.bzl", "custom_bootclasspath", "custom_library_with_bootclasspath") +load("//test/java/testutil:rules/custom_library_with_custom_output_source_jar.bzl", "custom_library_with_custom_output_source_jar") +load("//test/java/testutil:rules/custom_library_with_exports.bzl", "custom_library_with_exports") +load("//test/java/testutil:rules/custom_library_with_named_outputs.bzl", "custom_library_with_named_outputs") +load("//test/java/testutil:rules/custom_library_with_sourcepaths.bzl", "custom_library_with_sourcepaths") +load("//test/java/testutil:rules/custom_library_with_wrong_plugins_type.bzl", "custom_library_with_wrong_plugins_type") def _test_compile_default_values(name): util.helper_target(custom_library, name = name + "/custom", srcs = ["Main.java"]) diff --git a/test/java/common/java_info_tests.bzl b/test/java/common/java_info_tests.bzl index f3dd3f23..9a6a5601 100644 --- a/test/java/common/java_info_tests.bzl +++ b/test/java/common/java_info_tests.bzl @@ -8,9 +8,9 @@ load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") -load("//java/test/testutil:rules/bad_java_info_rules.bzl", "bad_deps", "bad_exports", "bad_libs", "bad_runtime_deps", "compile_jar_not_set", "compile_jar_set_to_none") -load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") -load("//java/test/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") +load("//test/java/testutil:rules/bad_java_info_rules.bzl", "bad_deps", "bad_exports", "bad_libs", "bad_runtime_deps", "compile_jar_not_set", "compile_jar_set_to_none") +load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") +load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") def _with_output_jar_only_test(name): target_name = name + "/my_starlark_rule" diff --git a/test/java/common/java_plugin_info_tests.bzl b/test/java/common/java_plugin_info_tests.bzl index c8cd28e1..f74f6c5f 100644 --- a/test/java/common/java_plugin_info_tests.bzl +++ b/test/java/common/java_plugin_info_tests.bzl @@ -6,7 +6,7 @@ load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//java/test/testutil:java_info_subject.bzl", "java_plugin_info_subject") -load("//java/test/testutil:rules/custom_plugin.bzl", "custom_plugin") +load("//test/java/testutil:rules/custom_plugin.bzl", "custom_plugin") def _test_exposes_java_outputs(name): util.helper_target( diff --git a/test/java/common/rules/java_binary_tests.bzl b/test/java/common/rules/java_binary_tests.bzl index f16898d9..b408504b 100644 --- a/test/java/common/rules/java_binary_tests.bzl +++ b/test/java/common/rules/java_binary_tests.bzl @@ -8,8 +8,8 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") -load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") -load("//java/test/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") +load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") +load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") def _test_java_binary_provides_binary_java_info(name): util.helper_target(java_binary, name = "bin", srcs = ["Main.java"]) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index ca54e7fe..fddfe188 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -6,7 +6,7 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_import.bzl", "java_import") load("//java:java_library.bzl", "java_library") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") -load("//java/test/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") +load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") def _test_java_import_attributes(name): target_name = name + "/import" diff --git a/test/java/common/rules/java_library_tests.bzl b/test/java/common/rules/java_library_tests.bzl index 283cf57d..01674c1d 100644 --- a/test/java/common/rules/java_library_tests.bzl +++ b/test/java/common/rules/java_library_tests.bzl @@ -9,9 +9,9 @@ load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") -load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") -load("//java/test/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") -load("//java/test/testutil:rules/wrap_java_info.bzl", "JavaInfoWrappingInfo", "java_info_wrapping_rule") +load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") +load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") +load("//test/java/testutil:rules/wrap_java_info.bzl", "JavaInfoWrappingInfo", "java_info_wrapping_rule") def _test_exposes_plugins(name): target_name = name + "/library" diff --git a/test/java/common/rules/java_test_tests.bzl b/test/java/common/rules/java_test_tests.bzl index 5a6a9a8f..4cc39ca2 100644 --- a/test/java/common/rules/java_test_tests.bzl +++ b/test/java/common/rules/java_test_tests.bzl @@ -7,7 +7,7 @@ load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_test.bzl", "java_test") -load("//java/test/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") +load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") def _test_java_test_propagates_direct_native_libraries(name): util.helper_target( diff --git a/test/java/testutil/BUILD b/test/java/testutil/BUILD new file mode 100644 index 00000000..e69de29b diff --git a/java/test/testutil/rules/bad_java_info_rules.bzl b/test/java/testutil/rules/bad_java_info_rules.bzl similarity index 100% rename from java/test/testutil/rules/bad_java_info_rules.bzl rename to test/java/testutil/rules/bad_java_info_rules.bzl diff --git a/java/test/testutil/rules/custom_java_info_rule.bzl b/test/java/testutil/rules/custom_java_info_rule.bzl similarity index 100% rename from java/test/testutil/rules/custom_java_info_rule.bzl rename to test/java/testutil/rules/custom_java_info_rule.bzl diff --git a/java/test/testutil/rules/custom_library.bzl b/test/java/testutil/rules/custom_library.bzl similarity index 100% rename from java/test/testutil/rules/custom_library.bzl rename to test/java/testutil/rules/custom_library.bzl diff --git a/java/test/testutil/rules/custom_library_extended_compile_jdeps.bzl b/test/java/testutil/rules/custom_library_extended_compile_jdeps.bzl similarity index 100% rename from java/test/testutil/rules/custom_library_extended_compile_jdeps.bzl rename to test/java/testutil/rules/custom_library_extended_compile_jdeps.bzl diff --git a/java/test/testutil/rules/custom_library_with_additional_inputs.bzl b/test/java/testutil/rules/custom_library_with_additional_inputs.bzl similarity index 100% rename from java/test/testutil/rules/custom_library_with_additional_inputs.bzl rename to test/java/testutil/rules/custom_library_with_additional_inputs.bzl diff --git a/java/test/testutil/rules/custom_library_with_bootclasspath.bzl b/test/java/testutil/rules/custom_library_with_bootclasspath.bzl similarity index 100% rename from java/test/testutil/rules/custom_library_with_bootclasspath.bzl rename to test/java/testutil/rules/custom_library_with_bootclasspath.bzl diff --git a/java/test/testutil/rules/custom_library_with_custom_output_source_jar.bzl b/test/java/testutil/rules/custom_library_with_custom_output_source_jar.bzl similarity index 100% rename from java/test/testutil/rules/custom_library_with_custom_output_source_jar.bzl rename to test/java/testutil/rules/custom_library_with_custom_output_source_jar.bzl diff --git a/java/test/testutil/rules/custom_library_with_exports.bzl b/test/java/testutil/rules/custom_library_with_exports.bzl similarity index 100% rename from java/test/testutil/rules/custom_library_with_exports.bzl rename to test/java/testutil/rules/custom_library_with_exports.bzl diff --git a/java/test/testutil/rules/custom_library_with_named_outputs.bzl b/test/java/testutil/rules/custom_library_with_named_outputs.bzl similarity index 100% rename from java/test/testutil/rules/custom_library_with_named_outputs.bzl rename to test/java/testutil/rules/custom_library_with_named_outputs.bzl diff --git a/java/test/testutil/rules/custom_library_with_sourcepaths.bzl b/test/java/testutil/rules/custom_library_with_sourcepaths.bzl similarity index 100% rename from java/test/testutil/rules/custom_library_with_sourcepaths.bzl rename to test/java/testutil/rules/custom_library_with_sourcepaths.bzl diff --git a/java/test/testutil/rules/custom_library_with_wrong_plugins_type.bzl b/test/java/testutil/rules/custom_library_with_wrong_plugins_type.bzl similarity index 100% rename from java/test/testutil/rules/custom_library_with_wrong_plugins_type.bzl rename to test/java/testutil/rules/custom_library_with_wrong_plugins_type.bzl diff --git a/java/test/testutil/rules/custom_plugin.bzl b/test/java/testutil/rules/custom_plugin.bzl similarity index 100% rename from java/test/testutil/rules/custom_plugin.bzl rename to test/java/testutil/rules/custom_plugin.bzl diff --git a/java/test/testutil/rules/forward_java_info.bzl b/test/java/testutil/rules/forward_java_info.bzl similarity index 100% rename from java/test/testutil/rules/forward_java_info.bzl rename to test/java/testutil/rules/forward_java_info.bzl diff --git a/java/test/testutil/rules/forward_java_runtime_info.bzl b/test/java/testutil/rules/forward_java_runtime_info.bzl similarity index 100% rename from java/test/testutil/rules/forward_java_runtime_info.bzl rename to test/java/testutil/rules/forward_java_runtime_info.bzl diff --git a/java/test/testutil/rules/wrap_java_info.bzl b/test/java/testutil/rules/wrap_java_info.bzl similarity index 100% rename from java/test/testutil/rules/wrap_java_info.bzl rename to test/java/testutil/rules/wrap_java_info.bzl diff --git a/test/java/toolchains/java_runtime_tests.bzl b/test/java/toolchains/java_runtime_tests.bzl index 2f2b86d2..9efd0d23 100644 --- a/test/java/toolchains/java_runtime_tests.bzl +++ b/test/java/toolchains/java_runtime_tests.bzl @@ -4,8 +4,8 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") load("//java/common:java_semantics.bzl", "semantics") load("//java/test/testutil:java_runtime_info_subject.bzl", "java_runtime_info_subject") -load("//java/test/testutil:rules/forward_java_runtime_info.bzl", "java_runtime_info_forwarding_rule") load("//java/toolchains:java_runtime.bzl", "java_runtime") +load("//test/java/testutil:rules/forward_java_runtime_info.bzl", "java_runtime_info_forwarding_rule") load("//toolchains:java_toolchain_alias.bzl", "java_runtime_alias") def _test_with_absolute_java_home(name): From 8e0fe0bac1e890fb438e26b69437784ac3cc5b66 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 7 Apr 2025 03:08:08 -0700 Subject: [PATCH 235/465] Move the rest of `@rules_java//java/test/testutil` to `@rules_java//test/java/testutil` We expose a couple of private APIs from the new `//java/testutil.bzl` in light of https://github.com/bazelbuild/bazel/commit/176b9b4df99299efb1e1e10f0c919ae58be025ba (ignore-relnotes) PiperOrigin-RevId: 744652502 Change-Id: I9405ee71221007457f66e73a79e514198a7802ae --- java/test/testutil/BUILD | 0 java/testutil.bzl | 16 ++++++++++++++++ test/java/common/java_common_tests.bzl | 4 ++-- test/java/common/java_info_tests.bzl | 2 +- test/java/common/java_plugin_info_tests.bzl | 2 +- test/java/common/rules/java_binary_tests.bzl | 2 +- test/java/common/rules/java_import_tests.bzl | 2 +- test/java/common/rules/java_library_tests.bzl | 2 +- test/java/common/rules/java_plugin_tests.bzl | 2 +- test/java/private/android_support_tests.bzl | 2 +- .../java}/testutil/artifact_closure.bzl | 0 .../java}/testutil/cc_info_subject.bzl | 5 +++-- .../java}/testutil/java_info_subject.bzl | 0 .../java}/testutil/java_runtime_info_subject.bzl | 0 .../testutil/java_toolchain_info_subject.bzl | 0 test/java/toolchains/java_runtime_tests.bzl | 2 +- test/java/toolchains/java_toolchain_tests.bzl | 2 +- 17 files changed, 30 insertions(+), 13 deletions(-) delete mode 100644 java/test/testutil/BUILD create mode 100644 java/testutil.bzl rename {java/test => test/java}/testutil/artifact_closure.bzl (100%) rename {java/test => test/java}/testutil/cc_info_subject.bzl (91%) rename {java/test => test/java}/testutil/java_info_subject.bzl (100%) rename {java/test => test/java}/testutil/java_runtime_info_subject.bzl (100%) rename {java/test => test/java}/testutil/java_toolchain_info_subject.bzl (100%) diff --git a/java/test/testutil/BUILD b/java/test/testutil/BUILD deleted file mode 100644 index e69de29b..00000000 diff --git a/java/testutil.bzl b/java/testutil.bzl new file mode 100644 index 00000000..26823ba8 --- /dev/null +++ b/java/testutil.bzl @@ -0,0 +1,16 @@ +"""Exposes some private APIs for tests""" + +# copybara: rules_java visibility + +# TODO: consider eventually upstreaming to rules_cc + +def _cc_info_transitive_native_libraries(cc_info): + return cc_info.transitive_native_libraries() + +def _cc_library_to_link_identifier(library_to_link): + return library_to_link.library_identifier() + +testutil = struct( + cc_info_transitive_native_libraries = _cc_info_transitive_native_libraries, + cc_library_to_link_identifier = _cc_library_to_link_identifier, +) diff --git a/test/java/common/java_common_tests.bzl b/test/java/common/java_common_tests.bzl index 94d58b98..26afce51 100644 --- a/test/java/common/java_common_tests.bzl +++ b/test/java/common/java_common_tests.bzl @@ -9,8 +9,8 @@ load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") -load("//java/test/testutil:artifact_closure.bzl", "artifact_closure") -load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:artifact_closure.bzl", "artifact_closure") +load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:rules/custom_library.bzl", "custom_library") load("//test/java/testutil:rules/custom_library_extended_compile_jdeps.bzl", "CompileJdepsInfo", "custom_library_extended_jdeps") load("//test/java/testutil:rules/custom_library_with_additional_inputs.bzl", "custom_library_with_additional_inputs") diff --git a/test/java/common/java_info_tests.bzl b/test/java/common/java_info_tests.bzl index 9a6a5601..5e95187f 100644 --- a/test/java/common/java_info_tests.bzl +++ b/test/java/common/java_info_tests.bzl @@ -7,7 +7,7 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") -load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:rules/bad_java_info_rules.bzl", "bad_deps", "bad_exports", "bad_libs", "bad_runtime_deps", "compile_jar_not_set", "compile_jar_set_to_none") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") diff --git a/test/java/common/java_plugin_info_tests.bzl b/test/java/common/java_plugin_info_tests.bzl index f74f6c5f..c3b8b378 100644 --- a/test/java/common/java_plugin_info_tests.bzl +++ b/test/java/common/java_plugin_info_tests.bzl @@ -5,7 +5,7 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") -load("//java/test/testutil:java_info_subject.bzl", "java_plugin_info_subject") +load("//test/java/testutil:java_info_subject.bzl", "java_plugin_info_subject") load("//test/java/testutil:rules/custom_plugin.bzl", "custom_plugin") def _test_exposes_java_outputs(name): diff --git a/test/java/common/rules/java_binary_tests.bzl b/test/java/common/rules/java_binary_tests.bzl index b408504b..08386ad1 100644 --- a/test/java/common/rules/java_binary_tests.bzl +++ b/test/java/common/rules/java_binary_tests.bzl @@ -7,7 +7,7 @@ load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") -load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index fddfe188..2b3038d3 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -5,7 +5,7 @@ load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_import.bzl", "java_import") load("//java:java_library.bzl", "java_library") -load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") def _test_java_import_attributes(name): diff --git a/test/java/common/rules/java_library_tests.bzl b/test/java/common/rules/java_library_tests.bzl index 01674c1d..4dca71f4 100644 --- a/test/java/common/rules/java_library_tests.bzl +++ b/test/java/common/rules/java_library_tests.bzl @@ -8,7 +8,7 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") -load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") load("//test/java/testutil:rules/wrap_java_info.bzl", "JavaInfoWrappingInfo", "java_info_wrapping_rule") diff --git a/test/java/common/rules/java_plugin_tests.bzl b/test/java/common/rules/java_plugin_tests.bzl index 047917a9..646de647 100644 --- a/test/java/common/rules/java_plugin_tests.bzl +++ b/test/java/common/rules/java_plugin_tests.bzl @@ -5,7 +5,7 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") -load("//java/test/testutil:java_info_subject.bzl", "java_plugin_info_subject") +load("//test/java/testutil:java_info_subject.bzl", "java_plugin_info_subject") def _test_exposes_plugins_to_starlark(name): target_name = name + "/plugin" diff --git a/test/java/private/android_support_tests.bzl b/test/java/private/android_support_tests.bzl index 11aab593..95596de2 100644 --- a/test/java/private/android_support_tests.bzl +++ b/test/java/private/android_support_tests.bzl @@ -18,7 +18,7 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:defs.bzl", "java_library", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") load("//java/private:android_support.bzl", "android_support") # buildifier: disable=bzl-visibility -load("//java/test/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") def _impl(ctx): return [ diff --git a/java/test/testutil/artifact_closure.bzl b/test/java/testutil/artifact_closure.bzl similarity index 100% rename from java/test/testutil/artifact_closure.bzl rename to test/java/testutil/artifact_closure.bzl diff --git a/java/test/testutil/cc_info_subject.bzl b/test/java/testutil/cc_info_subject.bzl similarity index 91% rename from java/test/testutil/cc_info_subject.bzl rename to test/java/testutil/cc_info_subject.bzl index cf877a22..c3306f68 100644 --- a/java/test/testutil/cc_info_subject.bzl +++ b/test/java/testutil/cc_info_subject.bzl @@ -1,6 +1,7 @@ """A custom @rules_testing subject for the CcInfo provider""" load("@rules_testing//lib:truth.bzl", "subjects") +load("//java:testutil.bzl", "testutil") def _new_cc_info_subject(cc_info, meta): self = struct( @@ -9,7 +10,7 @@ def _new_cc_info_subject(cc_info, meta): ) public = struct( linking_context = lambda: _new_cc_info_linking_context_subject(self.actual, self.meta), - native_libraries = lambda: subjects.collection(self.actual.transitive_native_libraries(), self.meta.derive("transitive_native_libraries()")), + native_libraries = lambda: subjects.collection(testutil.cc_info_transitive_native_libraries(self.actual), self.meta.derive("transitive_native_libraries()")), ) return public @@ -72,7 +73,7 @@ def _new_library_to_link_subject(library_to_link, meta): def _new_library_to_link_identifiers_subject(libraries_to_link, meta): self = subjects.collection( - [lib.library_identifier() for lib in libraries_to_link], + [testutil.cc_library_to_link_identifier(lib) for lib in libraries_to_link], meta = meta.derive("library_identifier()"), ) public = struct( diff --git a/java/test/testutil/java_info_subject.bzl b/test/java/testutil/java_info_subject.bzl similarity index 100% rename from java/test/testutil/java_info_subject.bzl rename to test/java/testutil/java_info_subject.bzl diff --git a/java/test/testutil/java_runtime_info_subject.bzl b/test/java/testutil/java_runtime_info_subject.bzl similarity index 100% rename from java/test/testutil/java_runtime_info_subject.bzl rename to test/java/testutil/java_runtime_info_subject.bzl diff --git a/java/test/testutil/java_toolchain_info_subject.bzl b/test/java/testutil/java_toolchain_info_subject.bzl similarity index 100% rename from java/test/testutil/java_toolchain_info_subject.bzl rename to test/java/testutil/java_toolchain_info_subject.bzl diff --git a/test/java/toolchains/java_runtime_tests.bzl b/test/java/toolchains/java_runtime_tests.bzl index 9efd0d23..4f1ec88a 100644 --- a/test/java/toolchains/java_runtime_tests.bzl +++ b/test/java/toolchains/java_runtime_tests.bzl @@ -3,8 +3,8 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") load("//java/common:java_semantics.bzl", "semantics") -load("//java/test/testutil:java_runtime_info_subject.bzl", "java_runtime_info_subject") load("//java/toolchains:java_runtime.bzl", "java_runtime") +load("//test/java/testutil:java_runtime_info_subject.bzl", "java_runtime_info_subject") load("//test/java/testutil:rules/forward_java_runtime_info.bzl", "java_runtime_info_forwarding_rule") load("//toolchains:java_toolchain_alias.bzl", "java_runtime_alias") diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index 2c4e1000..378ba910 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -2,9 +2,9 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") -load("//java/test/testutil:java_toolchain_info_subject.bzl", "java_toolchain_info_subject") load("//java/toolchains:java_runtime.bzl", "java_runtime") load("//java/toolchains:java_toolchain.bzl", "java_toolchain") +load("//test/java/testutil:java_toolchain_info_subject.bzl", "java_toolchain_info_subject") def _declare_java_toolchain(*, name, **kwargs): if "java_runtime" not in kwargs: From 804e93e70f610a900b55af9208a3ba86fa5f5fcc Mon Sep 17 00:00:00 2001 From: hvadehra Date: Tue, 8 Apr 2025 02:52:06 -0700 Subject: [PATCH 236/465] Update to `java_tools` `v14.0` (#286) Closes #286 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/286 from bazelbuild:hvd_javatools_14 1ba7e5f4efc83391a83b3816af42357f99b97553 PiperOrigin-RevId: 745056329 Change-Id: If9674fb772281cff1aa51cf50b23961469f845cf --- .bazelci/presubmit.yml | 12 ++++++++++-- .bazelrc | 4 ++++ MODULE.bazel | 1 + java/repositories.bzl | 32 ++++++++++++++++---------------- java/rules_java_deps.bzl | 37 +++++++++++++++++++++++++++++++++++++ test/repo/.bazelrc | 4 ++++ test/repo/BUILD.bazel | 3 ++- 7 files changed, 74 insertions(+), 19 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index ab032307..2385fa8b 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -3,7 +3,11 @@ build_targets: &build_targets - "//..." # can't build some analysis tests on older Bazel versions - "-//test/java/..." - - "@remote_java_tools//java_tools/..." + # build java_tools from source + - "@remote_java_tools//:ijar_cc_binary" + - "@remote_java_tools//:one_version_cc_bin" + - "@remote_java_tools//:proguard" + - "@remote_java_tools//:singlejar_cc_bin" # can't build @remote_java_tools_X repos for other platforms - "-//toolchains/..." # TODO: re-enable docs after moving them out of https://bazel.build/reference/be/java @@ -12,7 +16,11 @@ build_targets: &build_targets build_targets_bazel6: &build_targets_bazel6 - "//:all" - - "@remote_java_tools//java_tools/..." + # build java_tools from source + - "@remote_java_tools//:ijar_cc_binary" + - "@remote_java_tools//:one_version_cc_bin" + - "@remote_java_tools//:proguard" + - "@remote_java_tools//:singlejar_cc_bin" - "//examples/..." build_targets_integration: &build_targets_integration diff --git a/.bazelrc b/.bazelrc index b71e7a14..9db5d775 100644 --- a/.bazelrc +++ b/.bazelrc @@ -9,6 +9,10 @@ common --tool_java_runtime_version=remotejdk_8 # Hide Java 8 deprecation warnings. common --javacopt=-Xlint:-options +# Enable modern C++ features, for compiling java_tools from source +build --cxxopt=-std=c++17 +build --host_cxxopt=-std=c++17 + # Some tests relies on dynamic libs that are not interface libs # the latter are always enabled on Windows: https://github.com/bazelbuild/bazel/blob/1f5414408467171581b6142e93f67fe730d722cf/src/main/java/com/google/devtools/build/lib/rules/cpp/CcModule.java#L2430 # we can't use a transition because toolchain deps exceed the default --analysis_testing_deps_limit. diff --git a/MODULE.bazel b/MODULE.bazel index e83b4687..c8994eee 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -10,6 +10,7 @@ bazel_dep(name = "rules_cc", version = "0.0.15") bazel_dep(name = "bazel_features", version = "1.11.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") bazel_dep(name = "protobuf", version = "27.0", repo_name = "com_google_protobuf") +bazel_dep(name = "zlib", version = "1.3.1.bcr.5") # Required by @remote_java_tools, which is loaded via module extension. bazel_dep(name = "rules_license", version = "0.0.3") diff --git a/java/repositories.bzl b/java/repositories.bzl index edc7a2da..ee1d029a 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v13.18", + "version": "v14.0", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.18/java_tools_linux-v13.18.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.18/java_tools_linux-v13.18.zip", - "sha": "0da77fca085dd477a057581f26fe677d88e4b9f542c517d813e50553829f66a0", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v14.0/java_tools_linux-v14.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v14.0/java_tools_linux-v14.0.zip", + "sha": "51ed941d6c62e432e59cc3b6ad3503639cc138ee7a02ed6bf0bbbb16ded418c9", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.18/java_tools_windows-v13.18.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.18/java_tools_windows-v13.18.zip", - "sha": "e07c1604a492a5f316e8d8142446d2b297066d243d4ed3d54324aa89122ca862", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v14.0/java_tools_windows-v14.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v14.0/java_tools_windows-v14.0.zip", + "sha": "3f918fb9c24b04bcd6088ed62c240cfbb1a4bb50376e394151d34d60e8e71cdf", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.18/java_tools_darwin_x86_64-v13.18.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.18/java_tools_darwin_x86_64-v13.18.zip", - "sha": "ecc155c338ab106324dbd036364478b0fd85d4f12d11a95268b6c436b4bb41a2", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v14.0/java_tools_darwin_x86_64-v14.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v14.0/java_tools_darwin_x86_64-v14.0.zip", + "sha": "94daf7d9586943261114de6bde97053597ce031bb8d76672688843b33b7ff610", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.18/java_tools_darwin_arm64-v13.18.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.18/java_tools_darwin_arm64-v13.18.zip", - "sha": "d11cdccc9e906f68137b882d75d485122f3c6a9b50374b6bb2e526384114f897", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v14.0/java_tools_darwin_arm64-v14.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v14.0/java_tools_darwin_arm64-v14.0.zip", + "sha": "5f12ea12d0381058dac8aa85ad3656c3a7ab85b8c5d8cd98e4ab57bd8fbf8bee", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v13.18/java_tools-v13.18.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v13.18/java_tools-v13.18.zip", - "sha": "1945286e31ca21184b672290caa83cc3470dcdbd00ce0af34f02d24398974ebf", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v14.0/java_tools-v14.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v14.0/java_tools-v14.0.zip", + "sha": "1c2074e3ffb8c5bd22d5e65964535f70ba7b1bcd4e688f5d89f79f72a1b625bf", }, }, } diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl index 3bc8b8ba..a3a59aa9 100644 --- a/java/rules_java_deps.bzl +++ b/java/rules_java_deps.bzl @@ -164,6 +164,41 @@ def platforms_repo(): urls = ["https://github.com/bazelbuild/platforms/releases/download/0.0.11/platforms-0.0.11.tar.gz"], ) +def zlib_repo(): + maybe( + http_archive, + name = "zlib", + sha256 = "9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23", + urls = ["https://github.com/madler/zlib/releases/download/v1.3.1/zlib-1.3.1.tar.gz"], + strip_prefix = "zlib-1.3.1", + build_file_content = """ +cc_library( + name = "zlib", + srcs = glob(["*.c"]), + hdrs = glob(["*.h"]), + copts = select({ + "@platforms//os:windows": [], + "//conditions:default": [ + "-Wno-deprecated-non-prototype", + "-Wno-unused-variable", + "-Wno-implicit-function-declaration", + ], + }), + includes = ["."], + visibility = ["//visibility:public"], +) + """, + ) + +def absl_repo(): + maybe( + http_archive, + name = "com_google_absl", + sha256 = "f50e5ac311a81382da7fa75b97310e4b9006474f9560ac46f54a9967f07d4ae3", + strip_prefix = "abseil-cpp-20240722.0", + urls = ["https://github.com/abseil/abseil-cpp/archive/refs/tags/20240722.0.tar.gz"], + ) + def rules_java_dependencies(): """An utility method to load non-toolchain dependencies of rules_java. @@ -174,3 +209,5 @@ def rules_java_dependencies(): rules_cc_repo() protobuf_repo() platforms_repo() + zlib_repo() + absl_repo() diff --git a/test/repo/.bazelrc b/test/repo/.bazelrc index e8aef359..8d0ffca7 100644 --- a/test/repo/.bazelrc +++ b/test/repo/.bazelrc @@ -1,3 +1,7 @@ build:bzlmod --experimental_enable_bzlmod common --incompatible_disallow_empty_glob + +# Enable modern C++ features, for compiling java_tools from source +build --cxxopt=-std=c++17 +build --host_cxxopt=-std=c++17 diff --git a/test/repo/BUILD.bazel b/test/repo/BUILD.bazel index 6522f971..99f63087 100644 --- a/test/repo/BUILD.bazel +++ b/test/repo/BUILD.bazel @@ -1,5 +1,5 @@ load("@rules_java//java:defs.bzl", "java_binary", "java_library", "java_test") # copybara-use-repo-external-label -load("@rules_java//toolchains:default_java_toolchain.bzl", "default_java_toolchain") # copybara-use-repo-external-label +load("@rules_java//toolchains:default_java_toolchain.bzl", "NONPREBUILT_TOOLCHAIN_CONFIGURATION", "default_java_toolchain") # copybara-use-repo-external-label load("@rules_shell//shell:sh_test.bzl", "sh_test") java_library( @@ -50,4 +50,5 @@ sh_test( default_java_toolchain( name = "my_funky_toolchain", bootclasspath = ["@bazel_tools//tools/jdk:platformclasspath"], + configuration = NONPREBUILT_TOOLCHAIN_CONFIGURATION, ) From cce559d807b8af6d3f825c5fe053764e0b5fc631 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 9 Apr 2025 05:16:17 -0700 Subject: [PATCH 237/465] Fix licenses (ignore-relnotes) PiperOrigin-RevId: 745542463 Change-Id: Ie53c52da3856912e276c94f4440dfba36d97eb44 --- BUILD | 9 +++++++++ distro/BUILD.bazel | 5 ++++- examples/hello_world/BUILD | 2 ++ java/BUILD | 5 ++++- java/bazel/BUILD.bazel | 2 ++ java/bazel/common/BUILD.bazel | 2 ++ java/bazel/rules/BUILD.bazel | 2 ++ java/common/BUILD | 5 ++++- java/common/rules/BUILD | 5 ++++- java/common/rules/impl/BUILD | 5 ++++- java/docs/BUILD.bazel | 2 ++ java/private/BUILD | 2 ++ java/proto/BUILD | 5 ++++- java/rules_java_deps.bzl | 12 ++++++++++++ java/runfiles/BUILD | 2 ++ .../java/com/google/devtools/build/runfiles/BUILD | 2 ++ java/toolchains/BUILD | 5 ++++- test/BUILD.bazel | 2 ++ test/java/BUILD | 1 + test/java/common/BUILD | 2 ++ test/java/common/rules/BUILD | 2 ++ test/java/private/BUILD | 2 ++ .../com/google/devtools/build/runfiles/BUILD.bazel | 2 ++ test/java/testutil/BUILD | 1 + test/java/toolchains/BUILD | 2 ++ test/repo/BUILD.bazel | 2 ++ test/testdata/BUILD.bazel | 2 ++ test/toolchains/BUILD.bazel | 2 ++ toolchains/BUILD | 5 ++++- 29 files changed, 89 insertions(+), 8 deletions(-) diff --git a/BUILD b/BUILD index c138b7fa..2761f404 100644 --- a/BUILD +++ b/BUILD @@ -1,3 +1,7 @@ +load("@rules_license//rules:license.bzl", "license") + +package(default_applicable_licenses = ["@rules_java//:license"]) + licenses(["notice"]) exports_files([ @@ -18,3 +22,8 @@ filegroup( ], visibility = ["//visibility:public"], ) + +license( + name = "license", + package_name = "rules_java", +) diff --git a/distro/BUILD.bazel b/distro/BUILD.bazel index d8722d4f..0aca7dc3 100644 --- a/distro/BUILD.bazel +++ b/distro/BUILD.bazel @@ -1,7 +1,10 @@ load("@rules_pkg//pkg:tar.bzl", "pkg_tar") load(":relnotes.bzl", "print_rel_notes") -package(default_visibility = ["//visibility:private"]) +package( + default_applicable_licenses = ["@rules_java//:license"], + default_visibility = ["//visibility:private"], +) # Build the artifact to put on the github release page. pkg_tar( diff --git a/examples/hello_world/BUILD b/examples/hello_world/BUILD index 282e2d7e..2e951cc2 100644 --- a/examples/hello_world/BUILD +++ b/examples/hello_world/BUILD @@ -1,5 +1,7 @@ load("//java:defs.bzl", "java_binary") +package(default_applicable_licenses = ["@rules_java//:license"]) + java_binary( name = "hello_world", srcs = ["com/google/HelloWorld.java"], diff --git a/java/BUILD b/java/BUILD index a4363273..31621486 100644 --- a/java/BUILD +++ b/java/BUILD @@ -1,6 +1,9 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") -package(default_visibility = ["//visibility:public"]) +package( + default_applicable_licenses = ["@rules_java//:license"], + default_visibility = ["//visibility:public"], +) licenses(["notice"]) diff --git a/java/bazel/BUILD.bazel b/java/bazel/BUILD.bazel index bc61f061..68b3c1f1 100644 --- a/java/bazel/BUILD.bazel +++ b/java/bazel/BUILD.bazel @@ -15,6 +15,8 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") load(":repositories_util.bzl", "FLAT_CONFIGS") +package(default_applicable_licenses = ["@rules_java//:license"]) + # build this to generate _REMOTE_JDK_CONFIGS_LIST in repositories.bzl # this downloads all the jdks and computes their sha256 sum, so can take a while # TODO(hvd): make this a sh_binary to update the configs in place diff --git a/java/bazel/common/BUILD.bazel b/java/bazel/common/BUILD.bazel index dd3bc064..e5654e71 100644 --- a/java/bazel/common/BUILD.bazel +++ b/java/bazel/common/BUILD.bazel @@ -1,5 +1,7 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") +package(default_applicable_licenses = ["@rules_java//:license"]) + bzl_library( name = "common", srcs = glob(["*.bzl"]), diff --git a/java/bazel/rules/BUILD.bazel b/java/bazel/rules/BUILD.bazel index 00fa30ba..e0d79586 100644 --- a/java/bazel/rules/BUILD.bazel +++ b/java/bazel/rules/BUILD.bazel @@ -13,6 +13,8 @@ # limitations under the License. load("@bazel_skylib//:bzl_library.bzl", "bzl_library") +package(default_applicable_licenses = ["@rules_java//:license"]) + filegroup( name = "srcs", srcs = glob(["**"]), diff --git a/java/common/BUILD b/java/common/BUILD index a06a2f37..9958a883 100644 --- a/java/common/BUILD +++ b/java/common/BUILD @@ -1,6 +1,9 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") -package(default_visibility = ["//visibility:public"]) +package( + default_applicable_licenses = ["@rules_java//:license"], + default_visibility = ["//visibility:public"], +) licenses(["notice"]) diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD index 9d0678cd..12006384 100644 --- a/java/common/rules/BUILD +++ b/java/common/rules/BUILD @@ -1,6 +1,9 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") -package(default_visibility = ["//visibility:public"]) +package( + default_applicable_licenses = ["@rules_java//:license"], + default_visibility = ["//visibility:public"], +) filegroup( name = "srcs", diff --git a/java/common/rules/impl/BUILD b/java/common/rules/impl/BUILD index f50862c4..65c5af86 100644 --- a/java/common/rules/impl/BUILD +++ b/java/common/rules/impl/BUILD @@ -1,6 +1,9 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") -package(default_visibility = ["//visibility:public"]) +package( + default_applicable_licenses = ["@rules_java//:license"], + default_visibility = ["//visibility:public"], +) filegroup( name = "srcs", diff --git a/java/docs/BUILD.bazel b/java/docs/BUILD.bazel index 599e4e0c..f2b59360 100644 --- a/java/docs/BUILD.bazel +++ b/java/docs/BUILD.bazel @@ -1,6 +1,8 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") load("@stardoc//stardoc:stardoc.bzl", "stardoc") +package(default_applicable_licenses = ["@rules_java//:license"]) + exports_files( ["rules.md"], visibility = ["//test:__pkg__"], diff --git a/java/private/BUILD b/java/private/BUILD index 27be00de..939fa753 100644 --- a/java/private/BUILD +++ b/java/private/BUILD @@ -1,5 +1,7 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") +package(default_applicable_licenses = ["@rules_java//:license"]) + licenses(["notice"]) bzl_library( diff --git a/java/proto/BUILD b/java/proto/BUILD index 209a5f52..fa4ecf19 100644 --- a/java/proto/BUILD +++ b/java/proto/BUILD @@ -1,4 +1,7 @@ -package(default_visibility = ["//visibility:public"]) +package( + default_applicable_licenses = ["@rules_java//:license"], + default_visibility = ["//visibility:public"], +) # Toolchain type provided by proto_lang_toolchain rule and used by java_proto_library toolchain_type(name = "toolchain_type") diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl index a3a59aa9..0c96d8ca 100644 --- a/java/rules_java_deps.bzl +++ b/java/rules_java_deps.bzl @@ -199,6 +199,17 @@ def absl_repo(): urls = ["https://github.com/abseil/abseil-cpp/archive/refs/tags/20240722.0.tar.gz"], ) +def rules_license_repo(): + maybe( + http_archive, + name = "rules_license", + sha256 = "26d4021f6898e23b82ef953078389dd49ac2b5618ac564ade4ef87cced147b38", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/rules_license/releases/download/1.0.0/rules_license-1.0.0.tar.gz", + "https://github.com/bazelbuild/rules_license/releases/download/1.0.0/rules_license-1.0.0.tar.gz", + ], + ) + def rules_java_dependencies(): """An utility method to load non-toolchain dependencies of rules_java. @@ -211,3 +222,4 @@ def rules_java_dependencies(): platforms_repo() zlib_repo() absl_repo() + rules_license_repo() diff --git a/java/runfiles/BUILD b/java/runfiles/BUILD index 05a8104b..ef6b4d03 100644 --- a/java/runfiles/BUILD +++ b/java/runfiles/BUILD @@ -1,3 +1,5 @@ +package(default_applicable_licenses = ["@rules_java//:license"]) + alias( name = "runfiles", actual = "//java/runfiles/src/main/java/com/google/devtools/build/runfiles", diff --git a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD index ee1bd83a..5b521a9b 100644 --- a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD +++ b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD @@ -1,5 +1,7 @@ load("//java:defs.bzl", "java_library", "java_plugin") +package(default_applicable_licenses = ["@rules_java//:license"]) + java_library( name = "runfiles", srcs = [ diff --git a/java/toolchains/BUILD b/java/toolchains/BUILD index 29a572a0..2cb68270 100644 --- a/java/toolchains/BUILD +++ b/java/toolchains/BUILD @@ -1,6 +1,9 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") -package(default_visibility = ["//visibility:public"]) +package( + default_applicable_licenses = ["@rules_java//:license"], + default_visibility = ["//visibility:public"], +) licenses(["notice"]) diff --git a/test/BUILD.bazel b/test/BUILD.bazel index 70e62b53..084ff40c 100644 --- a/test/BUILD.bazel +++ b/test/BUILD.bazel @@ -17,6 +17,8 @@ load("@rules_shell//shell:sh_test.bzl", "sh_test") load("//java:repositories.bzl", "JAVA_TOOLS_CONFIG", "REMOTE_JDK_CONFIGS") load(":check_remotejdk_configs_match.bzl", "validate_configs") +package(default_applicable_licenses = ["@rules_java//:license"]) + sh_test( name = "check_remote_jdk_configs_test", srcs = ["check_remote_jdk_configs.sh"], diff --git a/test/java/BUILD b/test/java/BUILD index e69de29b..c2afbb31 100644 --- a/test/java/BUILD +++ b/test/java/BUILD @@ -0,0 +1 @@ +package(default_applicable_licenses = ["@rules_java//:license"]) diff --git a/test/java/common/BUILD b/test/java/common/BUILD index 5305a01e..590b11a1 100644 --- a/test/java/common/BUILD +++ b/test/java/common/BUILD @@ -2,6 +2,8 @@ load(":java_common_tests.bzl", "java_common_tests") load(":java_info_tests.bzl", "java_info_tests") load(":java_plugin_info_tests.bzl", "java_plugin_info_tests") +package(default_applicable_licenses = ["@rules_java//:license"]) + java_common_tests(name = "java_common_tests") java_info_tests(name = "java_info_tests") diff --git a/test/java/common/rules/BUILD b/test/java/common/rules/BUILD index 8ba67604..2311a3f2 100644 --- a/test/java/common/rules/BUILD +++ b/test/java/common/rules/BUILD @@ -5,6 +5,8 @@ load(":java_plugin_tests.bzl", "java_plugin_tests") load(":java_test_tests.bzl", "java_test_tests") load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") +package(default_applicable_licenses = ["@rules_java//:license"]) + merge_attrs_test_suite(name = "merge_attrs_tests") java_binary_tests(name = "java_binary_tests") diff --git a/test/java/private/BUILD b/test/java/private/BUILD index 0123c92f..dd2d2ad0 100644 --- a/test/java/private/BUILD +++ b/test/java/private/BUILD @@ -13,4 +13,6 @@ # limitations under the License. load(":android_support_tests.bzl", "android_support_tests") +package(default_applicable_licenses = ["@rules_java//:license"]) + android_support_tests(name = "android_support_tests") diff --git a/test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel b/test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel index 67a11ca5..79790df0 100644 --- a/test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel +++ b/test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel @@ -1,6 +1,8 @@ load("@rules_java//java:java_import.bzl", "java_import") load("@rules_java//java:java_test.bzl", "java_test") +package(default_applicable_licenses = ["@rules_java//:license"]) + java_test( name = "RunfilesTest", srcs = ["RunfilesTest.java"], diff --git a/test/java/testutil/BUILD b/test/java/testutil/BUILD index e69de29b..c2afbb31 100644 --- a/test/java/testutil/BUILD +++ b/test/java/testutil/BUILD @@ -0,0 +1 @@ +package(default_applicable_licenses = ["@rules_java//:license"]) diff --git a/test/java/toolchains/BUILD b/test/java/toolchains/BUILD index 440cb341..4ebe1f2d 100644 --- a/test/java/toolchains/BUILD +++ b/test/java/toolchains/BUILD @@ -1,6 +1,8 @@ load(":java_runtime_tests.bzl", "java_runtime_tests") load(":java_toolchain_tests.bzl", "java_toolchain_tests") +package(default_applicable_licenses = ["@rules_java//:license"]) + java_runtime_tests(name = "java_runtime_tests") java_toolchain_tests(name = "java_toolchain_tests") diff --git a/test/repo/BUILD.bazel b/test/repo/BUILD.bazel index 99f63087..ca414395 100644 --- a/test/repo/BUILD.bazel +++ b/test/repo/BUILD.bazel @@ -2,6 +2,8 @@ load("@rules_java//java:defs.bzl", "java_binary", "java_library", "java_test") load("@rules_java//toolchains:default_java_toolchain.bzl", "NONPREBUILT_TOOLCHAIN_CONFIGURATION", "default_java_toolchain") # copybara-use-repo-external-label load("@rules_shell//shell:sh_test.bzl", "sh_test") +package(default_applicable_licenses = ["@rules_java//:license"]) + java_library( name = "lib", srcs = ["src/Main.java"], diff --git a/test/testdata/BUILD.bazel b/test/testdata/BUILD.bazel index ffcc5c35..7a0c7589 100644 --- a/test/testdata/BUILD.bazel +++ b/test/testdata/BUILD.bazel @@ -1,5 +1,7 @@ load("//java:java_library.bzl", "java_library") +package(default_applicable_licenses = ["@rules_java//:license"]) + # Make a sample jar for the http_jar test. java_library( name = "my_jar", diff --git a/test/toolchains/BUILD.bazel b/test/toolchains/BUILD.bazel index 754e1dd4..e25b3d8c 100644 --- a/test/toolchains/BUILD.bazel +++ b/test/toolchains/BUILD.bazel @@ -1,5 +1,7 @@ load(":bootclasspath_tests.bzl", "bootclasspath_tests") +package(default_applicable_licenses = ["@rules_java//:license"]) + bootclasspath_tests( name = "bootclasspath_tests", ) diff --git a/toolchains/BUILD b/toolchains/BUILD index 99c4456c..9a1b2d33 100644 --- a/toolchains/BUILD +++ b/toolchains/BUILD @@ -22,7 +22,10 @@ load( ) load(":utf8_environment.bzl", "utf8_environment") -package(default_visibility = ["//visibility:public"]) +package( + default_applicable_licenses = ["@rules_java//:license"], + default_visibility = ["//visibility:public"], +) licenses(["notice"]) From 5017641204f4a9b7310fdd46d074a17a05b16959 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 9 Apr 2025 09:33:31 -0700 Subject: [PATCH 238/465] Run `@rules_java` presubmits on `macos_arm64` as well (ignore-relnotes) PiperOrigin-RevId: 745621788 Change-Id: Ia1e14d9823996ff369e6e42836868c080613f426 --- .bazelci/presubmit.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 2385fa8b..1ec039f2 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -46,8 +46,8 @@ flags_workspace_integration: &flags_workspace_integration buildifier: latest matrix: - all_platforms: ["ubuntu2004", "macos", "windows"] - integration_platforms: ["ubuntu2004", "macos"] # TODO: add windows batch setup script + all_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"] + integration_platforms: ["ubuntu2004", "macos", "macos_arm64"] # TODO: add windows batch setup script bazel: ["7.4.0", "8.1.0", "last_green"] # Bazel 6 tested separately, needs different flags modern_bazel: ["8.1.0", "last_green"] # Fully supported Bazel versions From 043d9760314a57f828d7e6b20898114420adea92 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 11 Apr 2025 08:43:34 -0700 Subject: [PATCH 239/465] Enable `@rules_java` integration tests on windows PiperOrigin-RevId: 746475348 Change-Id: I675d9415ef16e3d2b67cb7cc3ab4d0c0133bb916 --- .bazelci/presubmit.yml | 10 ++++++++-- test/repo/MODULE.bazel | 10 ++++++++-- test/repo/WORKSPACE | 5 ++++- test/repo/setup.bat | 4 ++++ 4 files changed, 24 insertions(+), 5 deletions(-) create mode 100755 test/repo/setup.bat diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 1ec039f2..a42c2810 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -47,7 +47,7 @@ buildifier: latest matrix: all_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"] - integration_platforms: ["ubuntu2004", "macos", "macos_arm64"] # TODO: add windows batch setup script + integration_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"] bazel: ["7.4.0", "8.1.0", "last_green"] # Bazel 6 tested separately, needs different flags modern_bazel: ["8.1.0", "last_green"] # Fully supported Bazel versions @@ -80,10 +80,12 @@ tasks: ubuntu2004_integration_bazel6: name: "Integration w/ Bazel 6.5.0" bazel: 6.5.0 - platform: ubuntu2004 + platform: ${{ integration_platforms }} working_directory: "test/repo" shell_commands: - sh setup.sh + batch_commands: + - setup.bat build_targets: *build_targets_integration test_targets: *test_target_integration @@ -95,6 +97,8 @@ tasks: working_directory: "test/repo" shell_commands: - sh setup.sh + batch_commands: + - setup.bat build_targets: *build_targets_integration test_targets: *test_target_integration integration_build_and_test_workspace: @@ -104,6 +108,8 @@ tasks: working_directory: "test/repo" shell_commands: - sh setup.sh + batch_commands: + - setup.bat build_targets: *build_targets_integration build_flags: *flags_workspace_integration test_targets: *test_target_integration diff --git a/test/repo/MODULE.bazel b/test/repo/MODULE.bazel index 85f99283..1faec90d 100644 --- a/test/repo/MODULE.bazel +++ b/test/repo/MODULE.bazel @@ -3,14 +3,20 @@ module(name = "integration_test_repo") bazel_dep(name = "rules_java", version = "7.5.0") archive_override( module_name = "rules_java", - urls = ["file:///tmp/rules_java-HEAD.tar.gz"], + urls = [ + "file:///tmp/rules_java-HEAD.tar.gz", + "file:///C:/b/rules_java-HEAD.tar.gz", + ], ) http_jar = use_repo_rule("@rules_java//java:http_jar.bzl", "http_jar") http_jar( name = "my_jar", - urls = ["file:///tmp/my_jar.jar"], + urls = [ + "file:///tmp/my_jar.jar", + "file:///C:/b/my_jar.jar", + ], ) java_toolchains = use_extension("@rules_java//java:extensions.bzl", "toolchains") diff --git a/test/repo/WORKSPACE b/test/repo/WORKSPACE index 08589c20..eb680856 100644 --- a/test/repo/WORKSPACE +++ b/test/repo/WORKSPACE @@ -23,7 +23,10 @@ load("@rules_java//java:http_jar.bzl", "http_jar") http_jar( name = "my_jar", - urls = ["file:///tmp/my_jar.jar"], + urls = [ + "file:///tmp/my_jar.jar", + "file:///C:/b/my_jar.jar", + ], ) load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") diff --git a/test/repo/setup.bat b/test/repo/setup.bat new file mode 100755 index 00000000..634892fa --- /dev/null +++ b/test/repo/setup.bat @@ -0,0 +1,4 @@ +cd ../../ +bazel build //distro:all //test/testdata:my_jar +cp -f ./bazel-bin/distro/*.tar.gz C:/b/rules_java-HEAD.tar.gz +cp -f bazel-bin/test/testdata/libmy_jar.jar C:/b/my_jar.jar From bd9c5f8678ad149db90ee349a6a4c3dafb9212b4 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 25 Apr 2025 08:55:38 -0700 Subject: [PATCH 240/465] Change type of `output_licenses` from `attr.license` to `attr.string_list`. BEGIN_PUBLIC internal change END PUBLIC PiperOrigin-RevId: 751437233 Change-Id: I6b76f1005aab506dc4bdeb8993776525bdfd6812 --- java/common/rules/java_package_configuration.bzl | 2 +- java/common/rules/java_plugin.bzl | 2 +- java/common/rules/java_runtime.bzl | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/java/common/rules/java_package_configuration.bzl b/java/common/rules/java_package_configuration.bzl index 0752e411..2c24b450 100644 --- a/java/common/rules/java_package_configuration.bzl +++ b/java/common/rules/java_package_configuration.bzl @@ -119,6 +119,6 @@ Corresponds to javac's --system flag. """, ), # buildifier: disable=attr-licenses - "output_licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), + "output_licenses": attr.string_list(), }, ) diff --git a/java/common/rules/java_plugin.bzl b/java/common/rules/java_plugin.bzl index 5b2cc936..569c77ff 100644 --- a/java/common/rules/java_plugin.bzl +++ b/java/common/rules/java_plugin.bzl @@ -46,7 +46,7 @@ from the annotation processor path using java.util.ServiceLoader.) """), # buildifier: disable=attr-licenses - "output_licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), + "output_licenses": attr.string_list(), }, remove_attrs = ["runtime_deps", "exports", "exported_plugins"], ) diff --git a/java/common/rules/java_runtime.bzl b/java/common/rules/java_runtime.bzl index 85acb22d..42321173 100644 --- a/java/common/rules/java_runtime.bzl +++ b/java/common/rules/java_runtime.bzl @@ -247,7 +247,7 @@ The feature version of the Java runtime. I.e., the integer returned by """, ), # buildifier: disable=attr-licenses - "output_licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), + "output_licenses": attr.string_list(), "_windows_constraints": attr.label_list( default = [paths.join(semantics.PLATFORMS_ROOT, "os:windows")], ), From da9eee279c1f95822ad4bd3d624cceb3910f986b Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Mon, 28 Apr 2025 04:52:09 -0700 Subject: [PATCH 241/465] Fix classpath separator when cross-compiling from Windows to Unix (#290) Closes #290 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/290 from fmeum:fix-host-dependence 0805387458cbe54619a0b1916561f72668972387 PiperOrigin-RevId: 752259438 Change-Id: I5e1134f3ce648cdeb65fa6c739a35debca344f26 --- java/bazel/rules/bazel_java_binary.bzl | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl index 75bc6eab..def12d14 100644 --- a/java/bazel/rules/bazel_java_binary.bzl +++ b/java/bazel/rules/bazel_java_binary.bzl @@ -236,7 +236,9 @@ def _create_stub(ctx, java_attrs, launcher, executable, jvm_flags, main_class, c "%classpath%", classpath, map_each = lambda file: _format_classpath_entry(runfiles_enabled, workspace_prefix, file), - join_with = ctx.configuration.host_path_separator, + # At the moment, this condition is always false since the dedicated + # Windows launcher is used above when targeting Windows. + join_with = ";" if helper.is_target_platform_windows(ctx) else ":", format_joined = "\"%s\"", allow_closure = True, ) From bf2fb4317a4d0f4e59759fc83e8208ab71e3c3e3 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 30 Apr 2025 04:25:30 -0700 Subject: [PATCH 242/465] Fix comment PiperOrigin-RevId: 753111760 Change-Id: Ifd05132db6c8bc29bb7432d749ccabe99baf28dc --- java/common/proguard_spec_info.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/common/proguard_spec_info.bzl b/java/common/proguard_spec_info.bzl index b2a591a2..bf006e80 100644 --- a/java/common/proguard_spec_info.bzl +++ b/java/common/proguard_spec_info.bzl @@ -14,7 +14,7 @@ """ProguardSpecInfo provider""" def _proguard_spec_info_init(specs): - # The constructor supports positional parameter, i.e ProguardSpecInfo([file]) + # The constructor supports positional parameter, i.e. ProguardSpecInfo([file]) return {"specs": specs} ProguardSpecInfo, _ = provider( From 277957425bf7a7116da87709b4dc7df4441b377c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89amonn=20McManus?= Date: Wed, 30 Apr 2025 09:14:04 -0700 Subject: [PATCH 243/465] The `test_class` of a `java_test` for JUnit4 does not have to have `@RunWith`. PiperOrigin-RevId: 753193925 Change-Id: I90d2717b45049870dee32f76a53d1d3ede8fe701 --- java/common/rules/java_binary.bzl | 2 -- 1 file changed, 2 deletions(-) diff --git a/java/common/rules/java_binary.bzl b/java/common/rules/java_binary.bzl index 09b6b121..c49d7d57 100644 --- a/java/common/rules/java_binary.bzl +++ b/java/common/rules/java_binary.bzl @@ -348,8 +348,6 @@ The Java class to be loaded by the test runner.
junit.framework.TestCase or it needs to have a public static suite() method that returns a junit.framework.Test (or a subclass of Test). - For JUnit4, the class needs to be annotated with - org.junit.runner.RunWith.

This attribute allows several java_test rules to From ad510edc8012877fd0fd7325093855c0401c9738 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 5 May 2025 05:04:41 -0700 Subject: [PATCH 244/465] Remove usages of `--incompatible_disable_non_executable_java_binary` With the java rules no longer in Bazel, this behaviour no longer needs to be a native flag. In the future, we can simply flip the value (although the lack of a flag means unmigrated users may have to patch `@rules_java` to change the value). PiperOrigin-RevId: 754890658 Change-Id: Ifcc43f981eeb7c461379b8fb78b631b91a4545ab --- java/bazel/rules/bazel_java_binary_wrapper.bzl | 4 ++-- java/common/java_semantics.bzl | 1 + java/common/rules/java_binary.bzl | 3 +-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/java/bazel/rules/bazel_java_binary_wrapper.bzl b/java/bazel/rules/bazel_java_binary_wrapper.bzl index 517dcd62..c44f1511 100644 --- a/java/bazel/rules/bazel_java_binary_wrapper.bzl +++ b/java/bazel/rules/bazel_java_binary_wrapper.bzl @@ -18,19 +18,19 @@ This is needed since the `executable` nature of the target must be computed from the supplied value of the `create_executable` attribute. """ +load("//java/common:java_semantics.bzl", "semantics") load( "//java/common/rules:java_binary_wrapper.bzl", "register_java_binary_rules", "register_legacy_java_binary_rules", ) -load("//java/private:native.bzl", "get_internal_java_common") load(":bazel_java_binary.bzl", java_bin_exec = "java_binary") load(":bazel_java_binary_nonexec.bzl", java_bin_nonexec = "java_binary") # copybara: default visibility def java_binary(**kwargs): - if get_internal_java_common().incompatible_disable_non_executable_java_binary(): + if semantics.INCOMPATIBLE_DISABLE_NON_EXECUTABLE_JAVA_BINARY: register_java_binary_rules( java_bin_exec, **kwargs diff --git a/java/common/java_semantics.bzl b/java/common/java_semantics.bzl index 88d0bcc8..700c0d1d 100644 --- a/java/common/java_semantics.bzl +++ b/java/common/java_semantics.bzl @@ -112,4 +112,5 @@ semantics = struct( minimize_cc_info = _minimize_cc_info, tokenize_javacopts = _tokenize_javacopts, PLATFORMS_ROOT = "@platforms//", + INCOMPATIBLE_DISABLE_NON_EXECUTABLE_JAVA_BINARY = False, # Flip when java_single_jar is feature complete ) diff --git a/java/common/rules/java_binary.bzl b/java/common/rules/java_binary.bzl index c49d7d57..cdd79f29 100644 --- a/java/common/rules/java_binary.bzl +++ b/java/common/rules/java_binary.bzl @@ -19,7 +19,6 @@ load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_semantics.bzl", "semantics") load("//java/private:java_common.bzl", "java_common") load("//java/private:java_info.bzl", "JavaInfo", "JavaPluginInfo") -load("//java/private:native.bzl", "get_internal_java_common") load(":basic_java_library.bzl", "BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS") load(":rule_util.bzl", "merge_attrs") @@ -323,7 +322,7 @@ binaries and not libraries, due to the danger of namespace conflicts. default = [paths.join(_PLATFORMS_ROOT, "os:windows")], ), "_build_info_translator": attr.label(default = semantics.BUILD_INFO_TRANSLATOR_LABEL), - } | ({} if get_internal_java_common().incompatible_disable_non_executable_java_binary() else {"create_executable": attr.bool(default = True, doc = "Deprecated, use java_single_jar instead.")}), + } | ({} if semantics.INCOMPATIBLE_DISABLE_NON_EXECUTABLE_JAVA_BINARY else {"create_executable": attr.bool(default = True, doc = "Deprecated, use java_single_jar instead.")}), ) BASE_TEST_ATTRIBUTES = { From 4b5e2a936889ca423530a14afee68046918ad4b0 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 5 May 2025 05:08:43 -0700 Subject: [PATCH 245/465] Fix empty jars check for Bazel java_import The check was initially added in https://github.com/bazelbuild/bazel/commit/1acda6be4ffc197f0a19a54556a4a3f8eb4b4906 [^1], but inadvertently made a no-op in https://github.com/bazelbuild/bazel/commit/67d3bca6b63db3c4d37c5204aef3cf49e84606ea [^2] which made it so that it would only take effect only if the rule class defined an allowlist (which the Bazel version never did). PiperOrigin-RevId: 754891782 Change-Id: I692dc94865a5aa04f9b5189efc1cbe86e636bfa2 --- java/common/rules/impl/bazel_java_import_impl.bzl | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/java/common/rules/impl/bazel_java_import_impl.bzl b/java/common/rules/impl/bazel_java_import_impl.bzl index 4df2ab84..f018fe7a 100644 --- a/java/common/rules/impl/bazel_java_import_impl.bzl +++ b/java/common/rules/impl/bazel_java_import_impl.bzl @@ -72,11 +72,13 @@ def _check_export_error(ctx, exports): def _check_empty_jars_error(ctx, jars): # TODO(kotlaja): Remove temporary incompatible flag [disallow_java_import_empty_jars] once migration is done. - not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_empty_jars") and not getattr(ctx.attr, "_allowlist_java_import_empty_jars")[PackageSpecificationInfo].contains(ctx.label) - disallow_java_import_empty_jars = ctx.fragments.java.disallow_java_import_empty_jars() - - if len(jars) == 0 and disallow_java_import_empty_jars and not_in_allowlist: - fail("empty java_import.jars is no longer supported " + ctx.label.package) + if len(jars) > 0: + return # jars is non empty + if not ctx.fragments.java.disallow_java_import_empty_jars(): + return # check disabled by flag + if hasattr(ctx.attr, "_allowlist_java_import_empty_jars") and getattr(ctx.attr, "_allowlist_java_import_empty_jars")[PackageSpecificationInfo].contains(ctx.label): + return # allowlisted + fail("empty java_import.jars is no longer supported " + ctx.label.package) def _create_java_info_with_dummy_output_file(ctx, srcjar, all_deps, exports, runtime_deps_list, neverlink, cc_info_list, add_exports, add_opens): dummy_jar = ctx.actions.declare_file(ctx.label.name + "_dummy.jar") From 9fac3acdcb688d3e59ce99093749d51cacad08f4 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Tue, 6 May 2025 02:55:39 -0700 Subject: [PATCH 246/465] Configure coverage helpers for the test exec group (#292) These tools run on the test action's execution platform and should thus be configured for it. Closes #292 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/292 from fmeum:fix-coverage-exec-group d341fc0b941478f26f78fff64ace22ce2726ce88 PiperOrigin-RevId: 755287580 Change-Id: I88548701af955d6ffe410852f60d8b6337f44d81 --- java/bazel/rules/bazel_java_test.bzl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java/bazel/rules/bazel_java_test.bzl b/java/bazel/rules/bazel_java_test.bzl index 7dec8496..fd3e2bd2 100644 --- a/java/bazel/rules/bazel_java_test.bzl +++ b/java/bazel/rules/bazel_java_test.bzl @@ -86,14 +86,14 @@ java_test( BASE_BINARY_ATTRS, { "_lcov_merger": attr.label( - cfg = "exec", + cfg = config.exec(exec_group = "test"), default = configuration_field( fragment = "coverage", name = "output_generator", ), ), "_collect_cc_coverage": attr.label( - cfg = "exec", + cfg = config.exec(exec_group = "test"), allow_single_file = True, default = "@bazel_tools//tools/test:collect_cc_coverage", ), From 86962f9c8ed73de61154e257626771c8e5df5451 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 6 May 2025 09:09:32 -0700 Subject: [PATCH 247/465] Change deprecation message to be more helpful for java_proto_library/java_lite_proto_library PiperOrigin-RevId: 755396353 Change-Id: Ib6340971acccc077d39323be95ca031d50753a9d --- java/defs.bzl | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/java/defs.bzl b/java/defs.bzl index da1d6af8..8899a705 100644 --- a/java/defs.bzl +++ b/java/defs.bzl @@ -45,13 +45,19 @@ java_package_configuration = _java_package_configuration # Deprecated: don't use java proto libraries from here def java_proto_library(**kwargs): if "deprecation" not in kwargs: - _java_proto_library(deprecation = "Use java_proto_library from com_google_protobuf", **kwargs) + _java_proto_library( + deprecation = "Use java_proto_library from @com_google_protobuf//bazel:java_proto_library.bzl", + **kwargs + ) else: _java_proto_library(**kwargs) def java_lite_proto_library(**kwargs): if "deprecation" not in kwargs: - _java_lite_proto_library(deprecation = "Use java_lite_proto_library from com_google_protobuf", **kwargs) + _java_lite_proto_library( + deprecation = "Use java_lite_proto_library from @com_google_protobuf//bazel:java_lite_proto_library.bzl", + **kwargs + ) else: _java_lite_proto_library(**kwargs) From 844d515edd19d5b51661658693cad0180ea3974f Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 7 May 2025 06:15:40 -0700 Subject: [PATCH 248/465] Migrate the `JavaStarlarkApiTest.testCompileExports` test to Starlark The test is removed from Bazel and added to rules_java. (ignore-relnotes) PiperOrigin-RevId: 755823264 Change-Id: Ie058f8810f5d74f72ff3c6268cebe8ccb7382f8f --- test/java/common/java_common_tests.bzl | 40 +++++++++++++++++++ test/java/testutil/java_info_subject.bzl | 1 + .../rules/custom_library_with_exports.bzl | 8 +++- 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/test/java/common/java_common_tests.bzl b/test/java/common/java_common_tests.bzl index 26afce51..b569b680 100644 --- a/test/java/common/java_common_tests.bzl +++ b/test/java/common/java_common_tests.bzl @@ -71,6 +71,45 @@ def _test_compile_exports_no_sources_impl(env, target): ["{package}/libjl.jar"], ) +def _test_compile_exports_with_sources(name): + target_name = name + "/custom" + util.helper_target( + custom_library_with_exports, + name = target_name, + srcs = ["Main.java"], + exports = [target_name + "/dep"], + output_name = "amazing", + ) + util.helper_target( + java_library, + name = target_name + "/dep", + srcs = ["Dep.java"], + ) + + analysis_test( + name = name, + impl = _test_compile_exports_with_sources_impl, + target = target_name, + # Bazel 6 JavaInfo doesn't expose compile_time_java_dependencies + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_compile_exports_with_sources_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/{name}/amazing-src.jar", + "{package}/lib{name}/dep-src.jar", + ]) + assert_java_info.compilation_args().compile_jars().contains_exactly([ + "{package}/{name}/amazing-hjar.jar", + "{package}/lib{name}/dep-hjar.jar", + ]) + assert_java_info.compilation_args().compile_time_java_dependencies().contains_exactly([ + "{package}/{name}/amazing-hjar.jdeps", + "{package}/lib{name}/dep-hjar.jdeps", + ]) + def _test_java_plugin_info(name): util.helper_target(native.filegroup, name = name + "/dummy") analysis_test( @@ -711,6 +750,7 @@ def java_common_tests(name): _test_compile_default_values, _test_compile_sourcepath, _test_compile_exports_no_sources, + _test_compile_exports_with_sources, _test_java_plugin_info, _test_compile_extend_compile_time_jdeps, _test_compile_extend_compile_time_jdeps_rule_outputs, diff --git a/test/java/testutil/java_info_subject.bzl b/test/java/testutil/java_info_subject.bzl index a49963a1..972dc47d 100644 --- a/test/java/testutil/java_info_subject.bzl +++ b/test/java/testutil/java_info_subject.bzl @@ -111,6 +111,7 @@ def _new_java_compilation_args_subject(java_info, meta): transitive_runtime_jars = lambda: subjects.depset_file(actual.transitive_runtime_jars, self.meta.derive("transitive_runtime_jars")), transitive_compile_time_jars = lambda: subjects.depset_file(actual.transitive_compile_time_jars, self.meta.derive("transitive_compile_time_jars")), transitive_runtime_jars_list = lambda: subjects.collection(actual.transitive_runtime_jars.to_list(), self.meta.derive("transitive_runtime_jars.to_list()")), + compile_time_java_dependencies = lambda: subjects.depset_file(actual._compile_time_java_dependencies, self.meta.derive("_compile_time_java_dependencies")), self = self, actual = actual, ) diff --git a/test/java/testutil/rules/custom_library_with_exports.bzl b/test/java/testutil/rules/custom_library_with_exports.bzl index 5ba6793c..0c180076 100644 --- a/test/java/testutil/rules/custom_library_with_exports.bzl +++ b/test/java/testutil/rules/custom_library_with_exports.bzl @@ -4,9 +4,13 @@ load("//java/common:java_common.bzl", "java_common") load("//java/common:java_semantics.bzl", "semantics") def _custom_library_with_exports_impl(ctx): - output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") + output_name = ( + ctx.label.name + "/" + ctx.attr.output_name + ".jar" + ) if ctx.attr.output_name else "lib" + ctx.label.name + ".jar" + output_jar = ctx.actions.declare_file(output_name) compilation_provider = java_common.compile( ctx, + source_files = ctx.files.srcs, exports = [export[java_common.provider] for export in ctx.attr.exports], output = output_jar, java_toolchain = semantics.find_java_toolchain(ctx), @@ -16,7 +20,9 @@ def _custom_library_with_exports_impl(ctx): custom_library_with_exports = rule( _custom_library_with_exports_impl, attrs = { + "srcs": attr.label_list(allow_files = [".java"]), "exports": attr.label_list(), + "output_name": attr.string(), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], fragments = ["java"], From 43f83a8e8baa873a1db1814c2e3c51799e48fb95 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 7 May 2025 06:30:55 -0700 Subject: [PATCH 249/465] Migrate the `JavaImportConfiguredTargetTest.testSimple` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 755827957 Change-Id: I64feaf5c30323bd1b70c2da76c92b08c28dd505f --- test/java/common/rules/java_import_tests.bzl | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 2b3038d3..f1011be4 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -53,10 +53,30 @@ def _test_java_import_attributes_impl(env, target): matching.file_basename_equals("jl_bottom_for_runtime_deps.jar"), ]) +def _test_simple(name): + target_name = name + "/libraryjar" + util.helper_target( + java_import, + name = target_name, + jars = ["library.jar"], + ) + + analysis_test( + name = name, + impl = _test_simple_impl, + target = target_name, + ) + +def _test_simple_impl(env, target): + env.expect.that_target(target).default_outputs().contains_exactly([ + "{package}/library.jar", + ]) + def java_import_tests(name): test_suite( name = name, tests = [ _test_java_import_attributes, + _test_simple, ], ) From 9b9cf06b94fb597a498133dac05f75ce912f9ab6 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 7 May 2025 06:54:46 -0700 Subject: [PATCH 250/465] Migrate the `JavaImportConfiguredTargetTest.testWithJavaLibrary` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 755834947 Change-Id: I973fefee2669d87b5ffee79ee3d5f37b05d07aef --- test/java/common/rules/java_import_tests.bzl | 32 ++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index f1011be4..a1064d2d 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -72,11 +72,43 @@ def _test_simple_impl(env, target): "{package}/library.jar", ]) +def _test_with_java_library(name): + target_name = name + "/javalib" + util.helper_target( + java_library, + name = target_name, + srcs = ["Other.java"], + deps = [target_name + "/libraryjar"], + ) + util.helper_target( + java_import, + name = target_name + "/libraryjar", + jars = ["library.jar"], + ) + + analysis_test( + name = name, + impl = _test_with_java_library_impl, + target = target_name, + ) + +def _test_with_java_library_impl(env, target): + assert_compliation_info = java_info_subject.from_target(env, target).compilation_info() + + assert_compliation_info.compilation_classpath().contains_exactly([ + "{package}/_ijar/{name}/libraryjar/{package}/library-ijar.jar", + ]) + assert_compliation_info.runtime_classpath().contains_exactly([ + "{package}/lib{name}.jar", + "{package}/library.jar", + ]) + def java_import_tests(name): test_suite( name = name, tests = [ _test_java_import_attributes, _test_simple, + _test_with_java_library, ], ) From 6e0e5f4cd524e364cebe078d83bc448de2293e91 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 7 May 2025 07:25:10 -0700 Subject: [PATCH 251/465] Migrate the `JavaImportConfiguredTargetTest.testDeps` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 755844034 Change-Id: I653e079863065895eb3b82f895af771e3f7fa9fe --- test/java/common/rules/java_import_tests.bzl | 69 ++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index a1064d2d..961ce576 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -103,6 +103,74 @@ def _test_with_java_library_impl(env, target): "{package}/library.jar", ]) +def _test_deps(name): + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["Main.java"], + deps = [name + "/import-jar"], + ) + util.helper_target( + java_import, + name = name + "/import-jar", + jars = ["import.jar"], + exports = [name + "/exportjar"], + deps = [name + "/depjar"], + ) + util.helper_target( + java_import, + name = name + "/depjar", + jars = ["depjar.jar"], + ) + util.helper_target( + java_import, + name = name + "/exportjar", + jars = ["exportjar.jar"], + ) + + analysis_test( + name = name, + impl = _test_deps_impl, + targets = { + "importjar": name + "/import-jar", + "lib": name + "/lib", + }, + ) + +def _test_deps_impl(env, targets): + env.expect.that_target(targets.importjar).default_outputs().contains_exactly([ + "{package}/import.jar", + ]) + + assert_import_compilation_args = java_info_subject.from_target(env, targets.importjar).compilation_args() + assert_import_compilation_args.transitive_compile_time_jars().contains_exactly([ + "{package}/_ijar/test_deps/import-jar/{package}/import-ijar.jar", + "{package}/_ijar/test_deps/exportjar/{package}/exportjar-ijar.jar", + "{package}/_ijar/test_deps/depjar/{package}/depjar-ijar.jar", + ]) + assert_import_compilation_args.transitive_runtime_jars().contains_exactly([ + "{package}/import.jar", + "{package}/exportjar.jar", + "{package}/depjar.jar", + ]) + assert_import_compilation_args.compile_jars().contains_exactly([ + "{package}/_ijar/test_deps/import-jar/{package}/import-ijar.jar", + "{package}/_ijar/test_deps/exportjar/{package}/exportjar-ijar.jar", + ]) + + assert_lib_compilation_info = java_info_subject.from_target(env, targets.lib).compilation_info() + assert_lib_compilation_info.compilation_classpath().contains_exactly([ + "{package}/_ijar/test_deps/import-jar/{package}/import-ijar.jar", + "{package}/_ijar/test_deps/exportjar/{package}/exportjar-ijar.jar", + "{package}/_ijar/test_deps/depjar/{package}/depjar-ijar.jar", + ]) + assert_lib_compilation_info.runtime_classpath().contains_exactly([ + "{package}/lib{name}.jar", + "{package}/import.jar", + "{package}/exportjar.jar", + "{package}/depjar.jar", + ]) + def java_import_tests(name): test_suite( name = name, @@ -110,5 +178,6 @@ def java_import_tests(name): _test_java_import_attributes, _test_simple, _test_with_java_library, + _test_deps, ], ) From 72cf8721c264c6d78d57c7ff46ca9cb60ea45579 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 7 May 2025 08:09:33 -0700 Subject: [PATCH 252/465] Migrate the `JavaImportConfiguredTargetTest.testCommandLineContainsTargetLabel` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 755858445 Change-Id: I1a4f0d9e6a9139e957dd7b9555ecae3d099aa80b --- test/java/common/rules/java_import_tests.bzl | 24 ++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 961ce576..f66c65c7 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -5,6 +5,7 @@ load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_import.bzl", "java_import") load("//java:java_library.bzl", "java_library") +load("//java/common:java_info.bzl", "JavaInfo") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") @@ -171,6 +172,28 @@ def _test_deps_impl(env, targets): "{package}/depjar.jar", ]) +# Regression test for b/262751943. +def _test_commandline_contains_target_label(name): + util.helper_target( + java_import, + name = name + "/java_imp", + jars = ["import.jar"], + ) + + analysis_test( + name = name, + impl = _test_commandline_contains_target_label_impl, + target = name + "/java_imp", + ) + +def _test_commandline_contains_target_label_impl(env, target): + compiled_artifact = target[JavaInfo].compile_jars.to_list()[0].short_path + assert_action = env.expect.that_target(target).action_generating(compiled_artifact) + + assert_action.contains_flag_values([ + ("--target_label", "//{package}:{name}"), + ]) + def java_import_tests(name): test_suite( name = name, @@ -179,5 +202,6 @@ def java_import_tests(name): _test_simple, _test_with_java_library, _test_deps, + _test_commandline_contains_target_label, ], ) From b0b41dba5aa373e0e3b07c7db7c3fdee6b93f6f5 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 7 May 2025 08:26:47 -0700 Subject: [PATCH 253/465] Migrate the `JavaImportConfiguredTargetTest.testJavaLibraryAllowsImportInDeps` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 755864538 Change-Id: I5c774240c6d4e54381a80b34825ecf823178582d --- test/java/common/rules/java_import_tests.bzl | 24 ++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index f66c65c7..46b39830 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -194,6 +194,29 @@ def _test_commandline_contains_target_label_impl(env, target): ("--target_label", "//{package}:{name}"), ]) +# Regression test for b/5868388. +def _test_java_library_allows_import_in_deps(name): + util.helper_target( + java_import, + name = name + "/libraryjar", + jars = ["library.jar"], + ) + util.helper_target( + java_library, + name = name + "/javalib", + srcs = ["Other.java"], + exports = [name + "/libraryjar"], + ) + + analysis_test( + name = name, + impl = _test_java_library_allows_import_in_deps_impl, + target = name + "/javalib", + ) + +def _test_java_library_allows_import_in_deps_impl(_env, _target): + pass # no errors + def java_import_tests(name): test_suite( name = name, @@ -203,5 +226,6 @@ def java_import_tests(name): _test_with_java_library, _test_deps, _test_commandline_contains_target_label, + _test_java_library_allows_import_in_deps, ], ) From 7673adcfd34c28e5b8ad1475a74f4797295bfec6 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 02:05:19 -0700 Subject: [PATCH 254/465] Migrate the `JavaImportConfiguredTargetTest.testModuleFlags` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756213013 Change-Id: Iaa80599a95b5fab90c107cc68f14b787fa55f3bc --- MODULE.bazel | 2 +- WORKSPACE | 11 ++++ test/java/common/rules/java_import_tests.bzl | 53 ++++++++++++++++++++ test/java/testutil/helper.bzl | 20 ++++++++ test/java/testutil/java_info_subject.bzl | 12 +++++ 5 files changed, 97 insertions(+), 1 deletion(-) create mode 100644 test/java/testutil/helper.bzl diff --git a/MODULE.bazel b/MODULE.bazel index c8994eee..400a4c2f 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -7,7 +7,7 @@ module( bazel_dep(name = "platforms", version = "0.0.11") bazel_dep(name = "rules_cc", version = "0.0.15") -bazel_dep(name = "bazel_features", version = "1.11.0") +bazel_dep(name = "bazel_features", version = "1.28.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") bazel_dep(name = "protobuf", version = "27.0", repo_name = "com_google_protobuf") bazel_dep(name = "zlib", version = "1.3.1.bcr.5") diff --git a/WORKSPACE b/WORKSPACE index cf3fa50c..3cb23798 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -63,3 +63,14 @@ http_archive( load("//test:repositories.bzl", "test_repositories") test_repositories() + +http_archive( + name = "bazel_features", + sha256 = "2f057dd02098a106095ea291b4344257398a059eadb2c74cc470de0f9664dccd", + strip_prefix = "bazel_features-1.28.0", + url = "https://github.com/bazel-contrib/bazel_features/releases/download/v1.28.0/bazel_features-v1.28.0.tar.gz", +) + +load("@bazel_features//:deps.bzl", "bazel_features_deps") + +bazel_features_deps() diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 46b39830..fbf21518 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -1,11 +1,13 @@ """Tests for the java_import rule""" +load("@bazel_features//:features.bzl", "bazel_features") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_import.bzl", "java_import") load("//java:java_library.bzl", "java_library") load("//java/common:java_info.bzl", "JavaInfo") +load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") @@ -217,6 +219,56 @@ def _test_java_library_allows_import_in_deps(name): def _test_java_library_allows_import_in_deps_impl(_env, _target): pass # no errors +def _test_module_flags(name): + if not bazel_features.java.java_info_constructor_module_flags: + # exit early because this test case would be a loading phase error otherwise + always_passes(name) + return + + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["Main.java"], + deps = [name + "/import-jar"], + ) + util.helper_target( + java_import, + name = name + "/import-jar", + jars = ["import.jar"], + exports = [name + "/exportjar"], + deps = [name + "/depjar"], + ) + util.helper_target( + java_import, + name = name + "/depjar", + add_exports = ["java.base/java.lang"], + jars = ["depjar.jar"], + ) + util.helper_target( + java_import, + name = name + "/exportjar", + add_opens = ["java.base/java.util"], + jars = ["exportjar.jar"], + ) + + analysis_test( + name = name, + impl = _test_module_flags_impl, + targets = { + "importjar": name + "/import-jar", + "lib": name + "/lib", + }, + ) + +def _test_module_flags_impl(env, targets): + assert_import_module_flags = java_info_subject.from_target(env, targets.importjar).module_flags() + assert_import_module_flags.add_exports().contains_exactly(["java.base/java.lang"]) + assert_import_module_flags.add_opens().contains_exactly(["java.base/java.util"]) + + assert_lib_module_flags = java_info_subject.from_target(env, targets.lib).module_flags() + assert_lib_module_flags.add_exports().contains_exactly(["java.base/java.lang"]) + assert_lib_module_flags.add_opens().contains_exactly(["java.base/java.util"]) + def java_import_tests(name): test_suite( name = name, @@ -227,5 +279,6 @@ def java_import_tests(name): _test_deps, _test_commandline_contains_target_label, _test_java_library_allows_import_in_deps, + _test_module_flags, ], ) diff --git a/test/java/testutil/helper.bzl b/test/java/testutil/helper.bzl new file mode 100644 index 00000000..eace0f85 --- /dev/null +++ b/test/java/testutil/helper.bzl @@ -0,0 +1,20 @@ +"""Misc helpers for rules_java testing""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test") +load("@rules_testing//lib:util.bzl", "util") + +def always_passes(name): + """Declares a fake, always passing test + + Args: + name: (str) the name of the test + """ + util.helper_target( + native.filegroup, + name = name + "/empty", + ) + analysis_test( + name = name, + impl = lambda *a, **kw: None, + target = name + "/empty", + ) diff --git a/test/java/testutil/java_info_subject.bzl b/test/java/testutil/java_info_subject.bzl index 972dc47d..f263b04f 100644 --- a/test/java/testutil/java_info_subject.bzl +++ b/test/java/testutil/java_info_subject.bzl @@ -26,6 +26,7 @@ def _new_java_info_subject(java_info, meta): transitive_source_jars = lambda: subjects.depset_file(java_info.transitive_source_jars, self.meta.derive("transitive_source_jars")), transitive_source_jars_list = lambda: subjects.collection(java_info.transitive_source_jars.to_list(), self.meta.derive("transitive_source_jars.to_list()")), runtime_output_jars = lambda: subjects.depset_file(java_info.runtime_output_jars, self.meta.derive("runtime_output_jars")), + module_flags = lambda: _new_java_module_flags_subject(self.actual, self.meta), ) return public @@ -37,6 +38,17 @@ def _java_info_subject_from_target(env, target): }, )) +def _new_java_module_flags_subject(java_info, meta): + self = struct( + actual = java_info.module_flags_info, + meta = meta.derive("module_flags_info"), + ) + public = struct( + add_exports = lambda: subjects.collection(self.actual.add_exports.to_list(), self.meta.derive("add_exports")), + add_opens = lambda: subjects.collection(self.actual.add_opens.to_list(), self.meta.derive("add_opens")), + ) + return public + def _new_java_compilation_info_subject(java_info, meta): self = struct( actual = java_info.compilation_info, From 949d4a9397681b8163681b68c3460030ec6c89d6 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 02:26:33 -0700 Subject: [PATCH 255/465] Migrate the `JavaImportConfiguredTargetTest.testSrcJars` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756219717 Change-Id: I84e33849c1d5d8e6411b68b337089d0c000f8f43 --- test/java/common/rules/java_import_tests.bzl | 21 ++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index fbf21518..3221f4ed 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -269,6 +269,26 @@ def _test_module_flags_impl(env, targets): assert_lib_module_flags.add_exports().contains_exactly(["java.base/java.lang"]) assert_lib_module_flags.add_opens().contains_exactly(["java.base/java.util"]) +def _test_src_jars(name): + util.helper_target( + java_import, + name = name + "/libraryjar_with_srcjar", + jars = ["import.jar"], + srcjar = "library.srcjar", + ) + + analysis_test( + name = name, + impl = _test_src_jars_impl, + target = name + "/libraryjar_with_srcjar", + ) + +def _test_src_jars_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + assert_java_info.outputs().source_output_jars().contains_exactly([ + "{package}/library.srcjar", + ]) + def java_import_tests(name): test_suite( name = name, @@ -280,5 +300,6 @@ def java_import_tests(name): _test_commandline_contains_target_label, _test_java_library_allows_import_in_deps, _test_module_flags, + _test_src_jars, ], ) From e4e63dfa306f5d657232e1b93325e48b46e2ebde Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 02:47:57 -0700 Subject: [PATCH 256/465] Migrate the `JavaImportConfiguredTargetTest.testFromGenrule` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756225826 Change-Id: Ie84ffd3836e2a47685ab6fb52ccaa4c57226d155 --- test/java/common/rules/java_import_tests.bzl | 51 ++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 3221f4ed..cea1e26d 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -289,6 +289,56 @@ def _test_src_jars_impl(env, target): "{package}/library.srcjar", ]) +def _test_from_genrule(name): + target_name = name + "/library-jar" + util.helper_target( + native.genrule, + name = target_name + "/generated_jar", + outs = [target_name + "/generated.jar"], + cmd = "", + ) + util.helper_target( + native.genrule, + name = target_name + "/generated_src_jar", + outs = [target_name + "/generated.srcjar"], + cmd = "", + ) + util.helper_target( + java_import, + name = target_name + "/libraryjar", + jars = ["library.jar"], + ) + util.helper_target( + java_import, + name = target_name, + jars = [target_name + "/generated_jar"], + srcjar = target_name + "/generated.srcjar", + exports = [target_name + "/libraryjar"], + ) + + analysis_test( + name = name, + impl = _test_from_genrule_impl, + targets = { + "lib": target_name, + "gen": target_name + "/generated_jar", + }, + ) + +def _test_from_genrule_impl(env, targets): + assert_compilation_args = java_info_subject.from_target(env, targets.lib).compilation_args() + assert_compilation_args.transitive_compile_time_jars().contains_exactly([ + "{package}/_ijar/{name}/{package}/{name}/generated-ijar.jar", + "{package}/_ijar/{name}/libraryjar/{package}/library-ijar.jar", + ]) + assert_compilation_args.transitive_runtime_jars().contains_exactly([ + "{package}/library.jar", + "{package}/{name}/generated.jar", + ]) + + jar = targets.lib[JavaInfo].transitive_runtime_jars.to_list()[0].short_path + env.expect.that_target(targets.gen).action_generating(jar).mnemonic().equals("Genrule") + def java_import_tests(name): test_suite( name = name, @@ -301,5 +351,6 @@ def java_import_tests(name): _test_java_library_allows_import_in_deps, _test_module_flags, _test_src_jars, + _test_from_genrule, ], ) From 2c52caef816c1000234e8971566e227eb3fa9d07 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 03:12:31 -0700 Subject: [PATCH 257/465] Migrate the `JavaImportConfiguredTargetTest.testTransitiveDependencies` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756232605 Change-Id: I68afea64884c5a9d3e37ddd7fb0be86a81ab96b7 --- test/java/common/rules/java_import_tests.bzl | 44 ++++++++++++ test/java/testutil/BUILD | 4 ++ test/java/testutil/javac_action_subject.bzl | 49 +++++++++++++ .../testutil/javac_action_subject_tests.bzl | 70 +++++++++++++++++++ 4 files changed, 167 insertions(+) create mode 100644 test/java/testutil/javac_action_subject.bzl create mode 100644 test/java/testutil/javac_action_subject_tests.bzl diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index cea1e26d..c400ec82 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -9,6 +9,7 @@ load("//java:java_library.bzl", "java_library") load("//java/common:java_info.bzl", "JavaInfo") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") def _test_java_import_attributes(name): @@ -339,6 +340,48 @@ def _test_from_genrule_impl(env, targets): jar = targets.lib[JavaInfo].transitive_runtime_jars.to_list()[0].short_path env.expect.that_target(targets.gen).action_generating(jar).mnemonic().equals("Genrule") +# Regression test for b/13936397: don't flatten transitive dependencies into direct deps. +def _test_transitive_dependencies(name): + target_name = name + "/javalib2" + util.helper_target( + java_import, + name = target_name + "/libraryjar", + jars = ["library.jar"], + ) + util.helper_target( + java_library, + name = target_name + "/lib", + srcs = ["Lib.java"], + deps = [target_name + "/libraryjar"], + ) + util.helper_target( + java_import, + name = target_name + "/library2-jar", + jars = ["library2.jar"], + exports = [target_name + "/lib"], + ) + util.helper_target( + java_library, + name = target_name, + srcs = ["Other.java"], + deps = [target_name + "/library2-jar"], + ) + + analysis_test( + name = name, + impl = _test_transitive_dependencies_impl, + target = target_name, + ) + +def _test_transitive_dependencies_impl(env, target): + assert_javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + + # Direct jars should NOT include libraryjar-ijar.jar + assert_javac_action.direct_dependencies().contains_exactly([ + "{bin_path}/{package}/_ijar/{name}/library2-jar/{package}/library2-ijar.jar", + "{bin_path}/{package}/lib{name}/lib-hjar.jar", + ]) + def java_import_tests(name): test_suite( name = name, @@ -352,5 +395,6 @@ def java_import_tests(name): _test_module_flags, _test_src_jars, _test_from_genrule, + _test_transitive_dependencies, ], ) diff --git a/test/java/testutil/BUILD b/test/java/testutil/BUILD index c2afbb31..748abb4b 100644 --- a/test/java/testutil/BUILD +++ b/test/java/testutil/BUILD @@ -1 +1,5 @@ +load(":javac_action_subject_tests.bzl", "javac_action_subject_tests") + package(default_applicable_licenses = ["@rules_java//:license"]) + +javac_action_subject_tests(name = "javac_action_subject_tests") diff --git a/test/java/testutil/javac_action_subject.bzl b/test/java/testutil/javac_action_subject.bzl new file mode 100644 index 00000000..0a14c777 --- /dev/null +++ b/test/java/testutil/javac_action_subject.bzl @@ -0,0 +1,49 @@ +"""Bespoke rules_testing subject for the Java compilation action""" + +load("@rules_testing//lib:truth.bzl", "subjects", "truth") +load("@rules_testing//lib:util.bzl", "TestingAspectInfo") + +def _new_javac_action_subject(env, target, output): + action = env.expect.that_target(target).action_generating(output).actual + self = struct( + actual = action, + parsed_flags = _parse_flags(action.argv), + meta = truth.expect(env).meta.derive( + "Javac", + format_str_kwargs = { + "name": target.label.name, + "package": target.label.package, + "bin_path": target[TestingAspectInfo].bin_path, + }, + ), + ) + public = struct( + direct_dependencies = lambda: subjects.collection(self.parsed_flags["--direct_dependencies"], self.meta.derive("--direct_dependencies"), format = True), + ) + return public + +def _parse_flags(argv): + flag_values = {} + current_flag_name = None + for idx, arg in enumerate(argv): + if idx == 0: + continue # java command + if arg.startswith("-"): + if "=" in arg: + parts = arg.split("=", 1) + flag_values.setdefault(parts[0], []).append(parts[1]) + current_flag_name = None + else: + flag_values.setdefault(arg, []) + current_flag_name = arg + else: + if not current_flag_name: + fail("No preceding flag for value:", arg, "at index:", idx, "\nargv:\n", argv) + flag_values[current_flag_name].append(arg) + + return flag_values + +javac_action_subject = struct( + of = _new_javac_action_subject, + parse_flags = _parse_flags, # exposed for testing this method itself +) diff --git a/test/java/testutil/javac_action_subject_tests.bzl b/test/java/testutil/javac_action_subject_tests.bzl new file mode 100644 index 00000000..eba3f76b --- /dev/null +++ b/test/java/testutil/javac_action_subject_tests.bzl @@ -0,0 +1,70 @@ +"""Tests for the javac_action_subject""" + +load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") +load(":javac_action_subject.bzl", "javac_action_subject") + +def _parse_flags_test_impl(ctx): + env = unittest.begin(ctx) + flags = javac_action_subject.parse_flags([ + "/usr/bin/java", + "-Xmx1g", + "-XX:SomeProp=SomeVal", + "-Dcom.google.foo=bar", + "--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", + "--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED", + "--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED", + "--add-opens=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED", + "-jar", + "JavaBuilder_deploy.jar", + "--output", + "blaze-out/k8/bin/pkg/libfoo.jar", + "-source", + "21", + "-target", + "17", + "-g", + "-parameters", + "-sourcepath", + ":", + "-Xmaxerrs", + "123", + "--", + "--strict_java_deps", + "ERROR", + "--classpath", + "pkg/bar-hjar.jar", + "other/pkg/baz.jar", + ]) + asserts.equals(env, { + "-Xmx1g": [], + "-XX:SomeProp": ["SomeVal"], + "-Dcom.google.foo": ["bar"], + "--add-exports": [ + "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", + "jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED", + ], + "--add-opens": [ + "jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED", + "jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED", + ], + "-jar": ["JavaBuilder_deploy.jar"], + "--output": ["blaze-out/k8/bin/pkg/libfoo.jar"], + "-source": ["21"], + "-target": ["17"], + "-g": [], + "-parameters": [], + "-sourcepath": [":"], + "-Xmaxerrs": ["123"], + "--": [], + "--strict_java_deps": ["ERROR"], + "--classpath": ["pkg/bar-hjar.jar", "other/pkg/baz.jar"], + }, flags) + return unittest.end(env) + +_parse_flags_test = unittest.make(_parse_flags_test_impl) + +def javac_action_subject_tests(name): + unittest.suite( + name, + _parse_flags_test, + ) From bfcc700b97fe6c095f4effb436ad3b1e2e0a6947 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 03:37:48 -0700 Subject: [PATCH 258/465] Migrate the `JavaImportConfiguredTargetTest.testExposesJavaProvider` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756239088 Change-Id: I1aa7e1e8d96203ba346044d653d7df17a0b6c076 --- test/java/common/rules/java_import_tests.bzl | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index c400ec82..2e7fd500 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -382,6 +382,25 @@ def _test_transitive_dependencies_impl(env, target): "{bin_path}/{package}/lib{name}/lib-hjar.jar", ]) +def _test_exposes_java_provider(name): + util.helper_target( + java_import, + name = name + "/libraryjar", + jars = ["library.jar"], + ) + + analysis_test( + name = name, + impl = _test_exposes_java_provider_impl, + target = name + "/libraryjar", + ) + +def _test_exposes_java_provider_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + assert_java_info.compilation_args().transitive_runtime_jars().contains_exactly([ + "{package}/library.jar", + ]) + def java_import_tests(name): test_suite( name = name, @@ -396,5 +415,6 @@ def java_import_tests(name): _test_src_jars, _test_from_genrule, _test_transitive_dependencies, + _test_exposes_java_provider, ], ) From e891c30a67c8ea9ab560654f57f32404ba3fbc31 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 03:56:57 -0700 Subject: [PATCH 259/465] Migrate the `JavaImportConfiguredTargetTest.testAllowsJarInSrcjars` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756244222 Change-Id: I9ce7d0b806543c2904cb866a2bd52c762c63288e --- test/java/common/rules/java_import_tests.bzl | 21 ++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 2e7fd500..41c1fe0e 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -401,6 +401,26 @@ def _test_exposes_java_provider_impl(env, target): "{package}/library.jar", ]) +def _test_jars_allowed_in_srcjar(name): + util.helper_target( + java_import, + name = name + "/library", + jars = ["somelib.jar"], + srcjar = "somelib-src.jar", + ) + + analysis_test( + name = name, + impl = _test_jars_allowed_in_srcjar_impl, + target = name + "/library", + ) + +def _test_jars_allowed_in_srcjar_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + assert_java_info.outputs().source_output_jars().contains_exactly([ + "{package}/somelib-src.jar", + ]) + def java_import_tests(name): test_suite( name = name, @@ -416,5 +436,6 @@ def java_import_tests(name): _test_from_genrule, _test_transitive_dependencies, _test_exposes_java_provider, + _test_jars_allowed_in_srcjar, ], ) From c09ccc491efa3837c18724461523c4c2a3909472 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 04:03:05 -0700 Subject: [PATCH 260/465] Update Bazel versions for `@rules_java` CI (ignore-relnotes) PiperOrigin-RevId: 756245762 Change-Id: I389903c6c842ab98fd9d75d7720cd62cef26d01b --- .bazelci/presubmit.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index a42c2810..6dc8cf3e 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -48,14 +48,14 @@ buildifier: latest matrix: all_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"] integration_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"] - bazel: ["7.4.0", "8.1.0", "last_green"] # Bazel 6 tested separately, needs different flags - modern_bazel: ["8.1.0", "last_green"] # Fully supported Bazel versions + bazel: ["7.6.1", "8.2.1", "last_green"] # Bazel 6 tested separately, needs different flags + modern_bazel: ["8.2.1", "last_green"] # Fully supported Bazel versions tasks: # Bazel 7.x build_and_test_bazel7: - name: "Bazel 7.5.0" - bazel: "7.5.0" + name: "Bazel 7.6.1" + bazel: "7.6.1" platform: ${{ all_platforms }} build_targets: *build_targets test_targets: *test_targets From 352ae328a7bb8ee9a986f041fa29e1e0554a8f71 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 04:38:34 -0700 Subject: [PATCH 261/465] Migrate the `JavaImportConfiguredTargetTest.testPermitsEmptyJars` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756255370 Change-Id: Ia7dd37d7491a3975903f2a2ccbbcb31e81dd2ed4 --- MODULE.bazel | 7 +++ WORKSPACE | 6 +-- test/java/common/rules/java_import_tests.bzl | 53 ++++++++++++++++++++ 3 files changed, 63 insertions(+), 3 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 400a4c2f..4b700447 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -8,6 +8,13 @@ module( bazel_dep(name = "platforms", version = "0.0.11") bazel_dep(name = "rules_cc", version = "0.0.15") bazel_dep(name = "bazel_features", version = "1.28.0") +archive_override( + module_name = "bazel_features", + integrity = "sha256-SOPLvKDy+RN7GHKN8eFjQ+58Wx4Isj+vcXoUluBqxLo=", + strip_prefix = "bazel_features-59915eb2ca215c7b2266c83c49bb7522a5b6737f", + urls = ["https://github.com/bazel-contrib/bazel_features/archive/59915eb2ca215c7b2266c83c49bb7522a5b6737f.zip"], +) + bazel_dep(name = "bazel_skylib", version = "1.6.1") bazel_dep(name = "protobuf", version = "27.0", repo_name = "com_google_protobuf") bazel_dep(name = "zlib", version = "1.3.1.bcr.5") diff --git a/WORKSPACE b/WORKSPACE index 3cb23798..6b8beb60 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -66,9 +66,9 @@ test_repositories() http_archive( name = "bazel_features", - sha256 = "2f057dd02098a106095ea291b4344257398a059eadb2c74cc470de0f9664dccd", - strip_prefix = "bazel_features-1.28.0", - url = "https://github.com/bazel-contrib/bazel_features/releases/download/v1.28.0/bazel_features-v1.28.0.tar.gz", + sha256 = "48e3cbbca0f2f9137b18728df1e16343ee7c5b1e08b23faf717a1496e06ac4ba", + strip_prefix = "bazel_features-59915eb2ca215c7b2266c83c49bb7522a5b6737f", + url = "https://github.com/bazel-contrib/bazel_features/archive/59915eb2ca215c7b2266c83c49bb7522a5b6737f.zip", ) load("@bazel_features//:deps.bzl", "bazel_features_deps") diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 41c1fe0e..92dce457 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -421,6 +421,57 @@ def _test_jars_allowed_in_srcjar_impl(env, target): "{package}/somelib-src.jar", ]) +def _test_permits_empty_jars_with_flag(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + # exit early because this test case would be a loading phase error otherwise + always_passes(name) + return + + util.helper_target( + java_import, + name = name + "/rule", + jars = [], + ) + + analysis_test( + name = name, + impl = _test_permits_empty_jars_with_flag_impl, + target = name + "/rule", + config_settings = { + "//command_line_option:incompatible_disallow_java_import_empty_jars": False, + }, + ) + +def _test_permits_empty_jars_with_flag_impl(_env, _target): + pass + +def _test_disallows_empty_jars(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + # exit early because this test case would be a loading phase error otherwise + always_passes(name) + return + + util.helper_target( + java_import, + name = name + "/rule", + jars = [], + ) + + analysis_test( + name = name, + impl = _test_disallows_empty_jars_impl, + target = name + "/rule", + config_settings = { + "//command_line_option:incompatible_disallow_java_import_empty_jars": True, + }, + expect_failure = True, + ) + +def _test_disallows_empty_jars_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("empty java_import.jars is no longer supported"), + ) + def java_import_tests(name): test_suite( name = name, @@ -437,5 +488,7 @@ def java_import_tests(name): _test_transitive_dependencies, _test_exposes_java_provider, _test_jars_allowed_in_srcjar, + _test_permits_empty_jars_with_flag, + _test_disallows_empty_jars, ], ) From 3b0942996d75f310d122e47d8efc1e3f9f398fb7 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 05:00:24 -0700 Subject: [PATCH 262/465] Migrate the `JavaImportConfiguredTargetTest.testDisallowsFilesInExports` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756261082 Change-Id: Idbf3b8ec2aadc9548b74627029d32cd2b2563416 --- test/java/common/rules/java_import_tests.bzl | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 92dce457..064c59a6 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -472,6 +472,27 @@ def _test_disallows_empty_jars_impl(env, target): matching.str_matches("empty java_import.jars is no longer supported"), ) +def _test_disallows_files_in_exports(name): + util.helper_target( + java_import, + name = name + "/rule", + jars = ["good.jar"], + # we can't create scratch files, so just use one that we know has a label + exports = ["BUILD"], + ) + + analysis_test( + name = name, + impl = _test_disallows_files_in_exports_impl, + target = name + "/rule", + expect_failure = True, + ) + +def _test_disallows_files_in_exports_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("source file * is misplaced here (expected no files)"), + ) + def java_import_tests(name): test_suite( name = name, @@ -490,5 +511,6 @@ def java_import_tests(name): _test_jars_allowed_in_srcjar, _test_permits_empty_jars_with_flag, _test_disallows_empty_jars, + _test_disallows_files_in_exports, ], ) From d52536dbadaad9b8b02322e7847a8dbbdbe52e58 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 05:15:02 -0700 Subject: [PATCH 263/465] Migrate the `JavaImportConfiguredTargetTest.testDisallowsArbitraryFiles` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756265386 Change-Id: Ib9756b4bb3b4bef372f344ad6c11b9593e60f9a1 --- test/java/common/rules/java_import_tests.bzl | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 064c59a6..b865c76e 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -493,6 +493,25 @@ def _test_disallows_files_in_exports_impl(env, target): matching.str_matches("source file * is misplaced here (expected no files)"), ) +def _test_disallows_arbitrary_files(name): + util.helper_target( + java_import, + name = name + "/rule", + jars = ["not-a-jar.txt"], + ) + + analysis_test( + name = name, + impl = _test_disallows_arbitrary_files_impl, + target = name + "/rule", + expect_failure = True, + ) + +def _test_disallows_arbitrary_files_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("does not produce any java_import jars files (expected .jar)"), + ) + def java_import_tests(name): test_suite( name = name, @@ -512,5 +531,6 @@ def java_import_tests(name): _test_permits_empty_jars_with_flag, _test_disallows_empty_jars, _test_disallows_files_in_exports, + _test_disallows_arbitrary_files, ], ) From 8aceb11a491b3d96ea3633b7a12dde0d3145f79a Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 05:43:40 -0700 Subject: [PATCH 264/465] Migrate the `JavaImportConfiguredTargetTest.testDisallowsArbitraryFilesFromGenrule` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756272969 Change-Id: I8890abb597a68653a31d23f98eb70c92c99232c7 --- test/java/common/rules/java_import_tests.bzl | 28 +++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index b865c76e..85d1973c 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -509,7 +509,32 @@ def _test_disallows_arbitrary_files(name): def _test_disallows_arbitrary_files_impl(env, target): env.expect.that_target(target).failures().contains_predicate( - matching.str_matches("does not produce any java_import jars files (expected .jar)"), + matching.str_matches("file '*:not-a-jar.txt' is misplaced here (expected .jar)"), + ) + +def _test_disallows_arbitrary_files_from_genrule(name): + util.helper_target( + native.genrule, + name = name + "/gen", + outs = ["not-a-jar.txt"], + cmd = "", + ) + util.helper_target( + java_import, + name = name + "/rule", + jars = [name + "/gen"], + ) + + analysis_test( + name = name, + impl = _test_disallows_arbitrary_files_from_genrule_impl, + target = name + "/rule", + expect_failure = True, + ) + +def _test_disallows_arbitrary_files_from_genrule_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("'*/gen' does not produce any java_import jars files (expected .jar)"), ) def java_import_tests(name): @@ -532,5 +557,6 @@ def java_import_tests(name): _test_disallows_empty_jars, _test_disallows_files_in_exports, _test_disallows_arbitrary_files, + _test_disallows_arbitrary_files_from_genrule, ], ) From a06d6ccda8234424a318a13b60c062faba62acaf Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 06:09:30 -0700 Subject: [PATCH 265/465] Migrate the `JavaImportConfiguredTargetTest.testDisallowsJavaRulesInSrcs` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756280462 Change-Id: Id5d5249e083fa9fd1f4d94ae1811371bca48b582 --- test/java/common/rules/java_import_tests.bzl | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 85d1973c..d691c01d 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -537,6 +537,33 @@ def _test_disallows_arbitrary_files_from_genrule_impl(env, target): matching.str_matches("'*/gen' does not produce any java_import jars files (expected .jar)"), ) +def _test_disallows_java_rules_in_jars(name): + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["JavaLib.java"], + ) + util.helper_target( + java_import, + name = name + "/rule", + jars = [name + "/lib"], + ) + + analysis_test( + name = name, + impl = _test_disallows_java_rules_in_jars_impl, + target = name + "/rule", + expect_failure = True, + ) + +def _test_disallows_java_rules_in_jars_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.any( + matching.str_matches("'jars' attribute cannot contain labels of Java targets"), + matching.str_matches("should not refer to Java rules"), # Bazel 6 + ), + ) + def java_import_tests(name): test_suite( name = name, @@ -558,5 +585,6 @@ def java_import_tests(name): _test_disallows_files_in_exports, _test_disallows_arbitrary_files, _test_disallows_arbitrary_files_from_genrule, + _test_disallows_java_rules_in_jars, ], ) From d2df00616c9a27da5d7f54aa334bc5e9ba37f3d5 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 06:43:38 -0700 Subject: [PATCH 266/465] Migrate the `JavaImportConfiguredTargetTest.testExports` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756289741 Change-Id: Ifd033bedc3115f272313926f5a46c591f6ac9cc5 --- test/java/common/rules/java_import_tests.bzl | 34 ++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index d691c01d..f18d0e4e 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -564,6 +564,39 @@ def _test_disallows_java_rules_in_jars_impl(env, target): ), ) +def _test_disallows_exports_with_flag(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + # exit early because this test case would be a loading phase error otherwise + always_passes(name) + return + + util.helper_target( + java_library, + name = name + "/dep", + srcs = ["Dep.java"], + ) + util.helper_target( + java_import, + name = name + "/rule", + jars = ["dummy.jar"], + exports = [name + "/dep"], + ) + + analysis_test( + name = name, + impl = _test_disallows_exports_with_flag_impl, + target = name + "/rule", + expect_failure = True, + config_settings = { + "//command_line_option:incompatible_disallow_java_import_exports": True, + }, + ) + +def _test_disallows_exports_with_flag_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("java_import.exports is no longer supported; use java_import.deps instead"), + ) + def java_import_tests(name): test_suite( name = name, @@ -586,5 +619,6 @@ def java_import_tests(name): _test_disallows_arbitrary_files, _test_disallows_arbitrary_files_from_genrule, _test_disallows_java_rules_in_jars, + _test_disallows_exports_with_flag, ], ) From 3b5ebd8b0dedf5d57aaacc83fd2e6fc45da30865 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 07:48:59 -0700 Subject: [PATCH 267/465] Migrate the `JavaImportConfiguredTargetTest.testIjarCanBeDisabled` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756309378 Change-Id: I2019ca733d33b0ce88c55dc3e4083b5a0f881993 --- test/java/common/rules/java_import_tests.bzl | 30 ++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index f18d0e4e..9962db8b 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -597,6 +597,35 @@ def _test_disallows_exports_with_flag_impl(env, target): matching.str_matches("java_import.exports is no longer supported; use java_import.deps instead"), ) +def _test_ijar_can_be_disabled(name): + util.helper_target( + java_library, + name = name + "/a", + srcs = ["A.java"], + deps = [name + "/b"], + ) + util.helper_target( + java_import, + name = name + "/b", + jars = ["b.jar"], + ) + + analysis_test( + name = name, + impl = _test_ijar_can_be_disabled_impl, + target = name + "/a", + config_settings = { + "//command_line_option:use_ijars": False, + }, + ) + +def _test_ijar_can_be_disabled_impl(env, target): + assert_jars = java_info_subject.from_target(env, target).compilation_args().transitive_compile_time_jars() + assert_jars.contains_exactly([ + "{package}/lib{name}-hjar.jar", + "{package}/b.jar", + ]) + def java_import_tests(name): test_suite( name = name, @@ -620,5 +649,6 @@ def java_import_tests(name): _test_disallows_arbitrary_files_from_genrule, _test_disallows_java_rules_in_jars, _test_disallows_exports_with_flag, + _test_ijar_can_be_disabled, ], ) From 54011738c4b7a2c72ce8128c88985b506ab044bf Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 08:09:59 -0700 Subject: [PATCH 268/465] Migrate the `JavaImportConfiguredTargetTest.testDuplicateJarsThroughFilegroup` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756316477 Change-Id: Ib6e82c964d3ac948055dd26ac31ee9a345425ebd --- test/java/common/rules/java_import_tests.bzl | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 9962db8b..3cfe11a4 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -626,6 +626,33 @@ def _test_ijar_can_be_disabled_impl(env, target): "{package}/b.jar", ]) +def _test_duplicate_jars_through_filegroup(name): + util.helper_target( + native.filegroup, + name = name + "/jars", + srcs = ["a.jar"], + ) + util.helper_target( + java_import, + name = name + "/ji-with-dupe-through-fg", + jars = ["a.jar", name + "/jars"], + ) + + analysis_test( + name = name, + impl = _test_duplicate_jars_through_filegroup_impl, + target = name + "/ji-with-dupe-through-fg", + expect_failure = True, + ) + +def _test_duplicate_jars_through_filegroup_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.any( + matching.str_matches("in jars attribute of java_import rule */ji-with-dupe-through-fg: a.jar is a duplicate"), + matching.str_matches("a.jar is a duplicate"), # Bazel 6 + ), + ) + def java_import_tests(name): test_suite( name = name, @@ -650,5 +677,6 @@ def java_import_tests(name): _test_disallows_java_rules_in_jars, _test_disallows_exports_with_flag, _test_ijar_can_be_disabled, + _test_duplicate_jars_through_filegroup, ], ) From d3ff0e01daeec60e39f5024d0c2a8204233a73bd Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 08:28:06 -0700 Subject: [PATCH 269/465] Migrate the `JavaImportConfiguredTargetTest.testRuntimeDepsAreNotOnClasspath` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756322627 Change-Id: I1831da5f84ef3f94cd6feacca8d727df56a7eef8 --- test/java/common/rules/java_import_tests.bzl | 39 ++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 3cfe11a4..83b28ac8 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -653,6 +653,44 @@ def _test_duplicate_jars_through_filegroup_impl(env, target): ), ) +def _test_runtime_deps_are_not_on_classpath(name): + target_name = name + "/depends_on_runtimedep" + util.helper_target( + java_import, + name = target_name + "/import_dep", + jars = ["import_compile.jar"], + runtime_deps = ["import_runtime.jar"], + ) + util.helper_target( + java_library, + name = target_name + "/library_dep", + srcs = ["library_compile.java"], + ) + util.helper_target( + java_library, + name = target_name, + srcs = ["dummy.java"], + deps = [ + target_name + "/import_dep", + target_name + "/library_dep", + ], + ) + + analysis_test( + name = name, + impl = _test_runtime_deps_are_not_on_classpath_impl, + target = name + "/depends_on_runtimedep", + ) + +def _test_runtime_deps_are_not_on_classpath_impl(env, target): + assert_javac = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + + # Direct jars should NOT include import_runtime.jar + assert_javac.direct_dependencies().contains_exactly([ + "{bin_path}/{package}/_ijar/{name}/import_dep/{package}/import_compile-ijar.jar", + "{bin_path}/{package}/lib{name}/library_dep-hjar.jar", + ]) + def java_import_tests(name): test_suite( name = name, @@ -678,5 +716,6 @@ def java_import_tests(name): _test_disallows_exports_with_flag, _test_ijar_can_be_disabled, _test_duplicate_jars_through_filegroup, + _test_runtime_deps_are_not_on_classpath, ], ) From 4bb7207e7e3f54bd04fc757f87294b96344d185a Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 08:49:39 -0700 Subject: [PATCH 270/465] Migrate the `JavaImportConfiguredTargetTest.testExportsRunfilesCollection` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756329625 Change-Id: I58dd7eb9a43140442960fa270e7fc86d431b2cbf --- test/java/common/rules/java_import_tests.bzl | 37 ++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 83b28ac8..8aee3936 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -4,6 +4,7 @@ load("@bazel_features//:features.bzl", "bazel_features") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") +load("//java:java_binary.bzl", "java_binary") load("//java:java_import.bzl", "java_import") load("//java:java_library.bzl", "java_library") load("//java/common:java_info.bzl", "JavaInfo") @@ -691,6 +692,41 @@ def _test_runtime_deps_are_not_on_classpath_impl(env, target): "{bin_path}/{package}/lib{name}/library_dep-hjar.jar", ]) +def _test_exports_runfile_collection(name): + target_name = name + "/tool" + util.helper_target( + java_import, + name = target_name + "/other_lib", + data = ["foo.txt"], + jars = ["other.jar"], + ) + util.helper_target( + java_import, + name = target_name + "/lib", + jars = ["lib.jar"], + exports = [target_name + "/other_lib"], + ) + util.helper_target( + java_binary, + name = target_name, + data = [target_name + "/lib"], + main_class = "com.google.exports.Launcher", + ) + + analysis_test( + name = name, + impl = _test_exports_runfile_collection_impl, + target = target_name, + ) + +def _test_exports_runfile_collection_impl(env, target): + assert_runfiles = env.expect.that_target(target).runfiles() + assert_runfiles.contains_at_least_predicates([ + matching.str_matches("/lib.jar"), + matching.str_matches("/other.jar"), + matching.str_matches("/foo.txt"), + ]) + def java_import_tests(name): test_suite( name = name, @@ -717,5 +753,6 @@ def java_import_tests(name): _test_ijar_can_be_disabled, _test_duplicate_jars_through_filegroup, _test_runtime_deps_are_not_on_classpath, + _test_exports_runfile_collection, ], ) From e6942214a8e6ac9e18672848ba481c7978a1b521 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 09:04:59 -0700 Subject: [PATCH 271/465] Migrate the `JavaImportConfiguredTargetTest.testTransitiveSourceJars` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756335072 Change-Id: I16dec8ab3e969b9f4ae2fb199186944321fb14cb --- test/java/common/rules/java_import_tests.bzl | 29 ++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 8aee3936..daf0134d 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -727,6 +727,34 @@ def _test_exports_runfile_collection_impl(env, target): matching.str_matches("/foo.txt"), ]) +def _test_transitive_source_jars(name): + target_name = name + "/a" + util.helper_target( + java_import, + name = target_name, + jars = ["dummy.jar"], + srcjar = "dummy-src.jar", + exports = [target_name + "/b"], + ) + util.helper_target( + java_library, + name = target_name + "/b", + srcs = ["B.java"], + ) + + analysis_test( + name = name, + impl = _test_transitive_source_jars_impl, + target = target_name, + ) + +def _test_transitive_source_jars_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/dummy-src.jar", + "{package}/lib{name}/b-src.jar", + ]) + def java_import_tests(name): test_suite( name = name, @@ -754,5 +782,6 @@ def java_import_tests(name): _test_duplicate_jars_through_filegroup, _test_runtime_deps_are_not_on_classpath, _test_exports_runfile_collection, + _test_transitive_source_jars, ], ) From 27bda7d6e30ea633aa7e85a43b911d092e37fa4f Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 09:20:12 -0700 Subject: [PATCH 272/465] Migrate the `JavaImportConfiguredTargetTest.testNeverlinkIsPopulated` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756340029 Change-Id: I8174a763ab569b2c15ddf659bdbb0a0561ace91d --- test/java/common/rules/java_import_tests.bzl | 26 ++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index daf0134d..0d398140 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -755,6 +755,31 @@ def _test_transitive_source_jars_impl(env, target): "{package}/lib{name}/b-src.jar", ]) +def _test_neverlink_is_populated(name): + target_name = name + "/jar" + util.helper_target( + java_library, + name = target_name + "/lib", + ) + util.helper_target( + java_import, + name = target_name, + jars = ["dummy.jar"], + neverlink = 1, + exports = [target_name + "/lib"], + ) + + analysis_test( + name = name, + impl = _test_neverlink_is_populated_impl, + target = target_name, + # in Bazel 6, JavaInfo._neverlink isn't exposed to Starlark + attr_values = {"tags": ["min_bazel_7"]}, + ) + +def _test_neverlink_is_populated_impl(env, target): + env.expect.that_bool(target[JavaInfo]._neverlink).equals(True) + def java_import_tests(name): test_suite( name = name, @@ -783,5 +808,6 @@ def java_import_tests(name): _test_runtime_deps_are_not_on_classpath, _test_exports_runfile_collection, _test_transitive_source_jars, + _test_neverlink_is_populated, ], ) From 668f1a66a08016767d02fd12b120c0914e94cc7f Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 09:48:34 -0700 Subject: [PATCH 273/465] Migrate the `JavaImportConfiguredTargetTest.testJavaImportValidatesTransitiveProguardSpecs` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756350281 Change-Id: Ie95370099e7ddc4f108730f7b47fea1259d163bb --- test/java/common/rules/java_import_tests.bzl | 36 ++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 0d398140..211d26b6 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -780,6 +780,41 @@ def _test_neverlink_is_populated(name): def _test_neverlink_is_populated_impl(env, target): env.expect.that_bool(target[JavaInfo]._neverlink).equals(True) +def _test_transitive_proguard_specs_are_validated(name): + target_name = name + "/lib" + util.helper_target( + java_import, + name = target_name + "/transitive", + constraints = ["android"], + jars = ["Transitive.jar"], + proguard_specs = ["transitive.pro"], + ) + util.helper_target( + java_import, + name = target_name, + constraints = ["android"], + jars = ["Lib.jar"], + exports = [target_name + "/transitive"], + ) + + analysis_test( + name = name, + impl = _test_transitive_proguard_specs_are_validated_impl, + targets = { + "lib": target_name, + "dep": target_name + "/transitive", + }, + ) + +def _test_transitive_proguard_specs_are_validated_impl(env, targets): + proguard_out = "{package}/validated_proguard/{name}/transitive/{package}/transitive.pro_valid" + env.expect.that_target(targets.lib).output_group( + "_hidden_top_level_INTERNAL_", + ).contains(proguard_out) + env.expect.that_target(targets.dep).action_named("ValidateProguard").inputs().contains( + "{package}/transitive.pro", + ) + def java_import_tests(name): test_suite( name = name, @@ -809,5 +844,6 @@ def java_import_tests(name): _test_exports_runfile_collection, _test_transitive_source_jars, _test_neverlink_is_populated, + _test_transitive_proguard_specs_are_validated, ], ) From cb4ccd139f480d92cdec40fbbd09312a163a32e8 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 10:58:34 -0700 Subject: [PATCH 274/465] Migrate the `JavaImportConfiguredTargetTest.testJavaImportValidatesProguardSpecs` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756379888 Change-Id: If37d40680cb0032a5a8cb2927cd321a7c701188f --- test/java/common/rules/java_import_tests.bzl | 26 ++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 211d26b6..8d3738b5 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -815,6 +815,31 @@ def _test_transitive_proguard_specs_are_validated_impl(env, targets): "{package}/transitive.pro", ) +def _test_proguard_specs_are_validated(name): + target_name = name + "/lib" + util.helper_target( + java_import, + name = target_name, + constraints = ["android"], + jars = ["Lib.jar"], + proguard_specs = ["lib.pro"], + ) + + analysis_test( + name = name, + impl = _test_proguard_specs_are_validated_impl, + target = target_name, + ) + +def _test_proguard_specs_are_validated_impl(env, target): + proguard_out = "{package}/validated_proguard/{name}/{package}/lib.pro_valid" + env.expect.that_target(target).output_group( + "_hidden_top_level_INTERNAL_", + ).contains(proguard_out) + env.expect.that_target(target).action_named("ValidateProguard").inputs().contains( + "{package}/lib.pro", + ) + def java_import_tests(name): test_suite( name = name, @@ -845,5 +870,6 @@ def java_import_tests(name): _test_transitive_source_jars, _test_neverlink_is_populated, _test_transitive_proguard_specs_are_validated, + _test_proguard_specs_are_validated, ], ) From bde9b219262e976aa029a2c670c2ee273e8a22dd Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 11:19:49 -0700 Subject: [PATCH 275/465] Migrate the `JavaImportConfiguredTargetTest.testJavaImportExportsTransitiveProguardSpecs` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 756388852 Change-Id: I630e2162dd7748a2c7378a96307bcc47d65c5e02 --- test/java/common/rules/java_import_tests.bzl | 44 ++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 8d3738b5..295d68cd 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -8,6 +8,7 @@ load("//java:java_binary.bzl", "java_binary") load("//java:java_import.bzl", "java_import") load("//java:java_library.bzl", "java_library") load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:proguard_spec_info.bzl", "ProguardSpecInfo") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") @@ -840,6 +841,48 @@ def _test_proguard_specs_are_validated_impl(env, target): "{package}/lib.pro", ) +def _test_transitive_proguard_specs_are_exported(name): + target_name = name + "/lib" + util.helper_target( + java_import, + name = target_name + "/export", + constraints = ["android"], + jars = ["Export.jar"], + proguard_specs = ["export.pro"], + ) + util.helper_target( + java_import, + name = target_name + "/runtime_dep", + constraints = ["android"], + jars = ["RuntimeDep.jar"], + proguard_specs = ["runtime_dep.pro"], + ) + util.helper_target( + java_import, + name = target_name, + constraints = ["android"], + jars = ["Lib.jar"], + proguard_specs = ["lib.pro"], + exports = [target_name + "/export"], + runtime_deps = [target_name + "/runtime_dep"], + ) + + analysis_test( + name = name, + impl = _test_transitive_proguard_specs_are_exported_impl, + target = target_name, + # Before Bazel 8, native rules use the native ProguardSpecProvider + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _test_transitive_proguard_specs_are_exported_impl(env, target): + spec_basenames = [f.basename for f in target[ProguardSpecInfo].specs.to_list()] + env.expect.that_collection(spec_basenames).contains_exactly([ + "lib.pro_valid", + "export.pro_valid", + "runtime_dep.pro_valid", + ]) + def java_import_tests(name): test_suite( name = name, @@ -871,5 +914,6 @@ def java_import_tests(name): _test_neverlink_is_populated, _test_transitive_proguard_specs_are_validated, _test_proguard_specs_are_validated, + _test_transitive_proguard_specs_are_exported, ], ) From 7a17d5eaa53f61ffe8686e03bff79461e8697006 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 12:03:38 -0700 Subject: [PATCH 276/465] Add a test for java_import srcjar output groups. (ignore-relnotes) PiperOrigin-RevId: 756405594 Change-Id: I5858d7093ac5e4a2de3174b5d4cdb9bfd09f6e02 --- test/java/common/rules/java_import_tests.bzl | 31 ++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 295d68cd..2cea4c62 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -883,6 +883,36 @@ def _test_transitive_proguard_specs_are_exported_impl(env, target): "runtime_dep.pro_valid", ]) +def _test_src_jars_output_groups(name): + target_name = name + "/a" + util.helper_target( + java_import, + name = target_name, + jars = ["jar_a.jar"], + srcjar = "src_jar_a.jar", + deps = [target_name + "/b"], + ) + util.helper_target( + java_import, + name = target_name + "/b", + jars = ["jar_b.jar"], + srcjar = "src_jar_b.jar", + ) + + analysis_test( + name = name, + impl = _test_src_jars_output_groups_impl, + target = target_name, + ) + +def _test_src_jars_output_groups_impl(env, target): + env.expect.that_target(target).output_group("_source_jars").contains_exactly([ + "{package}/src_jar_a.jar", + ]) + env.expect.that_target(target).output_group("_direct_source_jars").contains_exactly([ + "{package}/src_jar_a.jar", + ]) + def java_import_tests(name): test_suite( name = name, @@ -915,5 +945,6 @@ def java_import_tests(name): _test_transitive_proguard_specs_are_validated, _test_proguard_specs_are_validated, _test_transitive_proguard_specs_are_exported, + _test_src_jars_output_groups, ], ) From 02eae7eabbeb473491d23766ee9dc6b90a23aa6b Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 8 May 2025 12:15:04 -0700 Subject: [PATCH 277/465] Add a test for java_import with a custom java rule (ignore-relnotes) PiperOrigin-RevId: 756410044 Change-Id: I9adc599880b5b66c904d02b945d625afb8b53a36 --- test/java/common/rules/java_import_tests.bzl | 36 ++++++++++++++++++++ test/java/testutil/java_info_subject.bzl | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 2cea4c62..680136ae 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -12,6 +12,7 @@ load("//java/common:proguard_spec_info.bzl", "ProguardSpecInfo") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") +load("//test/java/testutil:rules/custom_library.bzl", "custom_library") load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") def _test_java_import_attributes(name): @@ -913,6 +914,40 @@ def _test_src_jars_output_groups_impl(env, target): "{package}/src_jar_a.jar", ]) +def _test_with_custom_library(name): + target_name = name + "/javalib" + util.helper_target( + java_library, + name = target_name, + srcs = ["MyClass.java"], + deps = [target_name + "/foo"], + ) + util.helper_target( + java_import, + name = target_name + "/foo", + jars = ["foo.jar"], + runtime_deps = [target_name + "/javacustomlib"], + ) + util.helper_target( + custom_library, + name = target_name + "/javacustomlib", + srcs = ["Other.java"], + ) + + analysis_test( + name = name, + impl = _test_with_custom_library_impl, + target = target_name, + ) + +def _test_with_custom_library_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + assert_java_info.compilation_info().runtime_classpath_list().contains_exactly_predicates([ + matching.file_basename_equals("javalib.jar"), + matching.file_basename_equals("foo.jar"), + matching.file_basename_equals("javacustomlib.jar"), + ]).in_order() + def java_import_tests(name): test_suite( name = name, @@ -946,5 +981,6 @@ def java_import_tests(name): _test_proguard_specs_are_validated, _test_transitive_proguard_specs_are_exported, _test_src_jars_output_groups, + _test_with_custom_library, ], ) diff --git a/test/java/testutil/java_info_subject.bzl b/test/java/testutil/java_info_subject.bzl index f263b04f..e9242436 100644 --- a/test/java/testutil/java_info_subject.bzl +++ b/test/java/testutil/java_info_subject.bzl @@ -57,7 +57,7 @@ def _new_java_compilation_info_subject(java_info, meta): public = struct( compilation_classpath = lambda: subjects.depset_file(self.actual.compilation_classpath, self.meta.derive("compilation_classpath")), runtime_classpath = lambda: subjects.depset_file(self.actual.runtime_classpath, self.meta.derive("runtime_classpath")), - runtime_classpath_list = lambda: subjects.collection(self.actual.runtime_classpath.to_list(), self.meta.derive("runtime_classpath.to_list()")), + runtime_classpath_list = lambda: subjects.collection(self.actual.runtime_classpath.to_list(), self.meta.derive("runtime_classpath.to_list()"), format = True), javac_options = lambda: subjects.collection(helper.tokenize_javacopts(opts = self.actual.javac_options), self.meta.derive("javac_options")), ) return public From 1d2eecd61d1af30d70ec183c997c04eb82af32dc Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 9 May 2025 16:29:44 -0700 Subject: [PATCH 278/465] Remove support for empty jars attribute from java_import RELNOTES: java_import.jars attributes can no longer be empty, and --noincompatible_disallow_java_import_empty_jars is no longer supported PiperOrigin-RevId: 756947066 Change-Id: I367ea741f95aeee4c26e7ad5e861b18f1da32725 --- .../rules/impl/bazel_java_import_impl.bzl | 10 ++----- test/java/common/rules/java_import_tests.bzl | 27 +------------------ 2 files changed, 3 insertions(+), 34 deletions(-) diff --git a/java/common/rules/impl/bazel_java_import_impl.bzl b/java/common/rules/impl/bazel_java_import_impl.bzl index f018fe7a..44656705 100644 --- a/java/common/rules/impl/bazel_java_import_impl.bzl +++ b/java/common/rules/impl/bazel_java_import_impl.bzl @@ -71,14 +71,8 @@ def _check_export_error(ctx, exports): fail("java_import.exports is no longer supported; use java_import.deps instead") def _check_empty_jars_error(ctx, jars): - # TODO(kotlaja): Remove temporary incompatible flag [disallow_java_import_empty_jars] once migration is done. - if len(jars) > 0: - return # jars is non empty - if not ctx.fragments.java.disallow_java_import_empty_jars(): - return # check disabled by flag - if hasattr(ctx.attr, "_allowlist_java_import_empty_jars") and getattr(ctx.attr, "_allowlist_java_import_empty_jars")[PackageSpecificationInfo].contains(ctx.label): - return # allowlisted - fail("empty java_import.jars is no longer supported " + ctx.label.package) + if len(jars) == 0: + fail("empty java_import.jars is not supported " + ctx.label.package) def _create_java_info_with_dummy_output_file(ctx, srcjar, all_deps, exports, runtime_deps_list, neverlink, cc_info_list, add_exports, add_opens): dummy_jar = ctx.actions.declare_file(ctx.label.name + "_dummy.jar") diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 680136ae..8580c1d4 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -424,30 +424,6 @@ def _test_jars_allowed_in_srcjar_impl(env, target): "{package}/somelib-src.jar", ]) -def _test_permits_empty_jars_with_flag(name): - if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: - # exit early because this test case would be a loading phase error otherwise - always_passes(name) - return - - util.helper_target( - java_import, - name = name + "/rule", - jars = [], - ) - - analysis_test( - name = name, - impl = _test_permits_empty_jars_with_flag_impl, - target = name + "/rule", - config_settings = { - "//command_line_option:incompatible_disallow_java_import_empty_jars": False, - }, - ) - -def _test_permits_empty_jars_with_flag_impl(_env, _target): - pass - def _test_disallows_empty_jars(name): if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: # exit early because this test case would be a loading phase error otherwise @@ -472,7 +448,7 @@ def _test_disallows_empty_jars(name): def _test_disallows_empty_jars_impl(env, target): env.expect.that_target(target).failures().contains_predicate( - matching.str_matches("empty java_import.jars is no longer supported"), + matching.str_matches("empty java_import.jars is not supported"), ) def _test_disallows_files_in_exports(name): @@ -964,7 +940,6 @@ def java_import_tests(name): _test_transitive_dependencies, _test_exposes_java_provider, _test_jars_allowed_in_srcjar, - _test_permits_empty_jars_with_flag, _test_disallows_empty_jars, _test_disallows_files_in_exports, _test_disallows_arbitrary_files, From 7a3d650d761bd4e4414a568af09807f94e2d486c Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 14 May 2025 01:19:06 -0700 Subject: [PATCH 279/465] Clarify `java_plugin` documentation (ignore-relnotes) PiperOrigin-RevId: 758566433 Change-Id: I942d1109e0fc75b56e951a0a5b02127eca526190 --- java/bazel/rules/bazel_java_plugin.bzl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/java/bazel/rules/bazel_java_plugin.bzl b/java/bazel/rules/bazel_java_plugin.bzl index d6fc7edc..cbd7eeca 100644 --- a/java/bazel/rules/bazel_java_plugin.bzl +++ b/java/bazel/rules/bazel_java_plugin.bzl @@ -134,10 +134,10 @@ java_plugin = rule(

  • libname.jar: A Java archive.
  • -

    - Arguments are identical to java_library, except - for the addition of the processor_class argument. -

    +

    Arguments are a subset of (and with identical semantics to) those of +java_library(), +except for the addition of the processor_class and +generates_api arguments.

    """, attrs = merge_attrs( JAVA_PLUGIN_ATTRS, From 94426d158cdc6fdfcba524ff042bf8ffddf9514a Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 15 May 2025 04:54:29 -0700 Subject: [PATCH 280/465] Fix case handling of `java_common.compile(strict_deps)` PiperOrigin-RevId: 759094738 Change-Id: Id076b9ab98e5b8cd922ff9f3dfe00d46bd4e9ec9 --- java/private/java_common_internal.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/private/java_common_internal.bzl b/java/private/java_common_internal.bzl index d7402555..466f59ab 100644 --- a/java/private/java_common_internal.bzl +++ b/java/private/java_common_internal.bzl @@ -177,7 +177,7 @@ def compile( has_sources = source_files or source_jars has_resources = resources or resource_jars - is_strict_mode = strict_deps != "OFF" + is_strict_mode = strict_deps.upper() != "OFF" classpath_mode = ctx.fragments.java.reduce_java_classpath() direct_jars = depset() From 4ce6ca94017971b4877a08fe178b005972d6a15b Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 19 May 2025 01:42:17 -0700 Subject: [PATCH 281/465] Validate `java_common.compile(strict_deps)` in Starlark Before this, passing an invalid value would crash Bazel PiperOrigin-RevId: 760518664 Change-Id: If482d29e36b40529a9f2c0be523944163408327f --- java/private/java_common_internal.bzl | 15 +++++- test/java/common/java_common_tests.bzl | 53 +++++++++++++++++++ .../rules/custom_library_with_strict_deps.bzl | 23 ++++++++ 3 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 test/java/testutil/rules/custom_library_with_strict_deps.bzl diff --git a/java/private/java_common_internal.bzl b/java/private/java_common_internal.bzl index 466f59ab..4a76df09 100644 --- a/java/private/java_common_internal.bzl +++ b/java/private/java_common_internal.bzl @@ -29,6 +29,14 @@ load(":native.bzl", "get_internal_java_common") # copybara: default multiline visibility +_STRICT_DEPS_VALUES = [ + "OFF", # Silently allow referencing transitive dependencies. + "WARN", # Warn about transitive dependencies being used directly. + "ERROR", # Fail the build when transitive dependencies are used directly. + "STRICT", # Transition to strict by default. + "DEFAULT", # When no flag value is specified on the command line. +] + def compile( ctx, output, @@ -117,6 +125,11 @@ def compile( get_internal_java_common().check_provider_instances([java_toolchain], "java_toolchain", JavaToolchainInfo) get_internal_java_common().check_provider_instances(plugins, "plugins", JavaPluginInfo) + # normalize and validate strict_deps + strict_deps = (strict_deps or "default").upper() + if strict_deps not in _STRICT_DEPS_VALUES: + fail("Got an invalid value for strict_deps:", strict_deps, "must be one of:", _STRICT_DEPS_VALUES) + plugin_info = merge_plugin_info_without_outputs(plugins + deps) all_javac_opts = [] # [depset[str]] @@ -177,7 +190,7 @@ def compile( has_sources = source_files or source_jars has_resources = resources or resource_jars - is_strict_mode = strict_deps.upper() != "OFF" + is_strict_mode = strict_deps != "OFF" classpath_mode = ctx.fragments.java.reduce_java_classpath() direct_jars = depset() diff --git a/test/java/common/java_common_tests.bzl b/test/java/common/java_common_tests.bzl index b569b680..d4528df8 100644 --- a/test/java/common/java_common_tests.bzl +++ b/test/java/common/java_common_tests.bzl @@ -19,6 +19,7 @@ load("//test/java/testutil:rules/custom_library_with_custom_output_source_jar.bz load("//test/java/testutil:rules/custom_library_with_exports.bzl", "custom_library_with_exports") load("//test/java/testutil:rules/custom_library_with_named_outputs.bzl", "custom_library_with_named_outputs") load("//test/java/testutil:rules/custom_library_with_sourcepaths.bzl", "custom_library_with_sourcepaths") +load("//test/java/testutil:rules/custom_library_with_strict_deps.bzl", "custom_library_with_strict_deps") load("//test/java/testutil:rules/custom_library_with_wrong_plugins_type.bzl", "custom_library_with_wrong_plugins_type") def _test_compile_default_values(name): @@ -743,6 +744,56 @@ def _test_compile_neverlink_impl(env, target): "somedep.jar", ]).in_order() +def _test_compile_strict_deps_case_sensitivity(name): + util.helper_target( + custom_library_with_strict_deps, + name = name + "/enabled", + strict_deps = "error", + ) + util.helper_target( + custom_library_with_strict_deps, + name = name + "/disabled", + strict_deps = "off", + ) + + analysis_test( + name = name, + impl = _test_compile_strict_deps_case_sensitivity_impl, + targets = { + "enabled": name + "/enabled", + "disabled": name + "/disabled", + }, + ) + +def _test_compile_strict_deps_case_sensitivity_impl(env, targets): + env.expect.that_target(targets.enabled).action_named("Javac").contains_flag_values( + [("--strict_java_deps", "ERROR")], + ) + env.expect.that_target(targets.disabled).action_named("Javac").not_contains_arg( + "--strict_java_deps", + ) + +def _test_compile_strict_deps_enum(name): + util.helper_target( + custom_library_with_strict_deps, + name = name + "/custom", + strict_deps = "foo", + ) + + analysis_test( + name = name, + impl = _test_compile_strict_deps_enum_impl, + target = name + "/custom", + expect_failure = True, + # This is a crash in earlier Bazel versions (i.e. native rules) + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _test_compile_strict_deps_enum_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("invalid value for strict_deps: FOO"), + ) + def java_common_tests(name): test_suite( name = name, @@ -770,5 +821,7 @@ def java_common_tests(name): _test_compile_custom_output_source_jar, _test_compile_additional_inputs_and_outputs, _test_compile_neverlink, + _test_compile_strict_deps_case_sensitivity, + _test_compile_strict_deps_enum, ], ) diff --git a/test/java/testutil/rules/custom_library_with_strict_deps.bzl b/test/java/testutil/rules/custom_library_with_strict_deps.bzl new file mode 100644 index 00000000..d2c931e4 --- /dev/null +++ b/test/java/testutil/rules/custom_library_with_strict_deps.bzl @@ -0,0 +1,23 @@ +"""Helper rule for testing compilation with default parameter values""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_semantics.bzl", "semantics") + +def _custom_library_impl(ctx): + output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") + compilation_provider = java_common.compile( + ctx, + output = output_jar, + strict_deps = ctx.attr.strict_deps, + java_toolchain = semantics.find_java_toolchain(ctx), + ) + return [DefaultInfo(files = depset([output_jar])), compilation_provider] + +custom_library_with_strict_deps = rule( + _custom_library_impl, + attrs = { + "strict_deps": attr.string(), + }, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], + fragments = ["java"], +) From 042e9a629ca2cab8b13539aeaee055a9e7394fd8 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 22 May 2025 04:10:58 -0700 Subject: [PATCH 282/465] Use `@platforms//host` instead of `@local_config_platform` The latter is deprecated (currently aliases to the former) and will be removed in Bazel 9. See similar unknown commit for rules_cc. PiperOrigin-RevId: 761901757 Change-Id: I133adb35ebb5f388ca02e61409267820db804763 --- toolchains/local_java_repository.bzl | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/toolchains/local_java_repository.bzl b/toolchains/local_java_repository.bzl index 627f8ab8..075f54d6 100644 --- a/toolchains/local_java_repository.bzl +++ b/toolchains/local_java_repository.bzl @@ -235,10 +235,18 @@ local_java_runtime( ) """ % (local_java_runtime_name, runtime_name, java_home, version) + bazel = native.bazel_version + if not bazel or bazel >= "7": + # Bazel 7+ uses @platforms//host for the host platform. + load_host_constraints = 'load("@platforms//host:constraints.bzl", "HOST_CONSTRAINTS")\n' + else: + # Bazel 6 uses @local_config_platform instead, but it's being removed in Bazel 9. + load_host_constraints = 'load("@local_config_platform//:constraints.bzl", "HOST_CONSTRAINTS")\n' + repository_ctx.file( "BUILD.bazel", 'load("@rules_java//toolchains:local_java_repository.bzl", "local_java_runtime")\n' + - 'load("@local_config_platform//:constraints.bzl", "HOST_CONSTRAINTS")\n' + + load_host_constraints + build_file + local_java_runtime_macro, ) From 808f8496a00a153840025a549b51d99bba874565 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Fri, 23 May 2025 01:02:46 -0700 Subject: [PATCH 283/465] Use the `launcher_maker` toolchain if available (#294) This avoids an unnecessary dependency on a C++ toolchain matching the target platform when not building for Windows. Also fix the configuration of the launcher, which should be built for the target platform. Closes #294 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/294 from fmeum:cross-compile-to-unix 13f097a3c541f603e091c139a4543b632382c9aa PiperOrigin-RevId: 762307907 Change-Id: I1e172a81bd198b02032a705c459ead48b0012aea --- .bazelci/presubmit.yml | 38 ++++++++------ MODULE.bazel | 9 +--- WORKSPACE | 15 ++---- distro/relnotes.bzl | 13 +++++ java/bazel/rules/bazel_java_binary.bzl | 21 ++++++-- java/rules_java_deps.bzl | 10 ++++ test/java/bazel/BUILD.bazel | 0 test/java/bazel/rules/BUILD.bazel | 3 ++ test/java/bazel/rules/java_binary_tests.bzl | 55 +++++++++++++++++++++ test/repo/WORKSPACE | 4 ++ 10 files changed, 132 insertions(+), 36 deletions(-) create mode 100644 test/java/bazel/BUILD.bazel create mode 100644 test/java/bazel/rules/BUILD.bazel create mode 100644 test/java/bazel/rules/java_binary_tests.bzl diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 6dc8cf3e..18088a21 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -42,16 +42,33 @@ test_target_integration: &test_target_integration flags_workspace_integration: &flags_workspace_integration - "--noenable_bzlmod" - "--enable_workspace" + # TODO(hvd): remove after Bazel 8.3.0 + - "--repositories_without_autoloads=bazel_features_version,bazel_features_globals" buildifier: latest matrix: all_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"] - integration_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"] bazel: ["7.6.1", "8.2.1", "last_green"] # Bazel 6 tested separately, needs different flags - modern_bazel: ["8.2.1", "last_green"] # Fully supported Bazel versions + modern_bazel: ["last_green"] # Fully supported Bazel versions tasks: +# Bazel 9+ + build_and_test: + name: "Bazel {modern_bazel}" + bazel: ${{ modern_bazel }} + platform: ${{ all_platforms }} + build_targets: *build_targets + test_targets: *test_targets +# Bazel 8.x + build_and_test_bazel8: + name: "Bazel 8.2.1" + bazel: "8.2.1" + platform: ${{ all_platforms }} + build_targets: *build_targets + test_targets: *test_targets + test_flags: + - "--test_tag_filters=-min_bazel_9" # Bazel 7.x build_and_test_bazel7: name: "Bazel 7.6.1" @@ -60,14 +77,7 @@ tasks: build_targets: *build_targets test_targets: *test_targets test_flags: - - "--test_tag_filters=-min_bazel_8" -# Bazel 8+ - build_and_test: - name: "Bazel {modern_bazel}" - bazel: ${{ modern_bazel }} - platform: ${{ all_platforms }} - build_targets: *build_targets - test_targets: *test_targets + - "--test_tag_filters=-min_bazel_8,-min_bazel_9" # Bazel 6.x build_and_test_bazel6: name: "Bazel 6.5.0" @@ -76,11 +86,11 @@ tasks: build_targets: *build_targets_bazel6 test_targets: *test_targets_bazel6 test_flags: - - "--test_tag_filters=-min_bazel_7,-min_bazel_8" + - "--test_tag_filters=-min_bazel_7,-min_bazel_8,-min_bazel_9" ubuntu2004_integration_bazel6: name: "Integration w/ Bazel 6.5.0" bazel: 6.5.0 - platform: ${{ integration_platforms }} + platform: ${{ all_platforms }} working_directory: "test/repo" shell_commands: - sh setup.sh @@ -93,7 +103,7 @@ tasks: integration_build_and_test: name: "Integration w/ Bazel {bazel}" bazel: ${{ bazel }} - platform: ${{ integration_platforms }} + platform: ${{ all_platforms }} working_directory: "test/repo" shell_commands: - sh setup.sh @@ -104,7 +114,7 @@ tasks: integration_build_and_test_workspace: name: "Integration (WORKSPACE) w/ Bazel {bazel}" bazel: ${{ bazel }} - platform: ${{ integration_platforms }} + platform: ${{ all_platforms }} working_directory: "test/repo" shell_commands: - sh setup.sh diff --git a/MODULE.bazel b/MODULE.bazel index 4b700447..bcfd03a5 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -7,14 +7,7 @@ module( bazel_dep(name = "platforms", version = "0.0.11") bazel_dep(name = "rules_cc", version = "0.0.15") -bazel_dep(name = "bazel_features", version = "1.28.0") -archive_override( - module_name = "bazel_features", - integrity = "sha256-SOPLvKDy+RN7GHKN8eFjQ+58Wx4Isj+vcXoUluBqxLo=", - strip_prefix = "bazel_features-59915eb2ca215c7b2266c83c49bb7522a5b6737f", - urls = ["https://github.com/bazel-contrib/bazel_features/archive/59915eb2ca215c7b2266c83c49bb7522a5b6737f.zip"], -) - +bazel_dep(name = "bazel_features", version = "1.30.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") bazel_dep(name = "protobuf", version = "27.0", repo_name = "com_google_protobuf") bazel_dep(name = "zlib", version = "1.3.1.bcr.5") diff --git a/WORKSPACE b/WORKSPACE index 6b8beb60..acd7cae0 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -41,6 +41,10 @@ load("//java:rules_java_deps.bzl", "rules_java_dependencies") rules_java_dependencies() +load("@bazel_features//:deps.bzl", "bazel_features_deps") + +bazel_features_deps() + load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_bazel_features") # buildifier: disable=bzl-visibility proto_bazel_features(name = "proto_bazel_features") @@ -63,14 +67,3 @@ http_archive( load("//test:repositories.bzl", "test_repositories") test_repositories() - -http_archive( - name = "bazel_features", - sha256 = "48e3cbbca0f2f9137b18728df1e16343ee7c5b1e08b23faf717a1496e06ac4ba", - strip_prefix = "bazel_features-59915eb2ca215c7b2266c83c49bb7522a5b6737f", - url = "https://github.com/bazel-contrib/bazel_features/archive/59915eb2ca215c7b2266c83c49bb7522a5b6737f.zip", -) - -load("@bazel_features//:deps.bzl", "bazel_features_deps") - -bazel_features_deps() diff --git a/distro/relnotes.bzl b/distro/relnotes.bzl index 5641bf7b..ce04d501 100644 --- a/distro/relnotes.bzl +++ b/distro/relnotes.bzl @@ -18,6 +18,16 @@ bazel_dep(name = "rules_java", version = "{VERSION}") ~~~ **WORKSPACE setup** + +With Bazel 8.0.0 and before 8.3.0, add the following to your `.bazelrc` file: + +~~~ +# https://github.com/bazelbuild/bazel/pull/26119 +common --repositories_without_autoloads=bazel_features_version,bazel_features_globals +~~~ + +In all cases, add the following to your `WORKSPACE` file: + ~~~ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( @@ -31,6 +41,9 @@ http_archive( load("@rules_java//java:rules_java_deps.bzl", "rules_java_dependencies") rules_java_dependencies() +load("@bazel_features//:deps.bzl", "bazel_features_deps") +bazel_features_deps() + # note that the following line is what is minimally required from protobuf for the java rules # consider using the protobuf_deps() public API from @com_google_protobuf//:protobuf_deps.bzl load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_bazel_features") # buildifier: disable=bzl-visibility diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl index def12d14..cbbe0de8 100644 --- a/java/bazel/rules/bazel_java_binary.bzl +++ b/java/bazel/rules/bazel_java_binary.bzl @@ -13,6 +13,7 @@ # limitations under the License. """Bazel java_binary rule""" +load("@bazel_features//:features.bzl", "bazel_features") load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc:find_cc_toolchain.bzl", "use_cc_toolchain") load("//java/common:java_semantics.bzl", "semantics") @@ -202,6 +203,14 @@ def _get_executable(ctx): return ctx.actions.declare_file(executable_name) +_LAUNCHER_MAKER_TOOLCHAIN_TYPE = "@bazel_tools//tools/launcher:launcher_maker_toolchain_type" +_LAUNCHER_MAKER_TOOLCHAIN = config_common.toolchain_type(_LAUNCHER_MAKER_TOOLCHAIN_TYPE, mandatory = True) + +def _find_launcher_maker(ctx): + if bazel_features.rules._has_launcher_maker_toolchain: + return ctx.toolchains[_LAUNCHER_MAKER_TOOLCHAIN_TYPE].binary + return ctx.executable._windows_launcher_maker + def _create_stub(ctx, java_attrs, launcher, executable, jvm_flags, main_class, coverage_main_class): java_runtime_toolchain = semantics.find_java_runtime_toolchain(ctx) java_executable = helper.get_java_executable(ctx, java_runtime_toolchain, launcher) @@ -282,11 +291,13 @@ def _create_windows_exe_launcher(ctx, java_executable, classpath, main_class, jv # TODO(b/295221112): Change to use the "launcher" attribute (only windows use a fixed _launcher attribute) launcher_artifact = ctx.executable._launcher ctx.actions.run( - executable = ctx.executable._windows_launcher_maker, + executable = _find_launcher_maker(ctx), inputs = [launcher_artifact], outputs = [executable], arguments = [launcher_artifact.path, launch_info, executable.path], use_default_shell_env = True, + toolchain = _LAUNCHER_MAKER_TOOLCHAIN_TYPE if bazel_features.rules._has_launcher_maker_toolchain else None, + mnemonic = "JavaLauncherMaker", ) return executable @@ -308,6 +319,8 @@ def make_binary_rule(implementation, *, doc, attrs, executable = False, test = F provides = [JavaInfo], toolchains = [semantics.JAVA_TOOLCHAIN] + use_cc_toolchain() + ( [semantics.JAVA_RUNTIME_TOOLCHAIN] if executable or test else [] + ) + ( + [_LAUNCHER_MAKER_TOOLCHAIN] if bazel_features.rules._has_launcher_maker_toolchain else [] ), # TODO(hvd): replace with filegroups? outputs = { @@ -340,16 +353,18 @@ logic as the Java package of source files. For example, a source file at ), "_test_support": attr.label(default = _compute_test_support), "_launcher": attr.label( - cfg = "exec", + cfg = "target", executable = True, default = "@bazel_tools//tools/launcher:launcher", ), + }, + { "_windows_launcher_maker": attr.label( default = "@bazel_tools//tools/launcher:launcher_maker", cfg = "exec", executable = True, ), - }, + } if not bazel_features.rules._has_launcher_maker_toolchain else {}, ) def make_java_binary(executable): diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl index 0c96d8ca..b32edd24 100644 --- a/java/rules_java_deps.bzl +++ b/java/rules_java_deps.bzl @@ -210,6 +210,15 @@ def rules_license_repo(): ], ) +def bazel_features_repo(): + maybe( + http_archive, + name = "bazel_features", + sha256 = "a660027f5a87f13224ab54b8dc6e191693c554f2692fcca46e8e29ee7dabc43b", + strip_prefix = "bazel_features-1.30.0", + url = "https://github.com/bazel-contrib/bazel_features/releases/download/v1.30.0/bazel_features-v1.30.0.tar.gz", + ) + def rules_java_dependencies(): """An utility method to load non-toolchain dependencies of rules_java. @@ -223,3 +232,4 @@ def rules_java_dependencies(): zlib_repo() absl_repo() rules_license_repo() + bazel_features_repo() diff --git a/test/java/bazel/BUILD.bazel b/test/java/bazel/BUILD.bazel new file mode 100644 index 00000000..e69de29b diff --git a/test/java/bazel/rules/BUILD.bazel b/test/java/bazel/rules/BUILD.bazel new file mode 100644 index 00000000..3bf8f436 --- /dev/null +++ b/test/java/bazel/rules/BUILD.bazel @@ -0,0 +1,3 @@ +load(":java_binary_tests.bzl", "java_binary_tests") + +java_binary_tests(name = "java_binary_tests") diff --git a/test/java/bazel/rules/java_binary_tests.bzl b/test/java/bazel/rules/java_binary_tests.bzl new file mode 100644 index 00000000..32036d82 --- /dev/null +++ b/test/java/bazel/rules/java_binary_tests.bzl @@ -0,0 +1,55 @@ +"""Tests for the Bazel java_binary rule""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_binary.bzl", "java_binary") + +def _test_java_binary_cross_compilation_to_unix(name): + # A Unix platform that: + # - has a JDK + # - does not require a launcher + # - is not supported by the default C++ toolchain + util.helper_target( + native.platform, + name = name + "/platform", + constraint_values = [ + "@platforms//os:linux", + "@platforms//cpu:s390x", + ], + ) + + util.helper_target( + java_binary, + name = name + "/bin", + srcs = ["java/C.java"], + main_class = "C", + ) + + analysis_test( + name = name, + impl = _test_java_binary_cross_compilation_to_unix_impl, + target = name + "/bin", + config_settings = { + "//command_line_option:platforms": [Label(name + "/platform")], + }, + # Requires the launcher_maker toolchain. + attr_values = {"tags": ["min_bazel_9"]}, + ) + +def _test_java_binary_cross_compilation_to_unix_impl(env, target): + # The main assertion is that analysis succeeds, but verify the absence of a + # binary launcher for good measure. We do this by checking that the output + # executable is the stub script, and not a bespoke launcher + executable = target[DefaultInfo].files_to_run.executable.short_path + assert_action = env.expect.that_target(target).action_generating(executable) + assert_action.mnemonic().equals("TemplateExpand") + assert_action.substitutions().keys().contains("%jvm_flags%") + assert_action.inputs().contains_exactly(["java/bazel/rules/java_stub_template.txt"]) + +def java_binary_tests(name): + test_suite( + name = name, + tests = [ + _test_java_binary_cross_compilation_to_unix, + ], + ) diff --git a/test/repo/WORKSPACE b/test/repo/WORKSPACE index eb680856..c272975e 100644 --- a/test/repo/WORKSPACE +++ b/test/repo/WORKSPACE @@ -9,6 +9,10 @@ load("@rules_java//java:rules_java_deps.bzl", "rules_java_dependencies") rules_java_dependencies() +load("@bazel_features//:deps.bzl", "bazel_features_deps") + +bazel_features_deps() + load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_bazel_features") # buildifier: disable=bzl-visibility proto_bazel_features(name = "proto_bazel_features") From 6915f89962442c5def663f559b75a4a8c2377b1b Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 23 May 2025 02:31:03 -0700 Subject: [PATCH 284/465] Release `rules_java` `8.12.0` (ignore-relnotes) PiperOrigin-RevId: 762333889 Change-Id: I1a925f0d4ad13179b207338409c81f8eaab3072b --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index bcfd03a5..9a1562e9 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "8.11.0", + version = "8.12.0", bazel_compatibility = [">=6.4.0"], compatibility_level = 1, ) From b07c3191fa8a0fd95bff87ab035975edfe5753a8 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 23 May 2025 03:14:18 -0700 Subject: [PATCH 285/465] Use Rocky Linux instead of CentOS for rules_java BCR presubmits See https://github.com/bazelbuild/continuous-integration/issues/2272 (ignore-relnotes) PiperOrigin-RevId: 762345962 Change-Id: I68a6e1805418144d409d2afd1a51d77f37df40fe --- .bcr/presubmit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.bcr/presubmit.yml b/.bcr/presubmit.yml index c81cf084..26dad0fe 100644 --- a/.bcr/presubmit.yml +++ b/.bcr/presubmit.yml @@ -1,6 +1,6 @@ matrix: platform: - - centos7 + - rockylinux8 - debian10 - macos - ubuntu2004 From 0af04abb2e8d0148ab05644223f3a3191671ecbb Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 26 May 2025 08:06:52 -0700 Subject: [PATCH 286/465] Replace asserts on library_identifier with static_library library_identifier is private and will be removed. Works towards starlarkifying LibraryToLink structure. PiperOrigin-RevId: 763431970 Change-Id: I5536fc0c5502674967b8b4c64278d991aa6fbf3a --- java/testutil.bzl | 6 +++--- test/java/common/java_info_tests.bzl | 18 +++++++++--------- test/java/common/rules/java_library_tests.bzl | 6 +++--- test/java/testutil/cc_info_subject.bzl | 10 +++++----- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/java/testutil.bzl b/java/testutil.bzl index 26823ba8..6207583b 100644 --- a/java/testutil.bzl +++ b/java/testutil.bzl @@ -7,10 +7,10 @@ def _cc_info_transitive_native_libraries(cc_info): return cc_info.transitive_native_libraries() -def _cc_library_to_link_identifier(library_to_link): - return library_to_link.library_identifier() +def _cc_library_to_link_static_library(library_to_link): + return library_to_link.static_library or library_to_link.pic_static_library testutil = struct( cc_info_transitive_native_libraries = _cc_info_transitive_native_libraries, - cc_library_to_link_identifier = _cc_library_to_link_identifier, + cc_library_to_link_static_library = _cc_library_to_link_static_library, ) diff --git a/test/java/common/java_info_tests.bzl b/test/java/common/java_info_tests.bzl index 5e95187f..5d3c6663 100644 --- a/test/java/common/java_info_tests.bzl +++ b/test/java/common/java_info_tests.bzl @@ -175,7 +175,7 @@ def _with_native_libraries_test(name): def _with_native_libraries_test_impl(env, target): assert_native_libs = java_info_subject.from_target(env, target).transitive_native_libraries() - assert_native_libs.identifiers().contains_exactly_predicates([matching.str_endswith("my_cc_lib_direct")]) + assert_native_libs.static_libraries().contains_exactly_predicates([matching.str_matches("*my_cc_lib_direct*")]) def _with_deps_and_neverlink_test(name): target_name = name + "/my_starlark_rule" @@ -1136,10 +1136,10 @@ def _transitive_native_libraries_test(name): def _transitive_native_libraries_test_impl(env, target): assert_transitive_native_libraries = java_info_subject.from_target(env, target).transitive_native_libraries() - assert_transitive_native_libraries.identifiers().contains_exactly_predicates([ - matching.str_endswith("my_cc_lib_a.so"), - matching.str_endswith("my_cc_lib_b.so"), - matching.str_endswith("my_cc_lib_c.so"), + assert_transitive_native_libraries.static_libraries().contains_exactly_predicates([ + matching.str_matches("*my_cc_lib_a.so*"), + matching.str_matches("*my_cc_lib_b.so*"), + matching.str_matches("*my_cc_lib_c.so*"), ]) def _native_libraries_propagation_test(name): @@ -1197,10 +1197,10 @@ def _native_libraries_propagation_test(name): def _native_libraries_propagation_test_impl(env, target): assert_transitive_native_libraries = java_info_subject.from_target(env, target).transitive_native_libraries() - assert_transitive_native_libraries.identifiers().contains_exactly_predicates([ - matching.str_endswith("native_rdeps1.so"), - matching.str_endswith("native_exports1.so"), - matching.str_endswith("native_deps1.so"), + assert_transitive_native_libraries.static_libraries().contains_exactly_predicates([ + matching.str_matches("*native_rdeps1.so*"), + matching.str_matches("*native_exports1.so*"), + matching.str_matches("*native_deps1.so*"), ]).in_order() def _annotation_processing_test(name): diff --git a/test/java/common/rules/java_library_tests.bzl b/test/java/common/rules/java_library_tests.bzl index 4dca71f4..58a282f9 100644 --- a/test/java/common/rules/java_library_tests.bzl +++ b/test/java/common/rules/java_library_tests.bzl @@ -273,9 +273,9 @@ def _test_propagates_direct_native_libraries(name): def _test_propagates_direct_native_libraries_impl(env, target): assert_transitive_native_libraries = java_info_subject.from_target(env, target).transitive_native_libraries() - assert_transitive_native_libraries.identifiers().contains_exactly_predicates([ - matching.str_endswith("native"), - matching.str_endswith("ccl"), + assert_transitive_native_libraries.static_libraries().contains_exactly_predicates([ + matching.str_matches("*native*"), + matching.str_matches("*ccl*"), ]).in_order() def _test_exposes_native_library_info(name): diff --git a/test/java/testutil/cc_info_subject.bzl b/test/java/testutil/cc_info_subject.bzl index c3306f68..c123c3d8 100644 --- a/test/java/testutil/cc_info_subject.bzl +++ b/test/java/testutil/cc_info_subject.bzl @@ -60,7 +60,7 @@ def _new_cc_info_libraries_to_link_subject(libraries_to_link, meta): meta = meta, ) public = struct( - identifiers = lambda: _new_library_to_link_identifiers_subject(self.actual, self.meta), + static_libraries = lambda: _new_library_to_link_static_libraries_subject(self.actual, self.meta), singleton = lambda: _new_library_to_link_subject(_get_singleton(self.actual), self.meta.derive("[0]")), ) return public @@ -71,11 +71,11 @@ def _new_library_to_link_subject(library_to_link, meta): ) return public -def _new_library_to_link_identifiers_subject(libraries_to_link, meta): +def _new_library_to_link_static_libraries_subject(libraries_to_link, meta): self = subjects.collection( - [testutil.cc_library_to_link_identifier(lib) for lib in libraries_to_link], - meta = meta.derive("library_identifier()"), - ) + [testutil.cc_library_to_link_static_library(lib) for lib in libraries_to_link], + meta = meta.derive("static_library()"), + ).transform(desc = "basename", map_each = lambda file: file.basename) public = struct( contains_exactly = lambda expected: self.contains_exactly([meta.format_str(e) for e in expected]), contains_exactly_predicates = lambda expected: self.contains_exactly_predicates(expected), From 899c2b75bdce62dbec082a3ad664f9f0b5f6ede9 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Tue, 27 May 2025 12:19:26 -0700 Subject: [PATCH 287/465] Improve the error message for no matching bootclasspath (#296) Closes #296 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/296 from fmeum:patch-3 6579d5119b6bb6fbd79d123718dc53b8b9bd9711 PiperOrigin-RevId: 763898415 Change-Id: I3a4a07d682e1e1b450b433931f3366bbe3051e3a --- toolchains/bootclasspath.bzl | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/toolchains/bootclasspath.bzl b/toolchains/bootclasspath.bzl index 1a2f5536..d89aa171 100644 --- a/toolchains/bootclasspath.bzl +++ b/toolchains/bootclasspath.bzl @@ -165,10 +165,12 @@ def _bootclasspath_impl(ctx): tool_prefix = "tool_" if is_exec else "" fail(""" No Java runtime found to extract the bootclasspath from for --{tool_prefix}java_language_version={language_version} and --{tool_prefix}java_runtime_version={runtime_version}. -You can: +The bootclasspath provides the particular version of the Java standard library to compile against. +You can do one of the following: - * register a Java runtime with name "{bootstrap_runtime_version}" to provide the bootclasspath or - * set --java_language_version to the Java version of an available runtime. + * register a Java runtime with name "{bootstrap_runtime_version}" to provide the bootclasspath + * set --java_language_version=N for an available runtime "{runtime_version}_N" + * remove the suffix from your runtime's name to use it as the bootclasspath Rerun with --toolchain_resolution_debug='@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type' to see more details about toolchain resolution. """.format( From ae8a5b22648f3e6c8a4bc58ec0bb9f7c3f1a9668 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 28 May 2025 19:09:52 -0700 Subject: [PATCH 288/465] Initial support for header compilation direct deps This adds a new output to header compilation actions which is used as the classpath for downstream header compilations, instead of using the same output for downstream header and regular compilations. Using a separate output allows trimming information that isn't needed by header compilation, but is required for regular compilation, including methods. This results in a smaller cache key for header compilation actions. PiperOrigin-RevId: 764512852 Change-Id: I4895e47f3418e9cbf602edd11fde38de5f3e32ca --- java/private/java_common_internal.bzl | 25 ++++++++++++++++++++ java/private/java_info.bzl | 34 +++++++++++++++++++++++++-- 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/java/private/java_common_internal.bzl b/java/private/java_common_internal.bzl index 4a76df09..54f0c7bd 100644 --- a/java/private/java_common_internal.bzl +++ b/java/private/java_common_internal.bzl @@ -196,6 +196,14 @@ def compile( direct_jars = depset() if is_strict_mode: direct_jars = depset(order = "preorder", transitive = [dep.compile_jars for dep in deps]) + + header_compilation_direct_deps = depset() + if is_strict_mode: + header_compilation_direct_deps = depset( + order = "preorder", + transitive = [dep.header_compilation_direct_deps for dep in deps], + ) + compilation_classpath = depset( order = "preorder", transitive = [direct_jars] + [dep.transitive_compile_time_jars for dep in deps], @@ -207,12 +215,25 @@ def compile( # create compile time jar action if not has_sources: compile_jar = None + header_compilation_jar = None compile_deps_proto = None elif not enable_compile_jar_action: compile_jar = output + header_compilation_jar = compile_jar compile_deps_proto = None elif _should_use_header_compilation(ctx, java_toolchain): compile_jar = helper.derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jar") + + # TODO: b/417791104 - remove hasattr check once Bazel 8.3.0 is released + if hasattr(ctx.fragments.java, "use_header_compilation_direct_deps") and ctx.fragments.java.use_header_compilation_direct_deps(): + header_compilation_jar = helper.derive_output_file(ctx, output, name_suffix = "-tjar", extension = "jar") + header_compilation_extra_args = { + "header_compilation_jar": header_compilation_jar, + "header_compilation_direct_deps": header_compilation_direct_deps, + } + else: + header_compilation_jar = None + header_compilation_extra_args = {} compile_deps_proto = helper.derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jdeps") get_internal_java_common().create_header_compilation_action( ctx, @@ -232,6 +253,7 @@ def compile( injecting_rule_kind, enable_direct_classpath, annotation_processor_additional_inputs, + **header_compilation_extra_args ) elif ctx.fragments.java.use_ijars(): compile_jar = run_ijar( @@ -241,9 +263,11 @@ def compile( target_label = ctx.label, injecting_rule_kind = injecting_rule_kind, ) + header_compilation_jar = compile_jar compile_deps_proto = None else: compile_jar = output + header_compilation_jar = compile_jar compile_deps_proto = None native_headers_jar = helper.derive_output_file(ctx, output, name_suffix = "-native-header") @@ -323,6 +347,7 @@ def compile( return java_info_for_compilation( output_jar = output, compile_jar = compile_jar, + header_compilation_jar = header_compilation_jar, source_jar = output_source_jar, generated_class_jar = generated_class_jar, generated_source_jar = generated_source_jar, diff --git a/java/private/java_info.bzl b/java/private/java_info.bzl index 083eef09..de1111b7 100644 --- a/java/private/java_info.bzl +++ b/java/private/java_info.bzl @@ -28,6 +28,7 @@ _JavaOutputInfo = provider( fields = { "class_jar": "(File) A classes jar file.", "compile_jar": "(File) An interface jar file.", + "header_compilation_jar": "(File) An header compilation jar file.", "ijar": "Deprecated: Please use compile_jar.", "compile_jdeps": "(File) Compile time dependencies information (deps.proto file).", "generated_class_jar": "(File) A jar containing classes generated via annotation processing.", @@ -114,6 +115,7 @@ def merge( transitive_runtime_jars = [] # [depset[File]] transitive_compile_time_jars = [] # [depset[File]] compile_jars = [] # [depset[File]] + header_compilation_direct_deps = [] # [depset[File]] full_compile_jars = [] # [depset[File]] _transitive_full_compile_time_jars = [] # [depset[File]] _compile_time_java_dependencies = [] # [depset[File]] @@ -131,6 +133,7 @@ def merge( transitive_runtime_jars.append(p.transitive_runtime_jars) transitive_compile_time_jars.append(p.transitive_compile_time_jars) compile_jars.append(p.compile_jars) + header_compilation_direct_deps.append(p.header_compilation_direct_deps) full_compile_jars.append(p.full_compile_jars) _transitive_full_compile_time_jars.append(p._transitive_full_compile_time_jars) _compile_time_java_dependencies.append(p._compile_time_java_dependencies) @@ -148,6 +151,7 @@ def merge( "transitive_runtime_jars": transitive_runtime_jars, "transitive_compile_time_jars": transitive_compile_time_jars, "compile_jars": depset(order = "preorder", transitive = compile_jars), + "header_compilation_direct_deps": depset(order = "preorder", transitive = header_compilation_direct_deps), "full_compile_jars": depset(order = "preorder", transitive = full_compile_jars), "_transitive_full_compile_time_jars": depset(order = "preorder", transitive = _transitive_full_compile_time_jars), "_compile_time_java_dependencies": depset(order = "preorder", transitive = _compile_time_java_dependencies), @@ -198,6 +202,7 @@ def to_java_binary_info(java_info, compilation_info): "transitive_runtime_jars": depset(), "transitive_compile_time_jars": depset(), "compile_jars": depset(), + "header_compilation_direct_deps": depset(), "full_compile_jars": depset(), "_transitive_full_compile_time_jars": depset(), "_compile_time_java_dependencies": depset(), @@ -220,6 +225,7 @@ def to_java_binary_info(java_info, compilation_info): java_outputs = [ _JavaOutputInfo( compile_jar = None, + header_compilation_jar = None, ijar = None, # deprecated compile_jdeps = None, class_jar = output.class_jar, @@ -253,6 +259,7 @@ def to_implicit_exportable(java_info, neverlink = False): "transitive_runtime_jars": depset() if neverlink else java_info.transitive_runtime_jars, "transitive_compile_time_jars": java_info.transitive_compile_time_jars, "compile_jars": java_info.compile_jars, + "header_compilation_direct_deps": java_info.header_compilation_direct_deps, "full_compile_jars": java_info.full_compile_jars, "_transitive_full_compile_time_jars": java_info._transitive_full_compile_time_jars, "_compile_time_java_dependencies": java_info._compile_time_java_dependencies, @@ -312,6 +319,7 @@ def make_non_strict(java_info): result.update( compile_jars = java_info.transitive_compile_time_jars, full_compile_jars = java_info._transitive_full_compile_time_jars, + header_compilation_direct_deps = java_info._transitive_full_compile_time_jars, ) # Omit jdeps, which aren't available transitively and aren't useful for reduced classpath @@ -411,12 +419,15 @@ def java_info_for_compilation( add_exports, add_opens, direct_runtime_jars, - compilation_info): + compilation_info, + header_compilation_jar): """Creates a JavaInfo instance represiting the result of java compilation. Args: output_jar: (File) The jar that was created as a result of a compilation. compile_jar: (File) A jar that is the compile-time dependency in lieu of `output_jar`. + header_compilation_jar: (File) A jar that is used for header compilation in lieu of + compile_jar or output_jar. source_jar: (File) The source jar that was used to create the output jar. generated_class_jar: (File) A jar file containing class files compiled from sources generated during annotation processing. @@ -466,6 +477,7 @@ def java_info_for_compilation( generated_source_jar, native_libraries, neverlink, + header_compilation_jar, ) # this differs ever so slightly from the usual JavaInfo in that direct_runtime_jars @@ -557,12 +569,18 @@ def _javainfo_init_base( generated_class_jar, generated_source_jar, native_libraries, - neverlink): + neverlink, + header_compilation_jar = None): _validate_provider_list(deps, "deps", JavaInfo) _validate_provider_list(runtime_deps, "runtime_deps", JavaInfo) _validate_provider_list(exports, "exports", JavaInfo) _validate_provider_list(native_libraries, "native_libraries", CcInfo) + # For clients that don't create a header_compilation_jar (e.g. java_import), fall back to using + # the compile jar. + if compile_jar and not header_compilation_jar: + header_compilation_jar = compile_jar + concatenated_deps = _compute_concatenated_deps(deps, runtime_deps, exports) source_jars = [source_jar] if source_jar else [] @@ -575,6 +593,7 @@ def _javainfo_init_base( java_outputs = [_JavaOutputInfo( class_jar = output_jar, compile_jar = compile_jar, + header_compilation_jar = header_compilation_jar, ijar = compile_jar, # deprecated compile_jdeps = compile_jdeps, generated_class_jar = generated_class_jar, @@ -592,6 +611,11 @@ def _javainfo_init_base( direct = [compile_jar] if compile_jar else [], transitive = [dep.compile_jars for dep in exports], ), + "header_compilation_direct_deps": depset( + order = "preorder", + direct = [header_compilation_jar] if header_compilation_jar else [], + transitive = [dep.header_compilation_direct_deps for dep in exports], + ), "full_compile_jars": depset( order = "preorder", direct = [output_jar], @@ -670,6 +694,7 @@ def _javainfo_init_base( def _javainfo_init( output_jar, compile_jar, + header_compilation_jar = None, source_jar = None, compile_jdeps = None, generated_class_jar = None, @@ -690,6 +715,8 @@ def _javainfo_init( Args: output_jar: (File) The jar that was created as a result of a compilation. compile_jar: (File) A jar that is the compile-time dependency in lieu of `output_jar`. + header_compilation_jar: (File) A jar that is used for header compilation in lieu of + compile_jar or output_jar. source_jar: (File) The source jar that was used to create the output jar. Optional. compile_jdeps: (File) jdeps information about compile time dependencies to be consumed by JavaCompileAction. This should be a binary proto encoded using the deps.proto protobuf @@ -739,6 +766,7 @@ def _javainfo_init( generated_source_jar, native_libraries, neverlink, + header_compilation_jar = header_compilation_jar, ) if neverlink: @@ -801,6 +829,8 @@ JavaInfo, _new_javainfo = provider( "compile_jars": """(depset[File]) The jars required directly at compile time. They can be interface jars (ijar or hjar), regular jars or both, depending on whether rule implementations chose to create interface jars or not.""", + "header_compilation_direct_deps": """(depset[File]) The header compilation jars required + directly at compile time.""", "full_compile_jars": """(depset[File]) The regular, full compile time Jars required by this target directly. They can be: - the corresponding regular Jars of the interface Jars returned by JavaInfo.compile_jars From a75e722ee86e248a129e7eca7fbe33eb68a2168d Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 29 May 2025 11:40:00 -0700 Subject: [PATCH 289/465] In `make_non_strict`, `header_compilation_direct_deps` should be the same as `compile_jars`, not `full_compile_jars` PiperOrigin-RevId: 764817862 Change-Id: Ieffa6ace40d189cdd1ff10c8cee1c6e567ba86b2 --- java/private/java_info.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/private/java_info.bzl b/java/private/java_info.bzl index de1111b7..bf793c5a 100644 --- a/java/private/java_info.bzl +++ b/java/private/java_info.bzl @@ -319,7 +319,7 @@ def make_non_strict(java_info): result.update( compile_jars = java_info.transitive_compile_time_jars, full_compile_jars = java_info._transitive_full_compile_time_jars, - header_compilation_direct_deps = java_info._transitive_full_compile_time_jars, + header_compilation_direct_deps = java_info.transitive_compile_time_jars, ) # Omit jdeps, which aren't available transitively and aren't useful for reduced classpath From fecb9fbe5e5417997bb8dda24c1873a130baf7d4 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 2 Jun 2025 11:30:53 -0700 Subject: [PATCH 290/465] Remove a reference to incompatible_disallow_java_import_empty_jars after unknown commit PiperOrigin-RevId: 766275350 Change-Id: I34dda7d32d6409e75256e7e424ae8fbb253a0580 --- test/java/common/rules/java_import_tests.bzl | 3 --- 1 file changed, 3 deletions(-) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 8580c1d4..e949e173 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -440,9 +440,6 @@ def _test_disallows_empty_jars(name): name = name, impl = _test_disallows_empty_jars_impl, target = name + "/rule", - config_settings = { - "//command_line_option:incompatible_disallow_java_import_empty_jars": True, - }, expect_failure = True, ) From 1947744286abd43834fd1c2a3c5a6b7495a669d5 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Wed, 11 Jun 2025 05:23:11 -0700 Subject: [PATCH 291/465] Add support for `--incompatible_compact_repo_mapping_manifest` (#301) Adds support for the new `_repo_mapping` format introduced in https://github.com/bazelbuild/bazel/issues/26262 to the runfiles library. Closes #301 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/301 from fmeum:compact-repo-mapping 678ea6da9257e7db1e1f5d4523b59f47e702a32a PiperOrigin-RevId: 770101779 Change-Id: Ifb6a8676b9612dd662e289d90a8e56e612c9f5b3 --- .../devtools/build/runfiles/Runfiles.java | 113 +++++++++++------- .../devtools/build/runfiles/RunfilesTest.java | 59 ++++++++- 2 files changed, 130 insertions(+), 42 deletions(-) diff --git a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Runfiles.java b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Runfiles.java index bec2091a..681f2479 100644 --- a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Runfiles.java +++ b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Runfiles.java @@ -24,8 +24,9 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.NavigableMap; import java.util.Objects; -import java.util.stream.Collectors; +import java.util.TreeMap; /** * Runfiles lookup library for Bazel-built Java binaries and tests. @@ -45,7 +46,7 @@ *

    2. Import the runfiles library. * *

    - *   import com.google.devtools.build.runfiles.Runfiles;
    + *   import Runfiles;
      * 
    * *

    3. Create a {@link Runfiles.Preloaded} object: @@ -59,11 +60,11 @@ *

    4. To look up a runfile, use either of the following approaches: * *

    4a. Annotate the class from which runfiles should be looked up with {@link - * AutoBazelRepository} and obtain the name of the Bazel repository containing the class from a - * constant generated by this annotation: + * AutoBazelRepository} and obtain the name of the Bazel + * repository containing the class from a constant generated by this annotation: * *

    - *   import com.google.devtools.build.runfiles.AutoBazelRepository;
    + *   import AutoBazelRepository;
      *   @AutoBazelRepository
      *   public class MyClass {
      *     public void myFunction() {
    @@ -95,7 +96,7 @@
      *
      * 
    * - * For more details on why it is required to pass in the current repository name, see {@see + *

    For more details on why it is required to pass in the current repository name, see {@see * https://bazel.build/build/bzlmod#repository-names}. * *

    Subprocesses

    @@ -204,7 +205,7 @@ public final Runfiles unmapped() { protected abstract String rlocationChecked(String path); - protected abstract Map getRepoMapping(); + protected abstract RepositoryMapping getRepoMapping(); // Private constructor, so only nested classes may extend it. private Preloaded() {} @@ -406,47 +407,19 @@ private static String getRunfilesDir(Map env) throws IOException return value; } - private static Map loadRepositoryMapping(String path) - throws IOException { - if (path == null || !new File(path).exists()) { - return Collections.emptyMap(); - } - - try (BufferedReader r = - new BufferedReader( - new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8))) { - return Collections.unmodifiableMap( - r.lines() - .filter(line -> !line.isEmpty()) - .map( - line -> { - String[] split = line.split(","); - if (split.length != 3) { - throw new IllegalArgumentException( - "Invalid line in repository mapping: '" + line + "'"); - } - return split; - }) - .collect( - Collectors.toMap( - split -> new Preloaded.RepoMappingKey(split[0], split[1]), - split -> split[2]))); - } - } - /** {@link Runfiles} implementation that parses a runfiles-manifest file to look up runfiles. */ private static final class ManifestBased extends Preloaded { private final Map runfiles; private final String manifestPath; - private final Map repoMapping; + private final RepositoryMapping repoMapping; ManifestBased(String manifestPath) throws IOException { Util.checkArgument(manifestPath != null); Util.checkArgument(!manifestPath.isEmpty()); this.manifestPath = manifestPath; this.runfiles = loadRunfiles(manifestPath); - this.repoMapping = loadRepositoryMapping(rlocationChecked("_repo_mapping")); + this.repoMapping = RepositoryMapping.readFromFile(rlocationChecked("_repo_mapping")); } @Override @@ -481,7 +454,7 @@ protected Map getEnvVars() { } @Override - protected Map getRepoMapping() { + protected RepositoryMapping getRepoMapping() { return repoMapping; } @@ -543,13 +516,13 @@ private static String findRunfilesDir(String manifest) { private static final class DirectoryBased extends Preloaded { private final String runfilesRoot; - private final Map repoMapping; + private final RepositoryMapping repoMapping; DirectoryBased(String runfilesDir) throws IOException { Util.checkArgument(!Util.isNullOrEmpty(runfilesDir)); Util.checkArgument(new File(runfilesDir).isDirectory()); this.runfilesRoot = runfilesDir; - this.repoMapping = loadRepositoryMapping(rlocationChecked("_repo_mapping")); + this.repoMapping = RepositoryMapping.readFromFile(rlocationChecked("_repo_mapping")); } @Override @@ -558,7 +531,7 @@ protected String rlocationChecked(String path) { } @Override - protected Map getRepoMapping() { + protected RepositoryMapping getRepoMapping() { return repoMapping; } @@ -579,4 +552,62 @@ static Preloaded createManifestBasedForTesting(String manifestPath) throws IOExc static Preloaded createDirectoryBasedForTesting(String runfilesDir) throws IOException { return new DirectoryBased(runfilesDir); } + + static final class RepositoryMapping { + private final Map exactMappings; + private final NavigableMap> wildcardMappings; + + private RepositoryMapping( + Map exactMappings, + NavigableMap> wildcardMappings) { + this.exactMappings = exactMappings; + this.wildcardMappings = wildcardMappings; + } + + static RepositoryMapping readFromFile(String path) throws IOException { + if (path == null || !new File(path).exists()) { + return new RepositoryMapping(Collections.emptyMap(), Collections.emptyNavigableMap()); + } + + try (BufferedReader r = + new BufferedReader( + new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8))) { + Map exactMappings = new HashMap<>(); + NavigableMap> wildcardMappings = new TreeMap<>(); + String line; + while ((line = r.readLine()) != null) { + if (line.isEmpty()) { + continue; + } + String[] split = line.split(","); + if (split.length != 3) { + throw new IllegalArgumentException( + "Invalid line in repository mapping: '" + line + "'"); + } + if (split[0].endsWith("*")) { + Map targetMap = + wildcardMappings.computeIfAbsent( + split[0].substring(0, split[0].length() - 1), k -> new HashMap<>()); + targetMap.put(split[1], split[2]); + } else { + exactMappings.put(new Preloaded.RepoMappingKey(split[0], split[1]), split[2]); + } + } + return new RepositoryMapping(exactMappings, wildcardMappings); + } + } + + String getOrDefault(Preloaded.RepoMappingKey key, String defaultValue) { + String exactMatch = exactMappings.get(key); + if (exactMatch != null) { + return exactMatch; + } + Map.Entry> floorEntry = + wildcardMappings.floorEntry(key.sourceRepo); + if (floorEntry == null || !key.sourceRepo.startsWith(floorEntry.getKey())) { + return defaultValue; + } + return floorEntry.getValue().getOrDefault(key.targetRepoApparentName, defaultValue); + } + } } diff --git a/test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java b/test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java index 035a0b52..406ebe8f 100644 --- a/test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java +++ b/test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/RunfilesTest.java @@ -427,6 +427,40 @@ public void testManifestBasedRlocationWithRepoMapping_fromOtherRepo() throws Exc assertThat(r.rlocation("protobuf")).isNull(); } + @Test + public void testManifestBasedRlocationWithRepoMapping_fromExtensionRepo() throws Exception { + Path rm = + tempFile( + "foo.repo_mapping", + ImmutableList.of( + ",config.json,config.json+1.2.3", + ",my_module,_main", + ",my_protobuf,protobuf+3.19.2", + ",my_workspace,_main", + "my_module++ext+*,my_module,my_module+", + "my_module++ext+*,repo1,my_module++ext+repo1")); + Path mf = + tempFile( + "foo.runfiles/MANIFEST", + ImmutableList.of( + "_repo_mapping " + rm, + "config.json /etc/config.json", + "protobuf+3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile", + "_main/bar/runfile /the/path/./to/other//other runfile.txt", + "protobuf+3.19.2/bar/dir E:\\Actual Path\\Directory", + "my_module+/foo/runfile /the/path/to/my_module+/runfile", + "my_module++ext+repo1/foo/runfile /the/path/to/my_module++ext+repo1/runfile", + "repo2+/foo/runfile /the/path/to/repo2+/runfile")); + Runfiles r = + Runfiles.createManifestBasedForTesting(mf.toString()) + .withSourceRepository("my_module++ext+repo1"); + + assertThat(r.rlocation("my_module/foo/runfile")).isEqualTo("/the/path/to/my_module+/runfile"); + assertThat(r.rlocation("repo1/foo/runfile")) + .isEqualTo("/the/path/to/my_module++ext+repo1/runfile"); + assertThat(r.rlocation("repo2+/foo/runfile")).isEqualTo("/the/path/to/repo2+/runfile"); + } + @Test public void testDirectoryBasedRlocationWithRepoMapping_fromMain() throws Exception { Path dir = tempDir.newFolder("foo.runfiles").toPath(); @@ -549,6 +583,28 @@ public void testDirectoryBasedRlocationWithRepoMapping_fromOtherRepo() throws Ex assertThat(r.rlocation("config.json")).isEqualTo(dir + "/config.json"); } + @Test + public void testDirectoryBasedRlocationWithRepoMapping_fromExtensionRepo() throws Exception { + Path dir = tempDir.newFolder("foo.runfiles").toPath(); + Path unused = + tempFile( + dir.resolve("_repo_mapping").toString(), + ImmutableList.of( + ",config.json,config.json+1.2.3", + ",my_module,_main", + ",my_protobuf,protobuf+3.19.2", + ",my_workspace,_main", + "my_module++ext+*,my_module,my_module+", + "my_module++ext+*,repo1,my_module++ext+repo1")); + Runfiles r = + Runfiles.createDirectoryBasedForTesting(dir.toString()) + .withSourceRepository("my_module++ext+repo1"); + + assertThat(r.rlocation("my_module/foo")).isEqualTo(dir + "/my_module+/foo"); + assertThat(r.rlocation("repo1/foo")).isEqualTo(dir + "/my_module++ext+repo1/foo"); + assertThat(r.rlocation("repo2+/foo")).isEqualTo(dir + "/repo2+/foo"); + } + @Test public void testDirectoryBasedCtorArgumentValidation() throws IOException { assertThrows( @@ -581,7 +637,8 @@ public void testManifestBasedCtorArgumentValidation() throws Exception { () -> Runfiles.createManifestBasedForTesting("").withSourceRepository("")); Path mf = tempFile("foobar", ImmutableList.of("a b")); - Runfiles unused = Runfiles.createManifestBasedForTesting(mf.toString()).withSourceRepository(""); + Runfiles unused = + Runfiles.createManifestBasedForTesting(mf.toString()).withSourceRepository(""); } @Test From 1a2c184bfc9423ea236db869841291de3be2f0da Mon Sep 17 00:00:00 2001 From: David Sanderson <32687193+dws@users.noreply.github.com> Date: Thu, 12 Jun 2025 07:49:41 -0700 Subject: [PATCH 292/465] use DefaultInfo in rules_java (#303) We here address the following obstacles in `rules_java` to using Bazel's `--incompatible_disable_target_default_provider_fields` flag: ERROR: /private/var/tmp/_bazel_dws/7fd3cd5077fbf76d9e2ae421c39ef7ed/external/rules_java+/toolchains/BUILD:359:27: in java_toolchain rule @@rules_java+//toolchains:toolchain_jdk_21: Traceback (most recent call last): File "/private/var/tmp/_bazel_dws/7fd3cd5077fbf76d9e2ae421c39ef7ed/external/rules_java+/java/common/rules/java_toolchain.bzl", line 100, column 45, in _java_toolchain_impl jacocorunner = ctx.attr.jacocorunner.files_to_run if ctx.attr.jacocorunner else None, Error: Accessing the default provider in this manner is deprecated and will be removed soon. It may be temporarily re-enabled by setting --incompatible_disable_target_default_provider_fields=false. See https://github.com/bazelbuild/bazel/issues/20183 for details. ERROR: /private/var/tmp/_bazel_dws/7fd3cd5077fbf76d9e2ae421c39ef7ed/external/rules_java+/toolchains/BUILD:359:27: Analysis of target '@@rules_java+//toolchains:toolchain_jdk_21' failed ERROR: Analysis of target '//src:bazel' failed; build aborted: Analysis failed ERROR: /Users/dws/src/bazel-dws/third_party/BUILD:578:20: in java_import rule //third_party:netty_tcnative_checked_in: Traceback (most recent call last): File "/private/var/tmp/_bazel_dws/7fd3cd5077fbf76d9e2ae421c39ef7ed/external/rules_java+/java/bazel/rules/bazel_java_import.bzl", line 25, column 34, in _proxy return bazel_java_import_rule( File "/private/var/tmp/_bazel_dws/7fd3cd5077fbf76d9e2ae421c39ef7ed/external/rules_java+/java/common/rules/impl/bazel_java_import_impl.bzl", line 132, column 35, in bazel_java_import_rule collected_jars = _collect_jars(ctx, jars) File "/private/var/tmp/_bazel_dws/7fd3cd5077fbf76d9e2ae421c39ef7ed/external/rules_java+/java/common/rules/impl/bazel_java_import_impl.bzl", line 38, column 24, in _collect_jars for jar in info.files.to_list(): Error: Accessing the default provider in this manner is deprecated and will be removed soon. It may be temporarily re-enabled by setting --incompatible_disable_target_default_provider_fields=false. See https://github.com/bazelbuild/bazel/issues/20183 for details. ERROR: /Users/dws/src/bazel-dws/third_party/BUILD:578:20: Analysis of target '//third_party:netty_tcnative_checked_in' failed ERROR: Analysis of target '//src:bazel' failed; build aborted: Analysis failed Closes #303 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/303 from dws:DefaultInfo c02b7724a5dcf85bb9c87bc06c1cd0504c0507f9 PiperOrigin-RevId: 770652076 Change-Id: Icc8a698ac66d76b47d9793a0c448d98d05e7186f --- .../common/rules/impl/bazel_java_import_impl.bzl | 4 ++-- java/common/rules/java_toolchain.bzl | 16 ++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/java/common/rules/impl/bazel_java_import_impl.bzl b/java/common/rules/impl/bazel_java_import_impl.bzl index 44656705..ce338cbd 100644 --- a/java/common/rules/impl/bazel_java_import_impl.bzl +++ b/java/common/rules/impl/bazel_java_import_impl.bzl @@ -35,7 +35,7 @@ def _collect_jars(ctx, jars): for info in jars: if JavaInfo in info: fail("'jars' attribute cannot contain labels of Java targets") - for jar in info.files.to_list(): + for jar in info[DefaultInfo].files.to_list(): jar_path = jar.dirname + jar.basename if jars_dict.get(jar_path) != None: fail("in jars attribute of java_import rule //" + ctx.label.package + ":" + ctx.attr.name + ": " + jar.basename + " is a duplicate") @@ -179,7 +179,7 @@ def bazel_java_import_rule( # TODO(kotlaja): Revise if collected_runtimes can be added into construct_defaultinfo directly. collected_runtimes = [] for runtime_dep in ctx.attr.runtime_deps: - collected_runtimes.extend(runtime_dep.files.to_list()) + collected_runtimes.extend(runtime_dep[DefaultInfo].files.to_list()) target["DefaultInfo"] = construct_defaultinfo( ctx, diff --git a/java/common/rules/java_toolchain.bzl b/java/common/rules/java_toolchain.bzl index 2e4fc67e..fe32fc36 100644 --- a/java/common/rules/java_toolchain.bzl +++ b/java/common/rules/java_toolchain.bzl @@ -96,13 +96,13 @@ def _java_toolchain_impl(ctx): oneversion_allowlist = ctx.file.oneversion_allowlist if ctx.file.oneversion_allowlist else ctx.file.oneversion_whitelist java_toolchain_info = _new_javatoolchaininfo( bootclasspath = bootclasspath_info.bootclasspath, - ijar = ctx.attr.ijar.files_to_run if ctx.attr.ijar else None, - jacocorunner = ctx.attr.jacocorunner.files_to_run if ctx.attr.jacocorunner else None, + ijar = ctx.attr.ijar[DefaultInfo].files_to_run if ctx.attr.ijar else None, + jacocorunner = ctx.attr.jacocorunner[DefaultInfo].files_to_run if ctx.attr.jacocorunner else None, java_runtime = java_runtime, jvm_opt = depset(get_internal_java_common().expand_java_opts(ctx, "jvm_opts", tokenize = False, exec_paths = True)), label = ctx.label, - proguard_allowlister = ctx.attr.proguard_allowlister.files_to_run if ctx.attr.proguard_allowlister else None, - single_jar = ctx.attr.singlejar.files_to_run, + proguard_allowlister = ctx.attr.proguard_allowlister[DefaultInfo].files_to_run if ctx.attr.proguard_allowlister else None, + single_jar = ctx.attr.singlejar[DefaultInfo].files_to_run, source_version = ctx.attr.source_version, target_version = ctx.attr.target_version, tools = depset(ctx.files.tools), @@ -131,7 +131,7 @@ def _java_toolchain_impl(ctx): _javac_supports_worker_multiplex_sandboxing = ctx.attr.javac_supports_worker_multiplex_sandboxing, _jspecify_info = _get_jspecify_info(ctx), _local_java_optimization_config = ctx.files._local_java_optimization_configuration, - _one_version_tool = ctx.attr.oneversion.files_to_run if ctx.attr.oneversion else None, + _one_version_tool = ctx.attr.oneversion[DefaultInfo].files_to_run if ctx.attr.oneversion else None, _one_version_allowlist = oneversion_allowlist, _one_version_allowlist_for_tests = ctx.file.oneversion_allowlist_for_tests, _package_configuration = [dep[JavaPackageConfigurationInfo] for dep in ctx.attr.package_configuration], @@ -171,7 +171,7 @@ def _get_javac_opts(ctx): def _get_android_lint_tool(ctx): if not ctx.attr.android_lint_runner: return None - files_to_run = ctx.attr.android_lint_runner.files_to_run + files_to_run = ctx.attr.android_lint_runner[DefaultInfo].files_to_run if not files_to_run or not files_to_run.executable: fail(ctx.attr.android_lint_runner.label, "does not refer to a valid executable target") return struct( @@ -186,7 +186,7 @@ def _get_tool_from_ctx(ctx, tool_attr, data_attr, opts_attr): dep = getattr(ctx.attr, tool_attr) if not dep: return None - files_to_run = dep.files_to_run + files_to_run = dep[DefaultInfo].files_to_run if not files_to_run or not files_to_run.executable: fail(dep.label, "does not refer to a valid executable target") data = getattr(ctx.attr, data_attr) @@ -200,7 +200,7 @@ def _get_tool_from_executable(ctx, attr_name, data = [], jvm_opts = []): dep = getattr(ctx.attr, attr_name) if not dep: return None - files_to_run = dep.files_to_run + files_to_run = dep[DefaultInfo].files_to_run if not files_to_run or not files_to_run.executable: fail(dep.label, "does not refer to a valid executable target") return struct(tool = files_to_run, data = depset(data), jvm_opts = depset(jvm_opts)) From d927aa05abfda8bf3fb988ab77dc73d5f2a825f5 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Thu, 12 Jun 2025 09:46:53 -0700 Subject: [PATCH 293/465] Fix Runfiles docs after #301 (#302) Closes #302 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/302 from fmeum:patch-4 feca4dbff3d928b2165d31d82bbe6a9ff7803e6e PiperOrigin-RevId: 770694363 Change-Id: I3c369b638abbdd4c4fb9ad414802e4af1b5abfea --- .../java/com/google/devtools/build/runfiles/Runfiles.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Runfiles.java b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Runfiles.java index 681f2479..06221b76 100644 --- a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Runfiles.java +++ b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/Runfiles.java @@ -46,7 +46,7 @@ *

    2. Import the runfiles library. * *

    - *   import Runfiles;
    + *   import com.google.devtools.build.runfiles.Runfiles;
      * 
    * *

    3. Create a {@link Runfiles.Preloaded} object: @@ -64,7 +64,7 @@ * repository containing the class from a constant generated by this annotation: * *

    - *   import AutoBazelRepository;
    + *   import com.google.devtools.build.runfiles.AutoBazelRepository;
      *   @AutoBazelRepository
      *   public class MyClass {
      *     public void myFunction() {
    
    From c289c727a19935dc6292545ce101972e02a667fd Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Fri, 20 Jun 2025 02:11:50 -0700
    Subject: [PATCH 294/465] Update `java_tools` `v15.0`
    
    Built at: https://github.com/bazelbuild/bazel/commit/387ed020deff607abcebe9b82ba8ea61da5a5e9d
    
    PiperOrigin-RevId: 773600616
    Change-Id: I3c31ec7e0f174503053f242546331bd658dafdfb
    ---
     java/repositories.bzl | 32 ++++++++++++++++----------------
     1 file changed, 16 insertions(+), 16 deletions(-)
    
    diff --git a/java/repositories.bzl b/java/repositories.bzl
    index ee1d029a..548fb2a0 100644
    --- a/java/repositories.bzl
    +++ b/java/repositories.bzl
    @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository")
     
     # visible for tests
     JAVA_TOOLS_CONFIG = {
    -    "version": "v14.0",
    +    "version": "v15.0",
         "release": "true",
         "artifacts": {
             "java_tools_linux": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v14.0/java_tools_linux-v14.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v14.0/java_tools_linux-v14.0.zip",
    -            "sha": "51ed941d6c62e432e59cc3b6ad3503639cc138ee7a02ed6bf0bbbb16ded418c9",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v15.0/java_tools_linux-v15.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v15.0/java_tools_linux-v15.0.zip",
    +            "sha": "8d9311ced79b7f346f7e71e924fbd9d3de0bb64c486c6e4cd27ea0287b4b9ab6",
             },
             "java_tools_windows": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v14.0/java_tools_windows-v14.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v14.0/java_tools_windows-v14.0.zip",
    -            "sha": "3f918fb9c24b04bcd6088ed62c240cfbb1a4bb50376e394151d34d60e8e71cdf",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v15.0/java_tools_windows-v15.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v15.0/java_tools_windows-v15.0.zip",
    +            "sha": "118691add8965116c716afc0eae2e0c079d39068c84e3d650c53b4ad18d27f10",
             },
             "java_tools_darwin_x86_64": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v14.0/java_tools_darwin_x86_64-v14.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v14.0/java_tools_darwin_x86_64-v14.0.zip",
    -            "sha": "94daf7d9586943261114de6bde97053597ce031bb8d76672688843b33b7ff610",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v15.0/java_tools_darwin_x86_64-v15.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v15.0/java_tools_darwin_x86_64-v15.0.zip",
    +            "sha": "b06facc077b01314884ea5f7e4dbdff20a0541f547d2249401ebcc1d3ae329c1",
             },
             "java_tools_darwin_arm64": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v14.0/java_tools_darwin_arm64-v14.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v14.0/java_tools_darwin_arm64-v14.0.zip",
    -            "sha": "5f12ea12d0381058dac8aa85ad3656c3a7ab85b8c5d8cd98e4ab57bd8fbf8bee",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v15.0/java_tools_darwin_arm64-v15.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v15.0/java_tools_darwin_arm64-v15.0.zip",
    +            "sha": "9c9d3b42576ccc6c2e908877b1576bdaa274d8db1bdf4b7c80d767e4b4185d6e",
             },
             "java_tools": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v14.0/java_tools-v14.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v14.0/java_tools-v14.0.zip",
    -            "sha": "1c2074e3ffb8c5bd22d5e65964535f70ba7b1bcd4e688f5d89f79f72a1b625bf",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v15.0/java_tools-v15.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v15.0/java_tools-v15.0.zip",
    +            "sha": "abae85fc87da0221cfaa8c1f11bce3db892c2b6946be7d9752cfa1e7fca36756",
             },
         },
     }
    
    From d1e335a58dcc24ca386042d7d9891d71013650d5 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Fri, 20 Jun 2025 02:18:17 -0700
    Subject: [PATCH 295/465] Release `rules_java` `v8.13.0`
    
    PiperOrigin-RevId: 773602637
    Change-Id: I14b501ee01214980a50cc56b645e2eecdb3d3266
    ---
     MODULE.bazel | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index 9a1562e9..7f1e91ce 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -1,6 +1,6 @@
     module(
         name = "rules_java",
    -    version = "8.12.0",
    +    version = "8.13.0",
         bazel_compatibility = [">=6.4.0"],
         compatibility_level = 1,
     )
    
    From 3daed1aeb1baa4d8867119785d60b50be4aa8b40 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Tue, 24 Jun 2025 02:15:16 -0700
    Subject: [PATCH 296/465] Update `@rules_java` CI to use Bazel `8.3.0`
    
    PiperOrigin-RevId: 775136930
    Change-Id: Iac7046b3c16682277bcc18fe3751d3fdce1271c4
    ---
     .bazelci/presubmit.yml | 8 +++-----
     1 file changed, 3 insertions(+), 5 deletions(-)
    
    diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml
    index 18088a21..3840395e 100644
    --- a/.bazelci/presubmit.yml
    +++ b/.bazelci/presubmit.yml
    @@ -42,14 +42,12 @@ test_target_integration: &test_target_integration
     flags_workspace_integration: &flags_workspace_integration
       - "--noenable_bzlmod"
       - "--enable_workspace"
    -  # TODO(hvd): remove after Bazel 8.3.0
    -  - "--repositories_without_autoloads=bazel_features_version,bazel_features_globals"
     
     buildifier: latest
     
     matrix:
       all_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"]
    -  bazel: ["7.6.1", "8.2.1", "last_green"] # Bazel 6 tested separately, needs different flags
    +  bazel: ["7.6.1", "8.3.0", "last_green"] # Bazel 6 tested separately, needs different flags
       modern_bazel: ["last_green"] # Fully supported Bazel versions
     
     tasks:
    @@ -62,8 +60,8 @@ tasks:
         test_targets: *test_targets
     # Bazel 8.x
       build_and_test_bazel8:
    -    name: "Bazel 8.2.1"
    -    bazel: "8.2.1"
    +    name: "Bazel 8.3.0"
    +    bazel: "8.3.0"
         platform: ${{ all_platforms }}
         build_targets: *build_targets
         test_targets: *test_targets
    
    From d3f34085e87d436e12e1df2fa2d018cba59d0e2b Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 25 Jun 2025 08:39:51 -0700
    Subject: [PATCH 297/465] Make C++ toolchain explicitly not mandatory
    
    Fixes: https://github.com/bazelbuild/rules_java/issues/305
    PiperOrigin-RevId: 775703888
    Change-Id: I709ccc8f29a09470aa3c4653ce9e1c413fafbbe4
    ---
     java/bazel/rules/bazel_java_binary.bzl | 4 ++--
     1 file changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl
    index cbbe0de8..da547226 100644
    --- a/java/bazel/rules/bazel_java_binary.bzl
    +++ b/java/bazel/rules/bazel_java_binary.bzl
    @@ -317,7 +317,7 @@ def make_binary_rule(implementation, *, doc, attrs, executable = False, test = F
             test = test,
             fragments = ["cpp", "java"],
             provides = [JavaInfo],
    -        toolchains = [semantics.JAVA_TOOLCHAIN] + use_cc_toolchain() + (
    +        toolchains = [semantics.JAVA_TOOLCHAIN] + use_cc_toolchain(mandatory = False) + (
                 [semantics.JAVA_RUNTIME_TOOLCHAIN] if executable or test else []
             ) + (
                 [_LAUNCHER_MAKER_TOOLCHAIN] if bazel_features.rules._has_launcher_maker_toolchain else []
    @@ -331,7 +331,7 @@ def make_binary_rule(implementation, *, doc, attrs, executable = False, test = F
                 "unstrippeddeployjar": "%{name}_deploy.jar.unstripped",
             },
             exec_groups = {
    -            "cpp_link": exec_group(toolchains = use_cc_toolchain()),
    +            "cpp_link": exec_group(toolchains = use_cc_toolchain(mandatory = False)),
             },
             subrules = [android_lint_subrule],
         )
    
    From aec334a90360d4a3213d70810199679f53fa663c Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Mon, 7 Jul 2025 02:09:10 -0700
    Subject: [PATCH 298/465] Migrate from deprecated
     cc_linking_context.libraries_to_link to
     cc_linking_context.linker_inputs.libraries
    
    Rename static_mode_params_for_dynamic_library_libs to libraries. Previously it was a misnomer.
    
    This is a no-op change.
    
    PiperOrigin-RevId: 780012470
    Change-Id: I418fc15f5c971cb68b033068e02ad719967101d8
    ---
     test/java/testutil/cc_info_subject.bzl | 11 +++++------
     1 file changed, 5 insertions(+), 6 deletions(-)
    
    diff --git a/test/java/testutil/cc_info_subject.bzl b/test/java/testutil/cc_info_subject.bzl
    index c123c3d8..2d7dca12 100644
    --- a/test/java/testutil/cc_info_subject.bzl
    +++ b/test/java/testutil/cc_info_subject.bzl
    @@ -21,12 +21,11 @@ def _new_cc_info_linking_context_subject(cc_info, meta):
         )
         public = struct(
             equals = lambda other: _cc_info_linking_context_equals(self.actual, other, self.meta),
    -        libraries_to_link = lambda: _new_cc_info_libraries_to_link_subject(self.actual.libraries_to_link, self.meta.derive("libraries_to_link")),
    -        static_mode_params_for_dynamic_library_libs = lambda: _new_static_mode_params_for_dynamic_library_libs_subject(self.actual, self.meta),
    +        library_files = lambda: _new_library_files_subject(self.actual, self.meta),
         )
         return public
     
    -def _new_static_mode_params_for_dynamic_library_libs_subject(linking_context, meta):
    +def _new_library_files_subject(linking_context, meta):
         libs = []
         for input in linking_context.linker_inputs.to_list():
             for lib in input.libraries:
    @@ -39,9 +38,9 @@ def _new_static_mode_params_for_dynamic_library_libs_subject(linking_context, me
                 else:
                     libs.append(lib.dynamic_library)
     
    -    return subjects.collection(
    -        libs,
    -        meta = meta.derive("static_mode_params_for_dynamic_library_libs"),
    +    return subjects.depset_file(
    +        depset(libs),
    +        meta = meta.derive("library_files"),
         )
     
     def _cc_info_linking_context_equals(actual, expected, meta):
    
    From 0b94d21938932eab2367fdca443b1f8a5196f7ae Mon Sep 17 00:00:00 2001
    From: Yun Peng 
    Date: Tue, 8 Jul 2025 02:58:57 -0700
    Subject: [PATCH 299/465] Use root test_deps target from bazel_skylib (#306)
    
    Fixing
    ```
    $ bazel build //src/test/java/com/google/devtools/build/lib/query2/cquery:FilesOutputFormatterCallbackTest
    ...
    ERROR: /private/var/tmp/_bazel_pcloudy/829441223e9fec5a5a2e3d1dd743fdf0/external/rules_java+/java/BUILD:78:10: in filegroup rule @@rules_java+//java:for_bazel_tests: Visibility error:
    target '@@bazel_skylib+//lib:test_deps' is not visible from
    target '@@rules_java+//java:for_bazel_tests'
    Recommendation: modify the visibility declaration if you think the dependency is legitimate. For more info see https://bazel.build/concepts/visibility
    ```
    after upgrading bazel_skylib which contains https://github.com/bazelbuild/bazel-skylib/pull/508
    
    Closes #306
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/306 from bazelbuild:meteorcloudy-patch-1 a0df97cd25f9784da04f55ac037eee4ae0fa777c
    PiperOrigin-RevId: 780484650
    Change-Id: I1516310b78322eeb62d982a2e2a69d7ec756f925
    ---
     java/BUILD | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/java/BUILD b/java/BUILD
    index 31621486..452c7654 100644
    --- a/java/BUILD
    +++ b/java/BUILD
    @@ -88,7 +88,7 @@ filegroup(
             "//java/common:for_bazel_tests",
             "//java/private:for_bazel_tests",
             "//java/toolchains:for_bazel_tests",
    -        "@bazel_skylib//lib:test_deps",
    +        "@bazel_skylib//:test_deps",
         ],
         visibility = ["//visibility:public"],
     )
    
    From 3b9ca9949516b1211d4626985c1755252241d559 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Thu, 17 Jul 2025 08:21:31 -0700
    Subject: [PATCH 300/465] Update to `java_tools` `v16.0`
    
    PiperOrigin-RevId: 784188539
    Change-Id: Iddd537d5bedf8f82490e2f4959b753a4ec63e065
    ---
     java/repositories.bzl | 32 ++++++++++++++++----------------
     1 file changed, 16 insertions(+), 16 deletions(-)
    
    diff --git a/java/repositories.bzl b/java/repositories.bzl
    index 548fb2a0..2af22140 100644
    --- a/java/repositories.bzl
    +++ b/java/repositories.bzl
    @@ -22,33 +22,33 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository")
     
     # visible for tests
     JAVA_TOOLS_CONFIG = {
    -    "version": "v15.0",
    +    "version": "v16.0",
         "release": "true",
         "artifacts": {
             "java_tools_linux": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v15.0/java_tools_linux-v15.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v15.0/java_tools_linux-v15.0.zip",
    -            "sha": "8d9311ced79b7f346f7e71e924fbd9d3de0bb64c486c6e4cd27ea0287b4b9ab6",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v16.0/java_tools_linux-v16.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v16.0/java_tools_linux-v16.0.zip",
    +            "sha": "7c360c60da9b9079e31f18de198f23a22555dfb7b6e91e3c6a7103127b1a8538",
             },
             "java_tools_windows": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v15.0/java_tools_windows-v15.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v15.0/java_tools_windows-v15.0.zip",
    -            "sha": "118691add8965116c716afc0eae2e0c079d39068c84e3d650c53b4ad18d27f10",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v16.0/java_tools_windows-v16.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v16.0/java_tools_windows-v16.0.zip",
    +            "sha": "b41faa85fceeb2f852e48d51d000d3bf4f29da86ee61d0fc8cca46d297bccf22",
             },
             "java_tools_darwin_x86_64": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v15.0/java_tools_darwin_x86_64-v15.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v15.0/java_tools_darwin_x86_64-v15.0.zip",
    -            "sha": "b06facc077b01314884ea5f7e4dbdff20a0541f547d2249401ebcc1d3ae329c1",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v16.0/java_tools_darwin_x86_64-v16.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v16.0/java_tools_darwin_x86_64-v16.0.zip",
    +            "sha": "a41de64afb663bb4880af52b55886098241b9222ee8ec1a0f6258d006ba247fb",
             },
             "java_tools_darwin_arm64": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v15.0/java_tools_darwin_arm64-v15.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v15.0/java_tools_darwin_arm64-v15.0.zip",
    -            "sha": "9c9d3b42576ccc6c2e908877b1576bdaa274d8db1bdf4b7c80d767e4b4185d6e",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v16.0/java_tools_darwin_arm64-v16.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v16.0/java_tools_darwin_arm64-v16.0.zip",
    +            "sha": "b79900dccca7c26fbae9a38c4da80987445e07194517ec53e169c45f1a88c7be",
             },
             "java_tools": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v15.0/java_tools-v15.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v15.0/java_tools-v15.0.zip",
    -            "sha": "abae85fc87da0221cfaa8c1f11bce3db892c2b6946be7d9752cfa1e7fca36756",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v16.0/java_tools-v16.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v16.0/java_tools-v16.0.zip",
    +            "sha": "d8b126078705e91677db67b05f7b25ad6fa8865949e2dd38ff85e0553bfb0be2",
             },
         },
     }
    
    From 02f488deec4eaf8188d8433762554dcc4e6083f7 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Fri, 18 Jul 2025 02:18:26 -0700
    Subject: [PATCH 301/465] Release `@rules_java` `v8.14.0`
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 784501450
    Change-Id: Iaeb8e09987f9d23956d180ca29cf4ee42345f1af
    ---
     MODULE.bazel | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index 7f1e91ce..bd4f2111 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -1,6 +1,6 @@
     module(
         name = "rules_java",
    -    version = "8.13.0",
    +    version = "8.14.0",
         bazel_compatibility = [">=6.4.0"],
         compatibility_level = 1,
     )
    
    From d8246a409519f9d551dd866a46278e394bd1b295 Mon Sep 17 00:00:00 2001
    From: Donald Duo Zhao 
    Date: Fri, 18 Jul 2025 16:58:04 -0700
    Subject: [PATCH 302/465] Automatic code cleanup.
    
    PiperOrigin-RevId: 784744315
    Change-Id: Ia6c12564112645ff2161dbb04a5b6f6393445026
    ---
     java/java_single_jar.bzl | 10 +++++++---
     1 file changed, 7 insertions(+), 3 deletions(-)
    
    diff --git a/java/java_single_jar.bzl b/java/java_single_jar.bzl
    index 6812fcff..48aa45c3 100644
    --- a/java/java_single_jar.bzl
    +++ b/java/java_single_jar.bzl
    @@ -3,9 +3,9 @@
     load("//java/common:java_common.bzl", "java_common")
     load("//java/common:java_info.bzl", "JavaInfo")
     
    -def _java_single_jar(ctx):
    +def _single_jar_inputs(deps, deploy_env):
         transitive_inputs = []
    -    for dep in ctx.attr.deps:
    +    for dep in deps:
             if JavaInfo in dep:
                 info = dep[JavaInfo]
                 transitive_inputs.append(info.transitive_runtime_jars)
    @@ -25,11 +25,15 @@ def _java_single_jar(ctx):
         if hasattr(java_common, "JavaRuntimeClasspathInfo"):
             deploy_env_jars = depset(transitive = [
                 dep[java_common.JavaRuntimeClasspathInfo].runtime_classpath
    -            for dep in ctx.attr.deploy_env
    +            for dep in deploy_env
             ])
             excluded_jars = {jar: None for jar in deploy_env_jars.to_list()}
             if excluded_jars:
                 inputs = depset([jar for jar in inputs.to_list() if jar not in excluded_jars])
    +    return inputs
    +
    +def _java_single_jar(ctx):
    +    inputs = _single_jar_inputs(ctx.attr.deps, ctx.attr.deploy_env)
     
         args = ctx.actions.args()
         args.add_all("--sources", inputs)
    
    From bbb99fa1450e1a92eb79ae77c841b08af9403ed2 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 30 Jul 2025 02:00:19 -0700
    Subject: [PATCH 303/465] rules_java: Rename CcInfo#transitive_native_libraries
     to _legacy_transitive_native_libraries
    
    This is needed to convert CcInfo to Starlark without causing a major regression.
    
    Mark the field as legacy, becuase we'll need to eventually clean it up.
    
    PiperOrigin-RevId: 788808464
    Change-Id: I86a21b4b16bd2953961b0f1e7bae2d4ac43e0712
    ---
     java/common/rules/impl/java_binary_impl.bzl |  5 ++++-
     java/private/java_info.bzl                  | 15 ++++++++++++---
     java/testutil.bzl                           |  2 ++
     3 files changed, 18 insertions(+), 4 deletions(-)
    
    diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl
    index a41a125b..15ae89b7 100644
    --- a/java/common/rules/impl/java_binary_impl.bzl
    +++ b/java/common/rules/impl/java_binary_impl.bzl
    @@ -154,7 +154,10 @@ def basic_java_binary(
             if JavaInfo in dep:
                 native_libs_depsets.append(dep[JavaInfo].transitive_native_libraries)
             if CcInfo in dep:
    -            native_libs_depsets.append(dep[CcInfo].transitive_native_libraries())
    +            if hasattr(dep[CcInfo], "_legacy_transitive_native_libraries"):
    +                native_libs_depsets.append(dep[CcInfo]._legacy_transitive_native_libraries)
    +            else:
    +                native_libs_depsets.append(dep[CcInfo].transitive_native_libraries())
         native_libs_dirs = collect_native_deps_dirs(depset(transitive = native_libs_depsets))
         if native_libs_dirs:
             prefix = "${JAVA_RUNFILES}/" + ctx.workspace_name + "/"
    diff --git a/java/private/java_info.bzl b/java/private/java_info.bzl
    index bf793c5a..65c6f2a1 100644
    --- a/java/private/java_info.bzl
    +++ b/java/private/java_info.bzl
    @@ -178,7 +178,8 @@ def merge(
             cc_info = semantics.minimize_cc_info(cc_common.merge_cc_infos(cc_infos = [p.cc_link_params_info for p in providers]))
             result.update(
                 cc_link_params_info = cc_info,
    -            transitive_native_libraries = cc_info.transitive_native_libraries(),
    +            transitive_native_libraries =
    +                cc_info._legacy_transitive_native_libraries if hasattr(cc_info, "_legacy_transitive_native_libraries") else cc_info.transitive_native_libraries(),
             )
         else:
             result.update(
    @@ -679,14 +680,22 @@ def _javainfo_init_base(
             cc_info = semantics.minimize_cc_info(cc_common.merge_cc_infos(cc_infos = transitive_cc_infos))
             result.update(
                 cc_link_params_info = cc_info,
    -            transitive_native_libraries = cc_info.transitive_native_libraries(),
    +            transitive_native_libraries =
    +                cc_info._legacy_transitive_native_libraries if hasattr(cc_info, "_legacy_transitive_native_libraries") else cc_info.transitive_native_libraries(),
             )
         else:
    +        transitive_native_libraries = []
    +        if native_libraries:
    +            merged_cc_info = cc_common.merge_cc_infos(cc_infos = native_libraries)
    +            if hasattr(merged_cc_info, "_legacy_transitive_native_libraries"):
    +                transitive_native_libraries = [merged_cc_info._legacy_transitive_native_libraries]
    +            else:
    +                transitive_native_libraries = [merged_cc_info.transitive_native_libraries()]
             result.update(
                 transitive_native_libraries = depset(
                     order = "topological",
                     transitive = [dep.transitive_native_libraries for dep in concatenated_deps.runtimedeps_exports_deps] +
    -                             ([cc_common.merge_cc_infos(cc_infos = native_libraries).transitive_native_libraries()] if native_libraries else []),
    +                             transitive_native_libraries,
                 ),
             )
         return result, concatenated_deps
    diff --git a/java/testutil.bzl b/java/testutil.bzl
    index 6207583b..4063ea6f 100644
    --- a/java/testutil.bzl
    +++ b/java/testutil.bzl
    @@ -5,6 +5,8 @@
     # TODO: consider eventually upstreaming to rules_cc
     
     def _cc_info_transitive_native_libraries(cc_info):
    +    if hasattr(cc_info, "_legacy_transitive_native_libraries"):
    +        return cc_info._legacy_transitive_native_libraries
         return cc_info.transitive_native_libraries()
     
     def _cc_library_to_link_static_library(library_to_link):
    
    From c0462f09c1a6f7607d5d6b86ba291746fd003a86 Mon Sep 17 00:00:00 2001
    From: "Ian (Hee) Cha" 
    Date: Fri, 1 Aug 2025 00:51:19 -0700
    Subject: [PATCH 304/465] Update rules_java to 8.15.0 (#309)
    
    See https://github.com/bazelbuild/rules_java/issues/308 for reference.
    
    Closes #309
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/309 from bazelbuild:iancha1992-8.15.0 6d270fca325bf30fc4c9ad72443374649cd8b838
    PiperOrigin-RevId: 789650494
    Change-Id: I2482eb988d2710d5ff72adcc45bb677e23d27398
    ---
     MODULE.bazel | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index bd4f2111..6fafb13d 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -1,6 +1,6 @@
     module(
         name = "rules_java",
    -    version = "8.14.0",
    +    version = "8.15.0",
         bazel_compatibility = [">=6.4.0"],
         compatibility_level = 1,
     )
    
    From 45061b38c54f4ee8e3038601c5d857154c7ae9db Mon Sep 17 00:00:00 2001
    From: Krishna Magar 
    Date: Thu, 7 Aug 2025 04:59:43 -0700
    Subject: [PATCH 305/465] Fix Java coverage support on Windows by adding
     coverage_main_class to launch_info (#311)
    
    ### Summary
    
    This PR enables Java code coverage to work properly on Windows by adding the `coverage_main_class` to the `launch_info` metadata in `bazel_java_binary.bzl`. Without this addition, Bazel fails to properly instrument and run Java binaries with coverage enabled on Windows platforms.
    
    ### Changes
    
    - Added `coverage_main_class` to `launch_info` in `bazel_java_binary.bzl` to explicitly define the main class used during coverage runs.
    
    ### Motivation
    
    - Before this fix, attempts to run Java coverage tests on Windows would not produce proper coverage output.
    - This is a step toward resolving [bazelbuild/bazel#18839](https://github.com/bazelbuild/bazel/issues/18839).
    
    Closes #311
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/311 from KrishnaM256:master 78942a24d9e34daa2ec9cecd8473dbfbb8c64059
    PiperOrigin-RevId: 792108185
    Change-Id: Ia29301538eaa3f7ca1195230abb32536dbe52e4f
    ---
     java/bazel/rules/bazel_java_binary.bzl | 6 ++++--
     1 file changed, 4 insertions(+), 2 deletions(-)
    
    diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl
    index da547226..1e4411e7 100644
    --- a/java/bazel/rules/bazel_java_binary.bzl
    +++ b/java/bazel/rules/bazel_java_binary.bzl
    @@ -232,7 +232,7 @@ def _create_stub(ctx, java_attrs, launcher, executable, jvm_flags, main_class, c
             jvm_flags_for_launcher = []
             for flag in jvm_flags:
                 jvm_flags_for_launcher.extend(ctx.tokenize(flag))
    -        return _create_windows_exe_launcher(ctx, java_executable, classpath, main_class, jvm_flags_for_launcher, runfiles_enabled, executable)
    +        return _create_windows_exe_launcher(ctx, java_executable, classpath, main_class, jvm_flags_for_launcher, runfiles_enabled, coverage_enabled, executable, coverage_main_class)
     
         if runfiles_enabled:
             prefix = "" if helper.is_absolute_target_platform_path(ctx, java_executable) else "${JAVA_RUNFILES}/"
    @@ -277,13 +277,15 @@ def _format_classpath_entry(runfiles_enabled, workspace_prefix, file):
     
         return "$(rlocation " + paths.normalize(workspace_prefix + file.short_path) + ")"
     
    -def _create_windows_exe_launcher(ctx, java_executable, classpath, main_class, jvm_flags_for_launcher, runfiles_enabled, executable):
    +def _create_windows_exe_launcher(ctx, java_executable, classpath, main_class, jvm_flags_for_launcher, runfiles_enabled, coverage_enabled, executable, coverage_main_class):
         launch_info = ctx.actions.args().use_param_file("%s", use_always = True).set_param_file_format("multiline")
         launch_info.add("binary_type=Java")
         launch_info.add(ctx.workspace_name, format = "workspace_name=%s")
         launch_info.add("1" if runfiles_enabled else "0", format = "symlink_runfiles_enabled=%s")
         launch_info.add(java_executable, format = "java_bin_path=%s")
         launch_info.add(main_class, format = "java_start_class=%s")
    +    if coverage_enabled:
    +        launch_info.add(coverage_main_class, format = "jacoco_main_class=%s")
         launch_info.add_joined(classpath, map_each = _short_path, join_with = ";", format_joined = "classpath=%s", omit_if_empty = False)
         launch_info.add_joined(jvm_flags_for_launcher, join_with = "\t", format_joined = "jvm_flags=%s", omit_if_empty = False)
         launch_info.add(semantics.find_java_runtime_toolchain(ctx).java_home_runfiles_path, format = "jar_bin_path=%s/bin/jar.exe")
    
    From 344df11f54627997e17b12dbbe2538293affa258 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Thu, 7 Aug 2025 07:19:13 -0700
    Subject: [PATCH 306/465] Release `@rules_java` `v8.15.1`
    
    Context: https://github.com/bazelbuild/rules_java/pull/311#issuecomment-3164152220
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 792147204
    Change-Id: Ic881922527848bf51e785cf6d275eebcbe55ab7f
    ---
     MODULE.bazel | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index 6fafb13d..b4b3f762 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -1,6 +1,6 @@
     module(
         name = "rules_java",
    -    version = "8.15.0",
    +    version = "8.15.1",
         bazel_compatibility = [">=6.4.0"],
         compatibility_level = 1,
     )
    
    From e22f29aa1ea4c90ce284845c01c0133ce9d6137d Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Tue, 12 Aug 2025 06:01:50 -0700
    Subject: [PATCH 307/465] Break the `java_helper.bzl` -> `cc_helper.bzl` edge
    
    PiperOrigin-RevId: 794075211
    Change-Id: I7f774b2b3378760e726fabdb0fa79ccf8ab08ea0
    ---
     java/bazel/rules/bazel_java_binary.bzl      |  4 +--
     java/bazel/rules/bazel_java_test.bzl        |  4 +--
     java/common/rules/impl/BUILD                |  1 +
     java/common/rules/impl/java_binary_impl.bzl | 32 +++++++++++++++++++++
     java/common/rules/impl/java_helper.bzl      | 30 +------------------
     5 files changed, 38 insertions(+), 33 deletions(-)
    
    diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl
    index 1e4411e7..de25ab8f 100644
    --- a/java/bazel/rules/bazel_java_binary.bzl
    +++ b/java/bazel/rules/bazel_java_binary.bzl
    @@ -24,12 +24,12 @@ load(
     load("//java/common/rules:java_binary.bzl", "BASIC_JAVA_BINARY_ATTRIBUTES")
     load("//java/common/rules:rule_util.bzl", "merge_attrs")
     load("//java/common/rules/impl:java_binary_deploy_jar.bzl", "create_deploy_archives")
    -load("//java/common/rules/impl:java_binary_impl.bzl", "basic_java_binary")
    +load("//java/common/rules/impl:java_binary_impl.bzl", "basic_java_binary", "binary_provider_helper")
     load("//java/common/rules/impl:java_helper.bzl", "helper")
     load("//java/private:java_info.bzl", "JavaInfo")
     
     def _bazel_java_binary_impl(ctx):
    -    return bazel_base_binary_impl(ctx, is_test_rule_class = False) + helper.executable_providers(ctx)
    +    return bazel_base_binary_impl(ctx, is_test_rule_class = False) + binary_provider_helper.executable_providers(ctx)
     
     def bazel_base_binary_impl(ctx, is_test_rule_class):
         """Common implementation for binaries and tests
    diff --git a/java/bazel/rules/bazel_java_test.bzl b/java/bazel/rules/bazel_java_test.bzl
    index fd3e2bd2..061c058e 100644
    --- a/java/bazel/rules/bazel_java_test.bzl
    +++ b/java/bazel/rules/bazel_java_test.bzl
    @@ -16,11 +16,11 @@
     load("//java/common:java_semantics.bzl", "semantics")
     load("//java/common/rules:java_binary.bzl", "BASE_TEST_ATTRIBUTES")
     load("//java/common/rules:rule_util.bzl", "merge_attrs")
    -load("//java/common/rules/impl:java_helper.bzl", "helper")
    +load("//java/common/rules/impl:java_binary_impl.bzl", "binary_provider_helper")
     load(":bazel_java_binary.bzl", "BASE_BINARY_ATTRS", "bazel_base_binary_impl", "make_binary_rule")
     
     def _bazel_java_test_impl(ctx):
    -    return bazel_base_binary_impl(ctx, is_test_rule_class = True) + helper.test_providers(ctx)
    +    return bazel_base_binary_impl(ctx, is_test_rule_class = True) + binary_provider_helper.test_providers(ctx)
     
     def _java_test_initializer(**kwargs):
         if "stamp" in kwargs and type(kwargs["stamp"]) == type(True):
    diff --git a/java/common/rules/impl/BUILD b/java/common/rules/impl/BUILD
    index 65c5af86..aead3739 100644
    --- a/java/common/rules/impl/BUILD
    +++ b/java/common/rules/impl/BUILD
    @@ -22,6 +22,7 @@ bzl_library(
             ":java_helper_bzl",
             "//java/common:proguard_spec_info_bzl",
             "@com_google_protobuf//bazel/common:proto_info_bzl",
    +        "@rules_cc//cc/common:cc_helper_bzl",
         ],
     )
     
    diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl
    index 15ae89b7..50dcaae9 100644
    --- a/java/common/rules/impl/java_binary_impl.bzl
    +++ b/java/common/rules/impl/java_binary_impl.bzl
    @@ -16,6 +16,7 @@
     
     load("@com_google_protobuf//bazel/common:proto_info.bzl", "ProtoInfo")
     load("@rules_cc//cc/common:cc_common.bzl", "cc_common")
    +load("@rules_cc//cc/common:cc_helper.bzl", "cc_helper")
     load("@rules_cc//cc/common:cc_info.bzl", "CcInfo")
     load("//java/common:java_semantics.bzl", "semantics")
     load("//java/common/rules/impl:basic_java_library_impl.bzl", "basic_java_library", "collect_deps")
    @@ -468,3 +469,34 @@ def _auto_create_deploy_jar(ctx, info, launcher_info, main_class, coverage_main_
             add_opens = info.add_opens,
         )
         return output
    +
    +def _test_providers(ctx):
    +    test_providers = []
    +    if helper.has_target_constraints(ctx, ctx.attr._apple_constraints):
    +        test_providers.append(testing.ExecutionInfo({"requires-darwin": ""}))
    +
    +    test_env = {}
    +    test_env.update(cc_helper.get_expanded_env(ctx, {}))
    +
    +    coverage_config = helper.get_coverage_config(
    +        ctx,
    +        runner = None,  # we only need the environment
    +    )
    +    if coverage_config:
    +        test_env.update(coverage_config.env)
    +    test_providers.append(testing.TestEnvironment(
    +        environment = test_env,
    +        inherited_environment = ctx.attr.env_inherit,
    +    ))
    +
    +    return test_providers
    +
    +def _executable_providers(ctx):
    +    if ctx.attr.create_executable:
    +        return [RunEnvironmentInfo(cc_helper.get_expanded_env(ctx, {}))]
    +    return []
    +
    +binary_provider_helper = struct(
    +    executable_providers = _executable_providers,
    +    test_providers = _test_providers,
    +)
    diff --git a/java/common/rules/impl/java_helper.bzl b/java/common/rules/impl/java_helper.bzl
    index c97d0060..683bf609 100644
    --- a/java/common/rules/impl/java_helper.bzl
    +++ b/java/common/rules/impl/java_helper.bzl
    @@ -17,7 +17,6 @@
     load("@bazel_skylib//lib:paths.bzl", "paths")
     load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cc_toolchain")
     load("@rules_cc//cc/common:cc_common.bzl", "cc_common")
    -load("@rules_cc//cc/common:cc_helper.bzl", "cc_helper")
     load("//java/common:java_semantics.bzl", "semantics")
     
     # copybara: rules_java visibility
    @@ -278,32 +277,6 @@ def _get_test_support(ctx):
             return ctx.attr._test_support
         return None
     
    -def _test_providers(ctx):
    -    test_providers = []
    -    if _has_target_constraints(ctx, ctx.attr._apple_constraints):
    -        test_providers.append(testing.ExecutionInfo({"requires-darwin": ""}))
    -
    -    test_env = {}
    -    test_env.update(cc_helper.get_expanded_env(ctx, {}))
    -
    -    coverage_config = _get_coverage_config(
    -        ctx,
    -        runner = None,  # we only need the environment
    -    )
    -    if coverage_config:
    -        test_env.update(coverage_config.env)
    -    test_providers.append(testing.TestEnvironment(
    -        environment = test_env,
    -        inherited_environment = ctx.attr.env_inherit,
    -    ))
    -
    -    return test_providers
    -
    -def _executable_providers(ctx):
    -    if ctx.attr.create_executable:
    -        return [RunEnvironmentInfo(cc_helper.get_expanded_env(ctx, {}))]
    -    return []
    -
     def _resource_mapper(file):
         root_relative_path = paths.relativize(
             path = file.path,
    @@ -499,8 +472,6 @@ helper = struct(
         is_target_platform_windows = _is_target_platform_windows,
         runfiles_enabled = _runfiles_enabled,
         get_test_support = _get_test_support,
    -    test_providers = _test_providers,
    -    executable_providers = _executable_providers,
         create_single_jar = _create_single_jar,
         shell_escape = _shell_escape,
         detokenize_javacopts = _detokenize_javacopts,
    @@ -508,4 +479,5 @@ helper = struct(
         derive_output_file = _derive_output_file,
         is_stamping_enabled = _is_stamping_enabled,
         get_relative = _get_relative,
    +    has_target_constraints = _has_target_constraints,
     )
    
    From 52aa53a7b7e56a4e545fbda2323db181d3c8ee3d Mon Sep 17 00:00:00 2001
    From: hvadehra 
    Date: Tue, 19 Aug 2025 01:05:45 -0700
    Subject: [PATCH 308/465] Add a module extension for registering local/remote
     jdks (#312)
    
    Closes #312
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/312 from bazelbuild:hvd_java_repos_module_ext d11e12e2eda5b3cfb5e1075d03f095ef5ebe3871
    PiperOrigin-RevId: 796756819
    Change-Id: I7d672490bcb47e64c6dbb2f5138d261bee9fa52d
    ---
     java/extensions.bzl       |  3 ++
     test/repo/BUILD.bazel     |  5 ++++
     test/repo/MODULE.bazel    | 19 +++++++++++++
     test/repo/WORKSPACE       | 18 ++++++++++++
     toolchains/extensions.bzl | 59 +++++++++++++++++++++++++++++++++++++++
     5 files changed, 104 insertions(+)
     create mode 100644 toolchains/extensions.bzl
    
    diff --git a/java/extensions.bzl b/java/extensions.bzl
    index f456f3f5..ad7978b6 100644
    --- a/java/extensions.bzl
    +++ b/java/extensions.bzl
    @@ -23,6 +23,7 @@ load(
         "remote_jdk21_repos",
         "remote_jdk8_repos",
     )
    +load("//toolchains:extensions.bzl", _java_repository = "java_repository")
     
     def _toolchains_impl(module_ctx):
         java_tools_repos()
    @@ -38,3 +39,5 @@ def _toolchains_impl(module_ctx):
             return None
     
     toolchains = module_extension(_toolchains_impl)
    +
    +java_repository = _java_repository
    diff --git a/test/repo/BUILD.bazel b/test/repo/BUILD.bazel
    index ca414395..b0fb6122 100644
    --- a/test/repo/BUILD.bazel
    +++ b/test/repo/BUILD.bazel
    @@ -53,4 +53,9 @@ default_java_toolchain(
         name = "my_funky_toolchain",
         bootclasspath = ["@bazel_tools//tools/jdk:platformclasspath"],
         configuration = NONPREBUILT_TOOLCHAIN_CONFIGURATION,
    +    exec_compatible_with = [
    +        "@platforms//os:linux",
    +        "@platforms//cpu:x86_64",
    +    ],
    +    java_runtime = "@my_funky_jdk//:jdk",
     )
    diff --git a/test/repo/MODULE.bazel b/test/repo/MODULE.bazel
    index 1faec90d..62109333 100644
    --- a/test/repo/MODULE.bazel
    +++ b/test/repo/MODULE.bazel
    @@ -49,6 +49,25 @@ use_repo(
         "remotejdk21_win",
     )
     
    +custom_jdk = use_extension("@rules_java//java:extensions.bzl", "java_repository")
    +custom_jdk.remote(
    +    name = "my_funky_jdk",
    +    prefix = "funky",
    +    strip_prefix = "zulu24.32.13-ca-jdk24.0.2-linux_x64",
    +    target_compatible_with = [
    +        "@platforms//os:linux",
    +        "@platforms//cpu:x86_64",
    +    ],
    +    urls = [
    +        "https://cdn.azul.com/zulu/bin/zulu24.32.13-ca-jdk24.0.2-linux_x64.tar.gz",
    +    ],
    +    version = "24",
    +)
    +use_repo(custom_jdk, "my_funky_jdk", "my_funky_jdk_toolchain_config_repo")
    +
    +register_toolchains("@my_funky_jdk_toolchain_config_repo//:all")
    +
     register_toolchains("//:all")
     
     bazel_dep(name = "rules_shell", version = "0.4.0", dev_dependency = True)
    +bazel_dep(name = "platforms", version = "0.0.11", dev_dependency = True)
    diff --git a/test/repo/WORKSPACE b/test/repo/WORKSPACE
    index c272975e..a6055e26 100644
    --- a/test/repo/WORKSPACE
    +++ b/test/repo/WORKSPACE
    @@ -47,3 +47,21 @@ load("@rules_shell//shell:repositories.bzl", "rules_shell_dependencies", "rules_
     rules_shell_dependencies()
     
     rules_shell_toolchains()
    +
    +load("@rules_java//toolchains:remote_java_repository.bzl", "remote_java_repository")
    +
    +remote_java_repository(
    +    name = "my_funky_jdk",
    +    prefix = "funky",
    +    strip_prefix = "zulu24.32.13-ca-jdk24.0.2-linux_x64",
    +    target_compatible_with = [
    +        "@platforms//os:linux",
    +        "@platforms//cpu:x86_64",
    +    ],
    +    urls = [
    +        "https://cdn.azul.com/zulu/bin/zulu24.32.13-ca-jdk24.0.2-linux_x64.tar.gz",
    +    ],
    +    version = "24",
    +)
    +
    +register_toolchains("@my_funky_jdk_toolchain_config_repo//:all")
    diff --git a/toolchains/extensions.bzl b/toolchains/extensions.bzl
    new file mode 100644
    index 00000000..330c7070
    --- /dev/null
    +++ b/toolchains/extensions.bzl
    @@ -0,0 +1,59 @@
    +"""Module extensions for local and remote java repositories"""
    +
    +load(":local_java_repository.bzl", "local_java_repository")
    +load(":remote_java_repository.bzl", "remote_java_repository")
    +
    +visibility(["//java"])
    +
    +def _java_repository_impl(mctx):
    +    for mod in mctx.modules:
    +        if not mod.is_root:
    +            fail(
    +                """This module extension may only be used in the root module. {name}
    +                must set `dev_dependency` = True on it's usage of this extension,
    +                if {name} can be dependency of other modules.""".format(name = mod.name),
    +            )
    +        for local in mod.tags.local:
    +            local_java_repository(
    +                local.name,
    +                java_home = local.java_home,
    +                version = local.version,
    +                build_file = local.build_file,
    +                build_file_content = local.build_file_content,
    +            )
    +        for remote in mod.tags.remote:
    +            remote_java_repository(
    +                remote.name,
    +                remote.version,
    +                target_compatible_with = remote.target_compatible_with,
    +                prefix = remote.prefix,
    +                sha256 = remote.sha256,
    +                strip_prefix = remote.strip_prefix,
    +                urls = remote.urls,
    +            )
    +
    +_local = tag_class(attrs = {
    +    "name": attr.string(mandatory = True),
    +    "build_file": attr.label(default = None),
    +    "build_file_content": attr.string(default = ""),
    +    "java_home": attr.string(default = ""),
    +    "version": attr.string(default = ""),
    +})
    +
    +_remote = tag_class(attrs = {
    +    "name": attr.string(mandatory = True),
    +    "version": attr.string(mandatory = True),
    +    "urls": attr.string_list(mandatory = True),
    +    "prefix": attr.string(default = ""),
    +    "sha256": attr.string(default = ""),
    +    "strip_prefix": attr.string(default = ""),
    +    "target_compatible_with": attr.string_list(default = []),
    +})
    +
    +java_repository = module_extension(
    +    _java_repository_impl,
    +    tag_classes = {
    +        "local": _local,
    +        "remote": _remote,
    +    },
    +)
    
    From d8744976967245dfab3f6575a64a8d1c21c926b8 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Mon, 1 Sep 2025 06:03:11 -0700
    Subject: [PATCH 309/465] Release `rules_java` `v8.15.2`
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 801782248
    Change-Id: I3b005be33e07803e4e6c92b40bb265b0f1223e2c
    ---
     MODULE.bazel | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index b4b3f762..e4211f31 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -1,6 +1,6 @@
     module(
         name = "rules_java",
    -    version = "8.15.1",
    +    version = "8.15.2",
         bazel_compatibility = [">=6.4.0"],
         compatibility_level = 1,
     )
    
    From 4bd56d5d62c7d9a630928c704262dc0a87614829 Mon Sep 17 00:00:00 2001
    From: Honnix 
    Date: Tue, 2 Sep 2025 04:11:54 -0700
    Subject: [PATCH 310/465] chore: Support remote_file_urls and
     remote_file_integrity in extension (#315)
    
    Closes #314
    
    Closes #315
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/315 from honnix:honnix/remote-file a0c276db08d7268781a3c17b5af6b9fd7f03b741
    PiperOrigin-RevId: 802081702
    Change-Id: I7bd2b082933844eed24570553fdb2fc20f51777c
    ---
     toolchains/extensions.bzl | 4 ++++
     1 file changed, 4 insertions(+)
    
    diff --git a/toolchains/extensions.bzl b/toolchains/extensions.bzl
    index 330c7070..1db0cbc9 100644
    --- a/toolchains/extensions.bzl
    +++ b/toolchains/extensions.bzl
    @@ -27,6 +27,8 @@ def _java_repository_impl(mctx):
                     remote.version,
                     target_compatible_with = remote.target_compatible_with,
                     prefix = remote.prefix,
    +                remote_file_urls = remote.remote_file_urls,
    +                remote_file_integrity = remote.remote_file_integrity,
                     sha256 = remote.sha256,
                     strip_prefix = remote.strip_prefix,
                     urls = remote.urls,
    @@ -45,6 +47,8 @@ _remote = tag_class(attrs = {
         "version": attr.string(mandatory = True),
         "urls": attr.string_list(mandatory = True),
         "prefix": attr.string(default = ""),
    +    "remote_file_urls": attr.string_list_dict(default = {}),
    +    "remote_file_integrity": attr.string_dict(default = {}),
         "sha256": attr.string(default = ""),
         "strip_prefix": attr.string(default = ""),
         "target_compatible_with": attr.string_list(default = []),
    
    From 79073396241f383d012572c7e110b6cabe755a84 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Mon, 8 Sep 2025 01:12:44 -0700
    Subject: [PATCH 311/465] Update `rules_java` CI to use Bazel 8.4.0
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 804312769
    Change-Id: Ib4a59f43e449d12d60f1509e1134e3a3c524f0b4
    ---
     .bazelci/presubmit.yml | 6 +++---
     1 file changed, 3 insertions(+), 3 deletions(-)
    
    diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml
    index 3840395e..796212bf 100644
    --- a/.bazelci/presubmit.yml
    +++ b/.bazelci/presubmit.yml
    @@ -47,7 +47,7 @@ buildifier: latest
     
     matrix:
       all_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"]
    -  bazel: ["7.6.1", "8.3.0", "last_green"] # Bazel 6 tested separately, needs different flags
    +  bazel: ["7.6.1", "8.4.0", "last_green"] # Bazel 6 tested separately, needs different flags
       modern_bazel: ["last_green"] # Fully supported Bazel versions
     
     tasks:
    @@ -60,8 +60,8 @@ tasks:
         test_targets: *test_targets
     # Bazel 8.x
       build_and_test_bazel8:
    -    name: "Bazel 8.3.0"
    -    bazel: "8.3.0"
    +    name: "Bazel 8.4.0"
    +    bazel: "8.4.0"
         platform: ${{ all_platforms }}
         build_targets: *build_targets
         test_targets: *test_targets
    
    From 6f74e94b5df3d8de190e6bcd3750f95e278ab3ef Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 10 Sep 2025 06:18:50 -0700
    Subject: [PATCH 312/465] Run `@rules_java` CI on rolling Bazel releases
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 805331268
    Change-Id: I785f5568e335aabb5896a01520dab9c83874c56b
    ---
     .bazelci/presubmit.yml | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml
    index 796212bf..7357c253 100644
    --- a/.bazelci/presubmit.yml
    +++ b/.bazelci/presubmit.yml
    @@ -48,7 +48,7 @@ buildifier: latest
     matrix:
       all_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"]
       bazel: ["7.6.1", "8.4.0", "last_green"] # Bazel 6 tested separately, needs different flags
    -  modern_bazel: ["last_green"] # Fully supported Bazel versions
    +  modern_bazel: ["last_green", "rolling"] # Fully supported Bazel versions
     
     tasks:
     # Bazel 9+
    
    From faaab4062f81deefaeef76dd21b2a5212432f8e3 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Thu, 11 Sep 2025 05:46:41 -0700
    Subject: [PATCH 313/465] Use `@bazel_features` for rules_java compatibility
     proxy
    
    The previous check would have eventually broken with Bazel 10.
    
    PiperOrigin-RevId: 805798844
    Change-Id: I4ea5d594f0e370d7d3b7568d54626944fe8f1923
    ---
     WORKSPACE                | 13 ++++++++++---
     distro/relnotes.bzl      | 11 +++++++++--
     java/rules_java_deps.bzl | 15 ++-------------
     test/repo/WORKSPACE      | 15 +++++++++++----
     4 files changed, 32 insertions(+), 22 deletions(-)
    
    diff --git a/WORKSPACE b/WORKSPACE
    index acd7cae0..475e9ef8 100644
    --- a/WORKSPACE
    +++ b/WORKSPACE
    @@ -37,14 +37,21 @@ http_archive(
         ],
     )
     
    -load("//java:rules_java_deps.bzl", "rules_java_dependencies")
    -
    -rules_java_dependencies()
    +http_archive(
    +    name = "bazel_features",
    +    sha256 = "a660027f5a87f13224ab54b8dc6e191693c554f2692fcca46e8e29ee7dabc43b",
    +    strip_prefix = "bazel_features-1.30.0",
    +    url = "https://github.com/bazel-contrib/bazel_features/releases/download/v1.30.0/bazel_features-v1.30.0.tar.gz",
    +)
     
     load("@bazel_features//:deps.bzl", "bazel_features_deps")
     
     bazel_features_deps()
     
    +load("//java:rules_java_deps.bzl", "rules_java_dependencies")
    +
    +rules_java_dependencies()
    +
     load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_bazel_features")  # buildifier: disable=bzl-visibility
     
     proto_bazel_features(name = "proto_bazel_features")
    diff --git a/distro/relnotes.bzl b/distro/relnotes.bzl
    index ce04d501..9d76230a 100644
    --- a/distro/relnotes.bzl
    +++ b/distro/relnotes.bzl
    @@ -38,12 +38,19 @@ http_archive(
         sha256 = "$$sha",
     )
     
    -load("@rules_java//java:rules_java_deps.bzl", "rules_java_dependencies")
    -rules_java_dependencies()
    +http_archive(
    +    name = "bazel_features",
    +    sha256 = "a660027f5a87f13224ab54b8dc6e191693c554f2692fcca46e8e29ee7dabc43b",
    +    strip_prefix = "bazel_features-1.30.0",
    +    url = "https://github.com/bazel-contrib/bazel_features/releases/download/v1.30.0/bazel_features-v1.30.0.tar.gz",
    +)
     
     load("@bazel_features//:deps.bzl", "bazel_features_deps")
     bazel_features_deps()
     
    +load("@rules_java//java:rules_java_deps.bzl", "rules_java_dependencies")
    +rules_java_dependencies()
    +
     # note that the following line is what is minimally required from protobuf for the java rules
     # consider using the protobuf_deps() public API from @com_google_protobuf//:protobuf_deps.bzl
     load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_bazel_features")  # buildifier: disable=bzl-visibility
    diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl
    index b32edd24..1eb28492 100644
    --- a/java/rules_java_deps.bzl
    +++ b/java/rules_java_deps.bzl
    @@ -1,12 +1,11 @@
     """Module extension for compatibility with previous Bazel versions"""
     
    +load("@bazel_features//private:util.bzl", _bazel_version_ge = "ge")
     load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
     load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
     
     def _compatibility_proxy_repo_impl(rctx):
    -    # TODO: use @bazel_features
    -    bazel = native.bazel_version
    -    if not bazel or bazel >= "8":
    +    if _bazel_version_ge("8.0.0"):
             rctx.file(
                 "BUILD.bazel",
                 """
    @@ -210,15 +209,6 @@ def rules_license_repo():
             ],
         )
     
    -def bazel_features_repo():
    -    maybe(
    -        http_archive,
    -        name = "bazel_features",
    -        sha256 = "a660027f5a87f13224ab54b8dc6e191693c554f2692fcca46e8e29ee7dabc43b",
    -        strip_prefix = "bazel_features-1.30.0",
    -        url = "https://github.com/bazel-contrib/bazel_features/releases/download/v1.30.0/bazel_features-v1.30.0.tar.gz",
    -    )
    -
     def rules_java_dependencies():
         """An utility method to load non-toolchain dependencies of rules_java.
     
    @@ -232,4 +222,3 @@ def rules_java_dependencies():
         zlib_repo()
         absl_repo()
         rules_license_repo()
    -    bazel_features_repo()
    diff --git a/test/repo/WORKSPACE b/test/repo/WORKSPACE
    index a6055e26..32cadb59 100644
    --- a/test/repo/WORKSPACE
    +++ b/test/repo/WORKSPACE
    @@ -5,14 +5,23 @@ local_repository(
         path = "../../",
     )
     
    -load("@rules_java//java:rules_java_deps.bzl", "rules_java_dependencies")
    +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
     
    -rules_java_dependencies()
    +http_archive(
    +    name = "bazel_features",
    +    sha256 = "a660027f5a87f13224ab54b8dc6e191693c554f2692fcca46e8e29ee7dabc43b",
    +    strip_prefix = "bazel_features-1.30.0",
    +    url = "https://github.com/bazel-contrib/bazel_features/releases/download/v1.30.0/bazel_features-v1.30.0.tar.gz",
    +)
     
     load("@bazel_features//:deps.bzl", "bazel_features_deps")
     
     bazel_features_deps()
     
    +load("@rules_java//java:rules_java_deps.bzl", "rules_java_dependencies")
    +
    +rules_java_dependencies()
    +
     load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_bazel_features")  # buildifier: disable=bzl-visibility
     
     proto_bazel_features(name = "proto_bazel_features")
    @@ -33,8 +42,6 @@ http_jar(
         ],
     )
     
    -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
    -
     http_archive(
         name = "rules_shell",
         sha256 = "3e114424a5c7e4fd43e0133cc6ecdfe54e45ae8affa14fadd839f29901424043",
    
    From 0423b071e1b183b55f35a0af02d9cd578e88b9e8 Mon Sep 17 00:00:00 2001
    From: Fabian Meumertzheim 
    Date: Mon, 22 Sep 2025 07:49:34 -0700
    Subject: [PATCH 314/465] Fix CI failures with last_green (#321)
    
    Closes #321
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/321 from fmeum:patch-3 bfde788dea60116dce574168a5c7cec98f5395ae
    PiperOrigin-RevId: 810011421
    Change-Id: I7d91fa12565fe856de8dbfcefb8f640fb6814f24
    ---
     MODULE.bazel                               |  29 +++-
     third_party/BUILD                          |   0
     third_party/abseil-cpp_load-cc-rules.patch |  36 +++++
     third_party/protobuf_load-cc-rules.patch   | 157 +++++++++++++++++++++
     4 files changed, 217 insertions(+), 5 deletions(-)
     create mode 100644 third_party/BUILD
     create mode 100644 third_party/abseil-cpp_load-cc-rules.patch
     create mode 100644 third_party/protobuf_load-cc-rules.patch
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index e4211f31..942c1bb2 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -6,15 +6,34 @@ module(
     )
     
     bazel_dep(name = "platforms", version = "0.0.11")
    -bazel_dep(name = "rules_cc", version = "0.0.15")
    +bazel_dep(name = "rules_cc", version = "0.2.8")
     bazel_dep(name = "bazel_features", version = "1.30.0")
     bazel_dep(name = "bazel_skylib", version = "1.6.1")
    -bazel_dep(name = "protobuf", version = "27.0", repo_name = "com_google_protobuf")
    +bazel_dep(name = "protobuf", version = "32.1", repo_name = "com_google_protobuf")
     bazel_dep(name = "zlib", version = "1.3.1.bcr.5")
     
     # Required by @remote_java_tools, which is loaded via module extension.
     bazel_dep(name = "rules_license", version = "0.0.3")
    -bazel_dep(name = "abseil-cpp", version = "20230802.1", repo_name = "com_google_absl")
    +bazel_dep(name = "abseil-cpp", version = "20250814.0", repo_name = "com_google_absl")
    +
    +# TODO: Remove this override after the next release of abseil-cpp.
    +single_version_override(
    +    module_name = "abseil-cpp",
    +    patch_strip = 1,
    +    patches = [
    +        "//third_party:abseil-cpp_load-cc-rules.patch",
    +    ],
    +    version = "20250814.0",
    +)
    +
    +single_version_override(
    +    module_name = "protobuf",
    +    patch_strip = 1,
    +    patches = [
    +        "//third_party:protobuf_load-cc-rules.patch",
    +    ],
    +    version = "32.1",
    +)
     
     register_toolchains("//toolchains:all")
     
    @@ -97,9 +116,9 @@ use_repo(compat, "compatibility_proxy")
     
     # Dev dependencies
     bazel_dep(name = "rules_pkg", version = "0.9.1", dev_dependency = True)
    -bazel_dep(name = "stardoc", version = "0.7.1", dev_dependency = True)
    +bazel_dep(name = "stardoc", version = "0.8.0", dev_dependency = True)
     bazel_dep(name = "rules_shell", version = "0.2.0", dev_dependency = True)
    -bazel_dep(name = "rules_testing", version = "0.7.0", dev_dependency = True)
    +bazel_dep(name = "rules_testing", dev_dependency = True)
     archive_override(
         module_name = "rules_testing",
         integrity = "sha256-0+3pLjeZCqn+K1qS7HNr7HbwMXBjxLvJm+pMSUhDel8=",
    diff --git a/third_party/BUILD b/third_party/BUILD
    new file mode 100644
    index 00000000..e69de29b
    diff --git a/third_party/abseil-cpp_load-cc-rules.patch b/third_party/abseil-cpp_load-cc-rules.patch
    new file mode 100644
    index 00000000..e3dfe2bb
    --- /dev/null
    +++ b/third_party/abseil-cpp_load-cc-rules.patch
    @@ -0,0 +1,36 @@
    +From 2370ccf579bd0fb4484c343389b8121c6b7f9bb8 Mon Sep 17 00:00:00 2001
    +From: Keith Smiley 
    +Date: Sat, 20 Sep 2025 20:02:06 -0700
    +Subject: [PATCH] PR #1939: Add missing rules_cc loads
    +
    +Imported from GitHub PR https://github.com/abseil/abseil-cpp/pull/1939
    +
    +This is required for use with bazel past this commit: https://github.com/bazelbuild/bazel/commit/71ca0ed111ff3d842a0d23bc3a46bd2e6745491d
    +
    +Most files do this already these were just missing
    +
    +Merge f7d58947afdb0549c9e5c287a5e5851a7d72e1e0 into 620d600442769b7ec4b61bd87667899908eec4ef
    +
    +Merging this change closes #1939
    +
    +COPYBARA_INTEGRATE_REVIEW=https://github.com/abseil/abseil-cpp/pull/1939 from keith:ks/add-missing-rules_cc-loads f7d58947afdb0549c9e5c287a5e5851a7d72e1e0
    +PiperOrigin-RevId: 809556509
    +Change-Id: I494a118b851685a03393485514a3b6fbe3a10597
    +---
    + absl/debugging/BUILD.bazel | 3 +++
    + 1 file changed, 3 insertions(+)
    +
    +diff --git a/absl/debugging/BUILD.bazel b/absl/debugging/BUILD.bazel
    +index ed7cc493e90..7cc053e783e 100644
    +--- a/absl/debugging/BUILD.bazel
    ++++ b/absl/debugging/BUILD.bazel
    +@@ -14,6 +14,9 @@
    + # limitations under the License.
    + #
    + 
    ++load("@rules_cc//cc:cc_binary.bzl", "cc_binary")
    ++load("@rules_cc//cc:cc_library.bzl", "cc_library")
    ++load("@rules_cc//cc:cc_test.bzl", "cc_test")
    + load(
    +     "//absl:copts/configure_copts.bzl",
    +     "ABSL_DEFAULT_COPTS",
    diff --git a/third_party/protobuf_load-cc-rules.patch b/third_party/protobuf_load-cc-rules.patch
    new file mode 100644
    index 00000000..09bd7025
    --- /dev/null
    +++ b/third_party/protobuf_load-cc-rules.patch
    @@ -0,0 +1,157 @@
    +Backported from https://github.com/protocolbuffers/protobuf/pull/23584 to 32.0:
    +
    +From 733a0ccf6f53f469352b19440a1d152eccea6bec Mon Sep 17 00:00:00 2001
    +From: Keith Smiley 
    +Date: Sat, 20 Sep 2025 09:30:37 -0700
    +Subject: [PATCH] bazel: add missing rules_cc loads
    +
    +This is required for use with bazel after this commit https://github.com/bazelbuild/bazel/commit/71ca0ed111ff3d842a0d23bc3a46bd2e6745491d
    +
    +Many files have these already
    +---
    + lua/BUILD.bazel                                    | 3 +++
    + pkg/test/BUILD.bazel                               | 1 +
    + ruby/ext/google/protobuf_c/BUILD.bazel             | 1 +
    + ruby/lib/google/BUILD.bazel                        | 1 +
    + rust/defs.bzl                                      | 1 +
    + src/google/protobuf/compiler/cpp/BUILD.bazel       | 1 +
    + src/google/protobuf/compiler/java/full/BUILD.bazel | 1 +
    + src/google/protobuf/compiler/java/lite/BUILD.bazel | 1 +
    + src/google/protobuf/compiler/kotlin/BUILD.bazel    | 1 +
    + src/google/protobuf/compiler/php/BUILD.bazel       | 1 +
    + src/google/protobuf/compiler/rust/BUILD.bazel      | 2 ++
    + toolchain/BUILD.bazel                              | 2 ++
    + 12 files changed, 16 insertions(+)
    +
    +diff --git a/lua/BUILD.bazel b/lua/BUILD.bazel
    +index 389e5da7635ca..db956713bd849 100644
    +--- a/lua/BUILD.bazel
    ++++ b/lua/BUILD.bazel
    +@@ -5,6 +5,9 @@
    + # license that can be found in the LICENSE file or at
    + # https://developers.google.com/open-source/licenses/bsd
    + 
    ++load("@rules_cc//cc:cc_binary.bzl", "cc_binary")
    ++load("@rules_cc//cc:cc_library.bzl", "cc_library")
    ++load("@rules_cc//cc:cc_test.bzl", "cc_test")
    + load("//bazel:proto_library.bzl", "proto_library")
    + load(
    +     "//lua:lua_proto_library.bzl",
    +diff --git a/pkg/test/BUILD.bazel b/pkg/test/BUILD.bazel
    +index d0954f0126ba2..4fd01c9759643 100644
    +--- a/pkg/test/BUILD.bazel
    ++++ b/pkg/test/BUILD.bazel
    +@@ -1,5 +1,6 @@
    + # Tests for CMake file list generation
    + 
    ++load("@rules_cc//cc:cc_library.bzl", "cc_library")
    + load("@rules_shell//shell:sh_test.bzl", "sh_test")
    + load("//pkg:build_systems.bzl", "gen_file_lists")
    + load("//pkg:cc_dist_library.bzl", "cc_dist_library")
    +diff --git a/ruby/ext/google/protobuf_c/BUILD.bazel b/ruby/ext/google/protobuf_c/BUILD.bazel
    +index 00458e2eedbe4..63276d538cc5c 100644
    +--- a/ruby/ext/google/protobuf_c/BUILD.bazel
    ++++ b/ruby/ext/google/protobuf_c/BUILD.bazel
    +@@ -1,4 +1,5 @@
    + load("@build_bazel_rules_apple//apple:apple_binary.bzl", "apple_binary")
    ++load("@rules_cc//cc:cc_library.bzl", "cc_library")
    + load("@rules_pkg//pkg:mappings.bzl", "pkg_files", "strip_prefix")
    + load("//upb/cmake:build_defs.bzl", "staleness_test")
    + 
    +diff --git a/ruby/lib/google/BUILD.bazel b/ruby/lib/google/BUILD.bazel
    +index db0d7cd6b89bc..157df81b6d734 100644
    +--- a/ruby/lib/google/BUILD.bazel
    ++++ b/ruby/lib/google/BUILD.bazel
    +@@ -1,3 +1,4 @@
    ++load("@rules_cc//cc:cc_binary.bzl", "cc_binary")
    + load("@rules_java//java:java_binary.bzl", "java_binary")
    + load("@rules_pkg//pkg:mappings.bzl", "pkg_files", "strip_prefix")
    + load("@rules_ruby//ruby:defs.bzl", "rb_library")
    +diff --git a/rust/defs.bzl b/rust/defs.bzl
    +index b787d108fc743..54dab26e25048 100644
    +--- a/rust/defs.bzl
    ++++ b/rust/defs.bzl
    +@@ -1,4 +1,5 @@
    + """This file implements rust_proto_library."""
    + 
    ++load("@rules_cc//cc/common:cc_info.bzl", "CcInfo")
    + load("@rules_rust//rust:defs.bzl", "rust_common")
    + load("//bazel/common:proto_common.bzl", "proto_common")
    +diff --git a/src/google/protobuf/compiler/cpp/BUILD.bazel b/src/google/protobuf/compiler/cpp/BUILD.bazel
    +index 4d4e99d774772..ced92c04e235d 100644
    +--- a/src/google/protobuf/compiler/cpp/BUILD.bazel
    ++++ b/src/google/protobuf/compiler/cpp/BUILD.bazel
    +@@ -2,6 +2,7 @@
    + # Protocol Buffers Compiler - C++ code generator
    + ################################################################################
    + 
    ++load("@rules_cc//cc:cc_binary.bzl", "cc_binary")
    + load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
    + load("@rules_pkg//pkg:mappings.bzl", "pkg_files", "strip_prefix")
    + load("//bazel:cc_proto_library.bzl", "cc_proto_library")
    +diff --git a/src/google/protobuf/compiler/java/full/BUILD.bazel b/src/google/protobuf/compiler/java/full/BUILD.bazel
    +index 6bffaa10fbc87..54b4ae9cd186d 100644
    +--- a/src/google/protobuf/compiler/java/full/BUILD.bazel
    ++++ b/src/google/protobuf/compiler/java/full/BUILD.bazel
    +@@ -1,6 +1,7 @@
    + # We use abbreviated target names in this directory to work around:
    + #     https://github.com/bazelbuild/bazel/issues/18683
    + 
    ++load("@rules_cc//cc:cc_library.bzl", "cc_library")
    + load("//build_defs:cpp_opts.bzl", "COPTS")
    + 
    + cc_library(
    +diff --git a/src/google/protobuf/compiler/java/lite/BUILD.bazel b/src/google/protobuf/compiler/java/lite/BUILD.bazel
    +index 02af1b3f917df..5e04135abbac0 100644
    +--- a/src/google/protobuf/compiler/java/lite/BUILD.bazel
    ++++ b/src/google/protobuf/compiler/java/lite/BUILD.bazel
    +@@ -1,3 +1,4 @@
    ++load("@rules_cc//cc:cc_library.bzl", "cc_library")
    + load("//build_defs:cpp_opts.bzl", "COPTS")
    + 
    + cc_library(
    +diff --git a/src/google/protobuf/compiler/kotlin/BUILD.bazel b/src/google/protobuf/compiler/kotlin/BUILD.bazel
    +index 4f866ae02e1b7..5a1e1b727092b 100644
    +--- a/src/google/protobuf/compiler/kotlin/BUILD.bazel
    ++++ b/src/google/protobuf/compiler/kotlin/BUILD.bazel
    +@@ -1,3 +1,4 @@
    ++load("@rules_cc//cc:cc_library.bzl", "cc_library")
    + load("//build_defs:cpp_opts.bzl", "COPTS")
    + 
    + cc_library(
    +diff --git a/src/google/protobuf/compiler/php/BUILD.bazel b/src/google/protobuf/compiler/php/BUILD.bazel
    +index 930db4476125b..d41fe6d122adb 100644
    +--- a/src/google/protobuf/compiler/php/BUILD.bazel
    ++++ b/src/google/protobuf/compiler/php/BUILD.bazel
    +@@ -2,6 +2,7 @@
    + # Protocol Buffers Compiler - PHP code generator
    + ################################################################################
    + 
    ++load("@rules_cc//cc:cc_test.bzl", "cc_test")
    + load("@rules_cc//cc:defs.bzl", "cc_library")
    + load("@rules_pkg//pkg:mappings.bzl", "pkg_files", "strip_prefix")
    + load("//build_defs:cpp_opts.bzl", "COPTS")
    +diff --git a/src/google/protobuf/compiler/rust/BUILD.bazel b/src/google/protobuf/compiler/rust/BUILD.bazel
    +index e5766c2abd40b..116e44b76df9c 100644
    +--- a/src/google/protobuf/compiler/rust/BUILD.bazel
    ++++ b/src/google/protobuf/compiler/rust/BUILD.bazel
    +@@ -9,6 +9,8 @@
    + # Protocol Buffers Compiler - Rust code generator
    + ################################################################################
    + 
    ++load("@rules_cc//cc:cc_binary.bzl", "cc_binary")
    ++load("@rules_cc//cc:cc_test.bzl", "cc_test")
    + load("@rules_cc//cc:defs.bzl", "cc_library")
    + load("//build_defs:cpp_opts.bzl", "COPTS")
    + load(
    +diff --git a/toolchain/BUILD.bazel b/toolchain/BUILD.bazel
    +index 524fa14390501..4cb056c75ff66 100644
    +--- a/toolchain/BUILD.bazel
    ++++ b/toolchain/BUILD.bazel
    +@@ -1,4 +1,6 @@
    + load("@bazel_skylib//rules:common_settings.bzl", "bool_flag")
    ++load("@rules_cc//cc/toolchains:cc_toolchain.bzl", "cc_toolchain")
    ++load("@rules_cc//cc/toolchains:cc_toolchain_suite.bzl", "cc_toolchain_suite")
    + load(":cc_toolchain_config.bzl", "cc_toolchain_config")
    + 
    + package(default_visibility = ["//visibility:public"])
    
    From 7a625caa6c06e5caa522f6402ec4ab2787307655 Mon Sep 17 00:00:00 2001
    From: Fabian Meumertzheim 
    Date: Mon, 22 Sep 2025 08:05:51 -0700
    Subject: [PATCH 315/465] Add JDK 25 (#319)
    
    Closes #319
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/319 from fmeum:jdk-25 ddc4341c58485a94f3d9882e7afb56f0b9f16a74
    PiperOrigin-RevId: 810016900
    Change-Id: Icecc0ee3056f1ac357ad92b46c5509403c42adb1
    ---
     MODULE.bazel                     |  8 +++++
     java/bazel/repositories_util.bzl | 10 ++++++
     java/extensions.bzl              |  2 ++
     java/repositories.bzl            | 53 ++++++++++++++++++++++++++++++++
     toolchains/BUILD                 | 10 ++++--
     5 files changed, 81 insertions(+), 2 deletions(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index 942c1bb2..ea1496b0 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -99,6 +99,14 @@ JDKS = {
             "win",
             "win_arm64",
         ],
    +    "25": [
    +        "linux",
    +        "linux_aarch64",
    +        "macos",
    +        "macos_aarch64",
    +        "win",
    +        "win_arm64",
    +    ],
     }
     
     REMOTE_JDK_REPOS = [(("remote_jdk" if version == "8" else "remotejdk") + version + "_" + platform) for version in JDKS for platform in JDKS[version]]
    diff --git a/java/bazel/repositories_util.bzl b/java/bazel/repositories_util.bzl
    index 38170c13..5b05fb2e 100644
    --- a/java/bazel/repositories_util.bzl
    +++ b/java/bazel/repositories_util.bzl
    @@ -86,6 +86,16 @@ _RELEASE_CONFIGS = {
                 },
             },
         },
    +    "25": {
    +        "zulu": {
    +            "release": "25.28.85-ca-jdk25.0.0",
    +            "platforms": {
    +                "linux": ["aarch64", "x86_64"],
    +                "macos": ["aarch64", "x86_64"],
    +                "windows": ["arm64", "x86_64"],
    +            },
    +        },
    +    },
     }
     
     _STRIP_PREFIX_OVERRIDES = {
    diff --git a/java/extensions.bzl b/java/extensions.bzl
    index ad7978b6..a791d179 100644
    --- a/java/extensions.bzl
    +++ b/java/extensions.bzl
    @@ -21,6 +21,7 @@ load(
         "remote_jdk11_repos",
         "remote_jdk17_repos",
         "remote_jdk21_repos",
    +    "remote_jdk25_repos",
         "remote_jdk8_repos",
     )
     load("//toolchains:extensions.bzl", _java_repository = "java_repository")
    @@ -32,6 +33,7 @@ def _toolchains_impl(module_ctx):
         remote_jdk11_repos()
         remote_jdk17_repos()
         remote_jdk21_repos()
    +    remote_jdk25_repos()
     
         if bazel_features.external_deps.extension_metadata_has_reproducible:
             return module_ctx.extension_metadata(reproducible = True)
    diff --git a/java/repositories.bzl b/java/repositories.bzl
    index 2af22140..09da2ce6 100644
    --- a/java/repositories.bzl
    +++ b/java/repositories.bzl
    @@ -325,6 +325,54 @@ _REMOTE_JDK_CONFIGS_LIST = [
             urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.6_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.6_7.tar.gz"],
             version = "21",
         ),
    +    struct(
    +        name = "remotejdk25_linux_aarch64",
    +        target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"],
    +        sha256 = "b60eb9d54c97ba4159547834a98cc5d016281dd2b3e60e7475cba4911324bcb4",
    +        strip_prefix = "zulu25.28.85-ca-jdk25.0.0-linux_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-linux_aarch64.tar.gz"],
    +        version = "25",
    +    ),
    +    struct(
    +        name = "remotejdk25_linux",
    +        target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"],
    +        sha256 = "164d901e5a240b8c18516f5ab55bc11fc9689ab6e829045aea8467356dcdb340",
    +        strip_prefix = "zulu25.28.85-ca-jdk25.0.0-linux_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-linux_x64.tar.gz"],
    +        version = "25",
    +    ),
    +    struct(
    +        name = "remotejdk25_macos_aarch64",
    +        target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"],
    +        sha256 = "73f64f6bad7c3df31fba740fbcbbbef7c1a5cedeffbb5df386dd79bc72aba9b6",
    +        strip_prefix = "zulu25.28.85-ca-jdk25.0.0-macosx_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-macosx_aarch64.tar.gz"],
    +        version = "25",
    +    ),
    +    struct(
    +        name = "remotejdk25_macos",
    +        target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"],
    +        sha256 = "c2cde1d313d904b793c3760214eefa207ecca7df04e7c4084abdf1f6bbebc27a",
    +        strip_prefix = "zulu25.28.85-ca-jdk25.0.0-macosx_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-macosx_x64.tar.gz"],
    +        version = "25",
    +    ),
    +    struct(
    +        name = "remotejdk25_win_arm64",
    +        target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"],
    +        sha256 = "f5f6d8a913695649e8e2607fe0dc79c81953b2583013ac1fb977c63cb4935bfb",
    +        strip_prefix = "zulu25.28.85-ca-jdk25.0.0-win_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-win_aarch64.zip"],
    +        version = "25",
    +    ),
    +    struct(
    +        name = "remotejdk25_win",
    +        target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"],
    +        sha256 = "5efcf4e6a613cae06c8041de8a3695b7346aad0307d397b66bf55281cf1a5cb6",
    +        strip_prefix = "zulu25.28.85-ca-jdk25.0.0-win_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-win_x64.zip"],
    +        version = "25",
    +    ),
     ]
     
     def _make_version_to_remote_jdks():
    @@ -369,6 +417,10 @@ def remote_jdk21_repos():
         """Imports OpenJDK 21 repositories."""
         _remote_jdk_repos_for_version("21")
     
    +def remote_jdk25_repos():
    +    """Imports OpenJDK 25 repositories."""
    +    _remote_jdk_repos_for_version("25")
    +
     def rules_java_dependencies():
         """DEPRECATED: No-op, kept for backwards compatibility"""
         print("DEPRECATED: use rules_java_dependencies() from rules_java_deps.bzl")  # buildifier: disable=print
    @@ -384,6 +436,7 @@ def rules_java_toolchains(name = "toolchains"):
         remote_jdk11_repos()
         remote_jdk17_repos()
         remote_jdk21_repos()
    +    remote_jdk25_repos()
         java_tools_repos()
     
         native.register_toolchains(
    diff --git a/toolchains/BUILD b/toolchains/BUILD
    index 9a1b2d33..d6d18bcc 100644
    --- a/toolchains/BUILD
    +++ b/toolchains/BUILD
    @@ -353,12 +353,12 @@ alias(
         actual = ":toolchain",
     )
     
    -RELEASES = (8, 9, 10, 11, 17, 21)
    +RELEASES = (8, 9, 10, 11, 17, 21, 25)
     
     [
         default_java_toolchain(
             name = ("toolchain_java%d" if release <= 11 else "toolchain_jdk_%d") % release,
    -        configuration = DEFAULT_TOOLCHAIN_CONFIGURATION,
    +        configuration = DEFAULT_TOOLCHAIN_CONFIGURATION if release <= 21 else DEFAULT_TOOLCHAIN_CONFIGURATION | {"java_runtime": ":remotejdk_%d" % release},
             source_version = "%s" % release,
             target_version = "%s" % release,
         )
    @@ -390,6 +390,12 @@ java_runtime_version_alias(
         visibility = ["//visibility:public"],
     )
     
    +java_runtime_version_alias(
    +    name = "remotejdk_25",
    +    runtime_version = "remotejdk_25",
    +    visibility = ["//visibility:public"],
    +)
    +
     java_runtime_version_alias(
         name = "jdk_8",
         runtime_version = "8",
    
    From 1ee3e3508f99c81c94afac75cf25cb14977b0b56 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Tue, 23 Sep 2025 03:03:03 -0700
    Subject: [PATCH 316/465] Release `@rules_java` `v8.16.0`
    
    PiperOrigin-RevId: 810363784
    Change-Id: I78a3ac45c37dd4f71047ab7f10e287d2a8700573
    ---
     MODULE.bazel | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index ea1496b0..adf1f140 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -1,6 +1,6 @@
     module(
         name = "rules_java",
    -    version = "8.15.2",
    +    version = "8.16.0",
         bazel_compatibility = [">=6.4.0"],
         compatibility_level = 1,
     )
    
    From 39cae30eea61d30ac6bbb5358d964cab059aa590 Mon Sep 17 00:00:00 2001
    From: Fabian Meumertzheim 
    Date: Tue, 23 Sep 2025 05:27:59 -0700
    Subject: [PATCH 317/465] Update the compilation JDK to 25 (#323)
    
    This is necessary to support `--java_runtime_version=remotejdk_25` with lower `--java_language_version` values. JDK 21 already showed warnings when targeting Java 8.
    
    Closes #323
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/323 from fmeum:jdk-25-default 8ab1d01eac01fcb221af113ede41fc7cdbac2581
    PiperOrigin-RevId: 810400625
    Change-Id: Id7b66c2a737f28b09316077a338ec9dd0e1928e1
    ---
     toolchains/BUILD                      | 2 +-
     toolchains/default_java_toolchain.bzl | 2 ++
     2 files changed, 3 insertions(+), 1 deletion(-)
    
    diff --git a/toolchains/BUILD b/toolchains/BUILD
    index d6d18bcc..3209930b 100644
    --- a/toolchains/BUILD
    +++ b/toolchains/BUILD
    @@ -358,7 +358,7 @@ RELEASES = (8, 9, 10, 11, 17, 21, 25)
     [
         default_java_toolchain(
             name = ("toolchain_java%d" if release <= 11 else "toolchain_jdk_%d") % release,
    -        configuration = DEFAULT_TOOLCHAIN_CONFIGURATION if release <= 21 else DEFAULT_TOOLCHAIN_CONFIGURATION | {"java_runtime": ":remotejdk_%d" % release},
    +        configuration = DEFAULT_TOOLCHAIN_CONFIGURATION | {"java_runtime": ":remotejdk_25"},
             source_version = "%s" % release,
             target_version = "%s" % release,
         )
    diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl
    index 4ec8961a..4f463937 100644
    --- a/toolchains/default_java_toolchain.bzl
    +++ b/toolchains/default_java_toolchain.bzl
    @@ -98,6 +98,8 @@ _BASE_TOOLCHAIN_CONFIGURATION = dict(
         reduced_classpath_incompatible_processors = [
             "dagger.hilt.processor.internal.root.RootProcessor",  # see b/21307381
         ],
    +    # TODO: Update to JDK 25 after some time has passed - it no longer supports
    +    # targeting JDK 7.
         java_runtime = Label("//toolchains:remotejdk_21"),
         oneversion = Label("//toolchains:one_version"),
     )
    
    From ff92bd1d0c8e73f6af04075f838b7b905391e22e Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Tue, 23 Sep 2025 06:01:17 -0700
    Subject: [PATCH 318/465] Release `@rules_java` `v8.16.1`
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 810408757
    Change-Id: I0edd49b8efc9238303752f3b1f348d5f95111604
    ---
     MODULE.bazel | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index adf1f140..f900a930 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -1,6 +1,6 @@
     module(
         name = "rules_java",
    -    version = "8.16.0",
    +    version = "8.16.1",
         bazel_compatibility = [">=6.4.0"],
         compatibility_level = 1,
     )
    
    From ebfccdfef2ff740b16b0b2502bc49b3a8a36050d Mon Sep 17 00:00:00 2001
    From: Benjamin Peterson 
    Date: Wed, 24 Sep 2025 02:48:45 -0700
    Subject: [PATCH 319/465] add some useful flags to the remotejdk fetching curl
     (#320)
    
    Closes #320
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/320 from benjaminp:curl-flags 8e1e447c523659ca5a6a49a18413470397294934
    PiperOrigin-RevId: 810796608
    Change-Id: Iece85dba3804699bacec260da807b6486ca4888b
    ---
     java/bazel/BUILD.bazel | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/java/bazel/BUILD.bazel b/java/bazel/BUILD.bazel
    index 68b3c1f1..225628e8 100644
    --- a/java/bazel/BUILD.bazel
    +++ b/java/bazel/BUILD.bazel
    @@ -29,7 +29,7 @@ while read -r config; do
         TMP_FILE=$$(mktemp -q /tmp/remotejdk.XXXXXX)
         IFS=\\| read -r name version urls strip_prefix target_compatible_with primary_url <<< "$$config"
         echo "fetching: $$primary_url to $$TMP_FILE" > /dev/stderr
    -    curl --silent --fail -o $$TMP_FILE -L "$$primary_url" > /dev/stderr
    +    curl --retry 5 --write-out '%{{onerror}}%{{url}}\n' --show-error --silent --fail -o $$TMP_FILE -L "$$primary_url" > /dev/stderr
         sha256=`sha256sum $$TMP_FILE | cut -d' ' -f1`
         echo "struct("
         echo "  name = \\"$$name\\","
    
    From 3cbc18e8e874b4d1d017d5e8b862d35624088b60 Mon Sep 17 00:00:00 2001
    From: Fabian Meumertzheim 
    Date: Wed, 24 Sep 2025 02:58:52 -0700
    Subject: [PATCH 320/465] Update abseil-cpp to remove override (#322)
    
    Closes #322
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/322 from fmeum:patch-3 ab0eba8fd5356edef6f48bf247650a4664b6a5bc
    PiperOrigin-RevId: 810799669
    Change-Id: Ib4113c9090964f676def76dc67caf2125b7264da
    ---
     MODULE.bazel                               | 12 +-------
     third_party/abseil-cpp_load-cc-rules.patch | 36 ----------------------
     2 files changed, 1 insertion(+), 47 deletions(-)
     delete mode 100644 third_party/abseil-cpp_load-cc-rules.patch
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index f900a930..2da6b179 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -14,17 +14,7 @@ bazel_dep(name = "zlib", version = "1.3.1.bcr.5")
     
     # Required by @remote_java_tools, which is loaded via module extension.
     bazel_dep(name = "rules_license", version = "0.0.3")
    -bazel_dep(name = "abseil-cpp", version = "20250814.0", repo_name = "com_google_absl")
    -
    -# TODO: Remove this override after the next release of abseil-cpp.
    -single_version_override(
    -    module_name = "abseil-cpp",
    -    patch_strip = 1,
    -    patches = [
    -        "//third_party:abseil-cpp_load-cc-rules.patch",
    -    ],
    -    version = "20250814.0",
    -)
    +bazel_dep(name = "abseil-cpp", version = "20250814.1", repo_name = "com_google_absl")
     
     single_version_override(
         module_name = "protobuf",
    diff --git a/third_party/abseil-cpp_load-cc-rules.patch b/third_party/abseil-cpp_load-cc-rules.patch
    deleted file mode 100644
    index e3dfe2bb..00000000
    --- a/third_party/abseil-cpp_load-cc-rules.patch
    +++ /dev/null
    @@ -1,36 +0,0 @@
    -From 2370ccf579bd0fb4484c343389b8121c6b7f9bb8 Mon Sep 17 00:00:00 2001
    -From: Keith Smiley 
    -Date: Sat, 20 Sep 2025 20:02:06 -0700
    -Subject: [PATCH] PR #1939: Add missing rules_cc loads
    -
    -Imported from GitHub PR https://github.com/abseil/abseil-cpp/pull/1939
    -
    -This is required for use with bazel past this commit: https://github.com/bazelbuild/bazel/commit/71ca0ed111ff3d842a0d23bc3a46bd2e6745491d
    -
    -Most files do this already these were just missing
    -
    -Merge f7d58947afdb0549c9e5c287a5e5851a7d72e1e0 into 620d600442769b7ec4b61bd87667899908eec4ef
    -
    -Merging this change closes #1939
    -
    -COPYBARA_INTEGRATE_REVIEW=https://github.com/abseil/abseil-cpp/pull/1939 from keith:ks/add-missing-rules_cc-loads f7d58947afdb0549c9e5c287a5e5851a7d72e1e0
    -PiperOrigin-RevId: 809556509
    -Change-Id: I494a118b851685a03393485514a3b6fbe3a10597
    ----
    - absl/debugging/BUILD.bazel | 3 +++
    - 1 file changed, 3 insertions(+)
    -
    -diff --git a/absl/debugging/BUILD.bazel b/absl/debugging/BUILD.bazel
    -index ed7cc493e90..7cc053e783e 100644
    ---- a/absl/debugging/BUILD.bazel
    -+++ b/absl/debugging/BUILD.bazel
    -@@ -14,6 +14,9 @@
    - # limitations under the License.
    - #
    - 
    -+load("@rules_cc//cc:cc_binary.bzl", "cc_binary")
    -+load("@rules_cc//cc:cc_library.bzl", "cc_library")
    -+load("@rules_cc//cc:cc_test.bzl", "cc_test")
    - load(
    -     "//absl:copts/configure_copts.bzl",
    -     "ABSL_DEFAULT_COPTS",
    
    From b19de64d5ebbf8548404be6f028c5a1ed336a826 Mon Sep 17 00:00:00 2001
    From: Ed Schouten 
    Date: Wed, 24 Sep 2025 07:46:29 -0700
    Subject: [PATCH 321/465] Stop using the deprecated Label.workspace_name (#317)
    
    Starting with Bazel 7 we should use Label.repo_name instead.
    
    Closes #317
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/317 from EdSchouten:eschouten/20250909-repo-name 8d6a3e327ffbd9339ac5021c4e07d20454b39ea4
    PiperOrigin-RevId: 810880486
    Change-Id: I147c477448c29f6a421586cded7f4e05b137c480
    ---
     java/common/rules/java_runtime.bzl    | 4 ++--
     java/private/java_common_internal.bzl | 2 +-
     2 files changed, 3 insertions(+), 3 deletions(-)
    
    diff --git a/java/common/rules/java_runtime.bzl b/java/common/rules/java_runtime.bzl
    index 42321173..47a93435 100644
    --- a/java/common/rules/java_runtime.bzl
    +++ b/java/common/rules/java_runtime.bzl
    @@ -54,7 +54,7 @@ JavaRuntimeInfo, _new_javaruntimeinfo = provider(
     )
     
     def _is_main_repo(label):
    -    return label.workspace_name == ""
    +    return label.repo_name == ""
     
     def _default_java_home(label):
         if _is_main_repo(label):
    @@ -70,7 +70,7 @@ def _get_runfiles_java_executable(ctx, java_home, label):
         if paths.is_absolute(java_home) or _is_main_repo(label):
             return helper.get_relative(java_home, _get_bin_java(ctx))
         else:
    -        repo_runfiles_path = "" if _is_main_repo(label) else helper.get_relative("..", label.workspace_name)
    +        repo_runfiles_path = "" if _is_main_repo(label) else helper.get_relative("..", label.repo_name)
             return helper.get_relative(repo_runfiles_path, _get_bin_java(ctx))
     
     def _is_java_binary(path):
    diff --git a/java/private/java_common_internal.bzl b/java/private/java_common_internal.bzl
    index 54f0c7bd..45b4f097 100644
    --- a/java/private/java_common_internal.bzl
    +++ b/java/private/java_common_internal.bzl
    @@ -141,7 +141,7 @@ def compile(
         if ("com.google.devtools.build.runfiles.AutoBazelRepositoryProcessor" in
             plugin_info.plugins.processor_classes.to_list()):
             all_javac_opts.append(depset(
    -            ["-Abazel.repository=" + ctx.label.workspace_name],
    +            ["-Abazel.repository=" + ctx.label.repo_name],
                 order = "preorder",
             ))
         system_bootclasspath = None
    
    From 6a30ab8814486d8a6cdb59ffb1bf2cc63496fdfa Mon Sep 17 00:00:00 2001
    From: Fabian Meumertzheim 
    Date: Wed, 8 Oct 2025 04:26:16 -0700
    Subject: [PATCH 322/465] Run the bootclasspath through ijar (#324)
    
    This reduces disk space and cache usage and should speed up Turbine actions.
    
    ```
    ls -lah bazel-out/darwin_arm64-fastbuild/bin/external/rules_java+/toolchains/platformclasspath*.jar
    -r-xr-xr-x@ 1 fmeum    24M Sep 25 11:36 bazel-out/darwin_arm64-fastbuild/bin/external/rules_java+/toolchains/platformclasspath.jar
    -r-xr-xr-x@ 1 fmeum   133M Sep 25 11:36 bazel-out/darwin_arm64-fastbuild/bin/external/rules_java+/toolchains/platformclasspath_unstripped.jar
    ```
    
    Closes #324
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/324 from fmeum:ijar-bootclasspath 25b0af0de4cc8464f6fc24dd3fd46475e65bdc1e
    PiperOrigin-RevId: 816643474
    Change-Id: I27082108be70825ca691c17a0d1eedc7342ad064
    ---
     test/toolchains/bootclasspath_tests.bzl |  3 +++
     toolchains/bootclasspath.bzl            | 36 ++++++++++++++++++++++---
     2 files changed, 36 insertions(+), 3 deletions(-)
    
    diff --git a/test/toolchains/bootclasspath_tests.bzl b/test/toolchains/bootclasspath_tests.bzl
    index 5eb436a0..e7ad1cac 100644
    --- a/test/toolchains/bootclasspath_tests.bzl
    +++ b/test/toolchains/bootclasspath_tests.bzl
    @@ -13,6 +13,9 @@ def _test_utf_8_environment(name):
     
     def _test_utf_8_environment_impl(env, target):
         for action in target.actions:
    +        if action.mnemonic == "Ijar":
    +            # ijar isn't sensitive to locales
    +            continue
             env_subject = env.expect.where(action = action).that_dict(action.env)
             env_subject.keys().contains("LC_CTYPE")
             env_subject.get("LC_CTYPE", factory = subjects.str).contains("UTF-8")
    diff --git a/toolchains/bootclasspath.bzl b/toolchains/bootclasspath.bzl
    index d89aa171..5b4187c7 100644
    --- a/toolchains/bootclasspath.bzl
    +++ b/toolchains/bootclasspath.bzl
    @@ -101,6 +101,21 @@ _bootclasspath_transition = transition(
         ],
     )
     
    +def _run_ijar(*, actions, label, ijar, input, output):
    +    args = actions.args()
    +    args.add(input)
    +    args.add(output)
    +    args.add("--target_label", label)
    +    actions.run(
    +        inputs = [input],
    +        outputs = [output],
    +        executable = ijar,
    +        arguments = [args],
    +        progress_message = "Extracting interfaces from %{input}",
    +        execution_requirements = _SUPPORTS_PATH_MAPPING,
    +        mnemonic = "Ijar",
    +    )
    +
     _JAVA_BOOTSTRAP_RUNTIME_TOOLCHAIN_TYPE = Label("@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type")
     
     # Opt the Java bootstrap actions into path mapping:
    @@ -138,7 +153,7 @@ def _bootclasspath_impl(ctx):
             use_default_shell_env = True,
         )
     
    -    bootclasspath = ctx.outputs.output_jar
    +    unstripped_bootclasspath = ctx.actions.declare_file("%s_unstripped.jar" % ctx.label.name)
     
         args = ctx.actions.args()
         args.add("-XX:+IgnoreUnrecognizedVMOptions")
    @@ -148,7 +163,7 @@ def _bootclasspath_impl(ctx):
         args.add("--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED")
         args.add_all("-cp", [class_dir], expand_directories = False)
         args.add("DumpPlatformClassPath")
    -    args.add(bootclasspath)
    +    args.add(unstripped_bootclasspath)
     
         if ctx.attr.language_version_bootstrap_runtime:
             # The attribute is subject to a split transition.
    @@ -201,12 +216,22 @@ Rerun with --toolchain_resolution_debug='@bazel_tools//tools/jdk:bootstrap_runti
             executable = str(exec_javabase.java_executable_exec_path),
             mnemonic = "JavaToolchainCompileBootClasspath",
             inputs = inputs,
    -        outputs = [bootclasspath],
    +        outputs = [unstripped_bootclasspath],
             arguments = [args],
             env = env,
             execution_requirements = _SUPPORTS_PATH_MAPPING,
             use_default_shell_env = True,
         )
    +
    +    bootclasspath = ctx.outputs.output_jar
    +    _run_ijar(
    +        actions = ctx.actions,
    +        label = ctx.label,
    +        ijar = ctx.executable._ijar,
    +        input = unstripped_bootclasspath,
    +        output = bootclasspath,
    +    )
    +
         return [
             DefaultInfo(files = depset([bootclasspath])),
             java_common.BootClassPathInfo(
    @@ -234,6 +259,11 @@ _bootclasspath = rule(
             "_allowlist_function_transition": attr.label(
                 default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
             ),
    +        "_ijar": attr.label(
    +            default = "//toolchains:ijar",
    +            cfg = "exec",
    +            executable = True,
    +        ),
             "_utf8_environment": attr.label(
                 default = ":utf8_environment",
                 cfg = "exec",
    
    From 212b7abb395fe4ee0e80ea8511638ec690c92303 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 8 Oct 2025 05:03:45 -0700
    Subject: [PATCH 323/465] Remove hasattr check from
     use_header_compilation_direct_deps logic
    
    PiperOrigin-RevId: 816653694
    Change-Id: I59255834bd625fa0cb4c99dde0e616c130cf7019
    ---
     java/private/java_common_internal.bzl | 12 ++++--------
     1 file changed, 4 insertions(+), 8 deletions(-)
    
    diff --git a/java/private/java_common_internal.bzl b/java/private/java_common_internal.bzl
    index 45b4f097..7af3bf79 100644
    --- a/java/private/java_common_internal.bzl
    +++ b/java/private/java_common_internal.bzl
    @@ -224,16 +224,11 @@ def compile(
         elif _should_use_header_compilation(ctx, java_toolchain):
             compile_jar = helper.derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jar")
     
    -        # TODO: b/417791104 - remove hasattr check once Bazel 8.3.0 is released
    -        if hasattr(ctx.fragments.java, "use_header_compilation_direct_deps") and ctx.fragments.java.use_header_compilation_direct_deps():
    +        # TODO: b/417791104 - remove check after a Bazel release
    +        if ctx.fragments.java.use_header_compilation_direct_deps():
                 header_compilation_jar = helper.derive_output_file(ctx, output, name_suffix = "-tjar", extension = "jar")
    -            header_compilation_extra_args = {
    -                "header_compilation_jar": header_compilation_jar,
    -                "header_compilation_direct_deps": header_compilation_direct_deps,
    -            }
             else:
                 header_compilation_jar = None
    -            header_compilation_extra_args = {}
             compile_deps_proto = helper.derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jdeps")
             get_internal_java_common().create_header_compilation_action(
                 ctx,
    @@ -253,7 +248,8 @@ def compile(
                 injecting_rule_kind,
                 enable_direct_classpath,
                 annotation_processor_additional_inputs,
    -            **header_compilation_extra_args
    +            header_compilation_jar,
    +            header_compilation_direct_deps,
             )
         elif ctx.fragments.java.use_ijars():
             compile_jar = run_ijar(
    
    From 3257e83974066f089202562d28603e06b06d3831 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 8 Oct 2025 05:30:18 -0700
    Subject: [PATCH 324/465] Re-enable `ReturnValueIgnored` error prone check
    
    The check was disabled (temporarily) to make progress at the time and never got re-enabled.
    
    Fixes https://github.com/bazelbuild/rules_java/issues/284
    
    PiperOrigin-RevId: 816661241
    Change-Id: I8aa0951a7963e5ca4e22a93a4d0723aeb62ead40
    ---
     toolchains/default_java_toolchain.bzl | 2 --
     1 file changed, 2 deletions(-)
    
    diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl
    index 4f463937..f836f8fb 100644
    --- a/toolchains/default_java_toolchain.bzl
    +++ b/toolchains/default_java_toolchain.bzl
    @@ -59,8 +59,6 @@ DEFAULT_JAVACOPTS = [
         "--should-stop=ifError=FLOW",  # See b/27049950, https://github.com/google/error-prone/issues/4595
         "-g",
         "-parameters",
    -    # https://github.com/bazelbuild/bazel/issues/15219
    -    "-Xep:ReturnValueIgnored:OFF",
         # https://github.com/bazelbuild/bazel/issues/16996
         "-Xep:IgnoredPureGetter:OFF",
         "-Xep:EmptyTopLevelDeclaration:OFF",
    
    From 1ed307b1d1a5fb06decb7ae3af1622339dd24620 Mon Sep 17 00:00:00 2001
    From: Farid Zakaria 
    Date: Wed, 15 Oct 2025 02:07:46 -0700
    Subject: [PATCH 325/465] Increase maxwarns to -1 (#291)
    
    Please see https://github.com/bazelbuild/bazel/issues/25927#issuecomment-2825206105
    
    It's important not to filter out any warnings otherwise the lint warnings are not surfaced and then any attempt to do `-Werror` can fail with what may be observed as spurious (affect other parts of the codebase).
    
    This is maybe a "breaking change" only if someone has enabled `-Werror` and may now see additional errors -- although that was in fact their intention...
    
    Closes #291
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/291 from fzakaria:patch-1 6938d218c5d8c3640f9c1d98cbf48e55b7f2639d
    PiperOrigin-RevId: 819643216
    Change-Id: I193e3fca51a56adc6ffa8623ef18729e633623e6
    ---
     toolchains/default_java_toolchain.bzl | 3 +++
     1 file changed, 3 insertions(+)
    
    diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl
    index f836f8fb..5d1d54a5 100644
    --- a/toolchains/default_java_toolchain.bzl
    +++ b/toolchains/default_java_toolchain.bzl
    @@ -65,6 +65,9 @@ DEFAULT_JAVACOPTS = [
         "-Xep:LenientFormatStringValidation:OFF",
         "-Xep:ReturnMissingNullable:OFF",
         "-Xep:UseCorrectAssertInTests:OFF",
    +    # Please see https://github.com/bazelbuild/bazel/issues/25927#issuecomment-2825206105
    +    # we need to make sure not to filter any warnings so that Bazel can trigger them as errors.
    +    "-Xmaxwarns -1",
     ]
     
     # If this is changed, the docs for "{,tool_}java_language_version" also
    
    From 7ff9193af58807c9b77f3b7cd56063c9b8a9f028 Mon Sep 17 00:00:00 2001
    From: Fabian Meumertzheim 
    Date: Wed, 15 Oct 2025 02:08:04 -0700
    Subject: [PATCH 326/465] Fix test class determination error message (#326)
    
    Closes #326
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/326 from fmeum:patch-5 cd3a7c35e6d9a027c6de7e0c6270a2ac8d62e88b
    PiperOrigin-RevId: 819643398
    Change-Id: I3d333388ae52c0e52da1e2ed56dbf5ef75ae5c4a
    ---
     java/bazel/rules/bazel_java_binary.bzl | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/java/bazel/rules/bazel_java_binary.bzl b/java/bazel/rules/bazel_java_binary.bzl
    index de25ab8f..4ee9c881 100644
    --- a/java/bazel/rules/bazel_java_binary.bzl
    +++ b/java/bazel/rules/bazel_java_binary.bzl
    @@ -84,7 +84,7 @@ def bazel_base_binary_impl(ctx, is_test_rule_class):
                 test_class = helper.primary_class(ctx)
             if test_class == None:
                 fail("cannot determine test class. You might want to rename the " +
    -                 " rule or add a 'test_class' attribute.")
    +                 "rule or add a 'test_class' attribute.")
             jvm_flags.extend([
                 "-ea",
                 "-Dbazel.test_suite=" + helper.shell_escape(test_class),
    
    From 6018c900f3aa553f97b9e3c0a5be4c4c6ea812a2 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 15 Oct 2025 06:24:18 -0700
    Subject: [PATCH 327/465] Temporarily disable rules_java CI on
     macos/macos_arm64 due to infra issue
    
    PiperOrigin-RevId: 819722046
    Change-Id: I6f284a68c317f545d9b5dbd7b3e19ce846c826aa
    ---
     .bazelci/presubmit.yml | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml
    index 7357c253..594ab399 100644
    --- a/.bazelci/presubmit.yml
    +++ b/.bazelci/presubmit.yml
    @@ -46,7 +46,7 @@ flags_workspace_integration: &flags_workspace_integration
     buildifier: latest
     
     matrix:
    -  all_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"]
    +  all_platforms: ["ubuntu2004", "windows"] # TODO: b/443213966 - re-enable macos/macos_arm64
       bazel: ["7.6.1", "8.4.0", "last_green"] # Bazel 6 tested separately, needs different flags
       modern_bazel: ["last_green", "rolling"] # Fully supported Bazel versions
     
    
    From b4539a4977bc66620c319275b96e63020f8ad05c Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Thu, 16 Oct 2025 02:20:06 -0700
    Subject: [PATCH 328/465] Revert: Temporarily disable rules_java CI on
     macos/macos_arm64 due to infra issue
    
    PiperOrigin-RevId: 820135832
    Change-Id: I0355ecf2044aef9609a2d0c4bc4e6cf82ed8d119
    ---
     .bazelci/presubmit.yml | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml
    index 594ab399..7357c253 100644
    --- a/.bazelci/presubmit.yml
    +++ b/.bazelci/presubmit.yml
    @@ -46,7 +46,7 @@ flags_workspace_integration: &flags_workspace_integration
     buildifier: latest
     
     matrix:
    -  all_platforms: ["ubuntu2004", "windows"] # TODO: b/443213966 - re-enable macos/macos_arm64
    +  all_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"]
       bazel: ["7.6.1", "8.4.0", "last_green"] # Bazel 6 tested separately, needs different flags
       modern_bazel: ["last_green", "rolling"] # Fully supported Bazel versions
     
    
    From 36264e47900e693a45b4388c396ca65e8be8a5a8 Mon Sep 17 00:00:00 2001
    From: simonresch <65217285+simonresch@users.noreply.github.com>
    Date: Fri, 17 Oct 2025 04:19:06 -0700
    Subject: [PATCH 329/465] Update zulu JDKs to latest patch release (#327)
     (#328)
    
    Closes #327
    
    Closes #328
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/328 from simonresch:update-zulu-jdks 7478e8f79ef7b6f1569ab592c0865ca4bb1a51ad
    PiperOrigin-RevId: 820632158
    Change-Id: I49d4ed50ff8467f6305107b07b6bd8ea5dc736c2
    ---
     java/bazel/repositories_util.bzl |   8 +-
     java/repositories.bzl            | 132 +++++++++++++++----------------
     2 files changed, 70 insertions(+), 70 deletions(-)
    
    diff --git a/java/bazel/repositories_util.bzl b/java/bazel/repositories_util.bzl
    index 5b05fb2e..e9a68f5e 100644
    --- a/java/bazel/repositories_util.bzl
    +++ b/java/bazel/repositories_util.bzl
    @@ -18,7 +18,7 @@ visibility(["//test"])
     _RELEASE_CONFIGS = {
         "8": {
             "zulu": {
    -            "release": "8.84.0.15-ca-jdk8.0.442",
    +            "release": "8.88.0.19-ca-jdk8.0.462",
                 "platforms": {
                     "linux": ["aarch64", "x86_64"],
                     "macos": ["aarch64", "x86_64"],
    @@ -34,7 +34,7 @@ _RELEASE_CONFIGS = {
         },
         "11": {
             "zulu": {
    -            "release": "11.78.15-ca-jdk11.0.26",
    +            "release": "11.82.19-ca-jdk11.0.28",
                 "platforms": {
                     "linux": ["aarch64", "x86_64"],
                     "macos": ["aarch64", "x86_64"],
    @@ -56,7 +56,7 @@ _RELEASE_CONFIGS = {
         },
         "17": {
             "zulu": {
    -            "release": "17.56.15-ca-jdk17.0.14",
    +            "release": "17.60.17-ca-jdk17.0.16",
                 "platforms": {
                     "linux": ["aarch64", "x86_64"],
                     "macos": ["aarch64", "x86_64"],
    @@ -72,7 +72,7 @@ _RELEASE_CONFIGS = {
         },
         "21": {
             "zulu": {
    -            "release": "21.40.17-ca-jdk21.0.6",
    +            "release": "21.44.17-ca-jdk21.0.8",
                 "platforms": {
                     "linux": ["aarch64", "x86_64"],
                     "macos": ["aarch64", "x86_64"],
    diff --git a/java/repositories.bzl b/java/repositories.bzl
    index 09da2ce6..ff473d4c 100644
    --- a/java/repositories.bzl
    +++ b/java/repositories.bzl
    @@ -80,41 +80,41 @@ _REMOTE_JDK_CONFIGS_LIST = [
         struct(
             name = "remote_jdk8_linux_aarch64",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"],
    -        sha256 = "3ae6b27727a308c0c262a99e20af29c87aad7910de423db2607c44551b598e57",
    -        strip_prefix = "zulu8.84.0.15-ca-jdk8.0.442-linux_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-linux_aarch64.tar.gz"],
    +        sha256 = "7f3a4f6a24f764259db98c69e759bf7cae95ce957dadd74117ed5d6037fcfcc7",
    +        strip_prefix = "zulu8.88.0.19-ca-jdk8.0.462-linux_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-linux_aarch64.tar.gz"],
             version = "8",
         ),
         struct(
             name = "remote_jdk8_linux",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"],
    -        sha256 = "6e3bd4d911e6eb2d14e0b48e622b6909c76add0b51c51d11f5c2c3d2a045bcf3",
    -        strip_prefix = "zulu8.84.0.15-ca-jdk8.0.442-linux_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-linux_x64.tar.gz"],
    +        sha256 = "af194163bd9c870321f06b134f447869daafe6aef5b92b49d15b2fbc03a3b999",
    +        strip_prefix = "zulu8.88.0.19-ca-jdk8.0.462-linux_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-linux_x64.tar.gz"],
             version = "8",
         ),
         struct(
             name = "remote_jdk8_macos_aarch64",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"],
    -        sha256 = "effa6d1bd4b6bce68328df66e063a97c2c4afeb0aa36fda4f85c434dd8246572",
    -        strip_prefix = "zulu8.84.0.15-ca-jdk8.0.442-macosx_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-macosx_aarch64.tar.gz"],
    +        sha256 = "abfb45c587b80646eedc679f5fd1c47f1851fd682a043adf5c46c0f55e4d2321",
    +        strip_prefix = "zulu8.88.0.19-ca-jdk8.0.462-macosx_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-macosx_aarch64.tar.gz"],
             version = "8",
         ),
         struct(
             name = "remote_jdk8_macos",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"],
    -        sha256 = "52131294512042dd6356426202e6a4116536477281fe76cfc0a3a15fe0d6ff44",
    -        strip_prefix = "zulu8.84.0.15-ca-jdk8.0.442-macosx_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-macosx_x64.tar.gz"],
    +        sha256 = "e39adde0283ff1cb5c82193654c15688ea5ea4e6f38336d001c43d81d26c102c",
    +        strip_prefix = "zulu8.88.0.19-ca-jdk8.0.462-macosx_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-macosx_x64.tar.gz"],
             version = "8",
         ),
         struct(
             name = "remote_jdk8_windows",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"],
    -        sha256 = "551c0df372a4b01754e214c52d2bdc2e22e1582274a3ea0e4a27d77db6a9cbea",
    -        strip_prefix = "zulu8.84.0.15-ca-jdk8.0.442-win_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.84.0.15-ca-jdk8.0.442-win_x64.zip"],
    +        sha256 = "4811dd4bb476f7484d132cb6393ca58344c45d43b9547f4251b15c5b8d1fd580",
    +        strip_prefix = "zulu8.88.0.19-ca-jdk8.0.462-win_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-win_x64.zip"],
             version = "8",
         ),
         struct(
    @@ -128,41 +128,41 @@ _REMOTE_JDK_CONFIGS_LIST = [
         struct(
             name = "remotejdk11_linux_aarch64",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"],
    -        sha256 = "f221d794325ab04382ba52250fc8fe8c4d384841a63bc2acd62d623a5bc53eb7",
    -        strip_prefix = "zulu11.78.15-ca-jdk11.0.26-linux_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-linux_aarch64.tar.gz"],
    +        sha256 = "f90d9eb822f68cacd536144660b43402fc8a8e922358d67e84609d7828070e6b",
    +        strip_prefix = "zulu11.82.19-ca-jdk11.0.28-linux_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-linux_aarch64.tar.gz"],
             version = "11",
         ),
         struct(
             name = "remotejdk11_linux",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"],
    -        sha256 = "fdf95b001d50b03bc3ce5f4fe7dc96bec9f94e561f9ec722a149bd7995600449",
    -        strip_prefix = "zulu11.78.15-ca-jdk11.0.26-linux_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-linux_x64.tar.gz"],
    +        sha256 = "b34a75da63dab5f61ac342290000c1a51de3023049e2b30da89393f5f0b79759",
    +        strip_prefix = "zulu11.82.19-ca-jdk11.0.28-linux_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-linux_x64.tar.gz"],
             version = "11",
         ),
         struct(
             name = "remotejdk11_macos_aarch64",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"],
    -        sha256 = "3708badcc0c79fc1791e74b62478188a1f43c4f9a1e7d3e1bd4173da995479a3",
    -        strip_prefix = "zulu11.78.15-ca-jdk11.0.26-macosx_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-macosx_aarch64.tar.gz"],
    +        sha256 = "5b104e96bb41dc38b1605d701e4482003acffbe48e25e15ba0cb7a1611821aa7",
    +        strip_prefix = "zulu11.82.19-ca-jdk11.0.28-macosx_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-macosx_aarch64.tar.gz"],
             version = "11",
         ),
         struct(
             name = "remotejdk11_macos",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"],
    -        sha256 = "bb3884619c6f09ec5ca3ce43810c61ade647bb896f4120a6cf076ec993b5a1a0",
    -        strip_prefix = "zulu11.78.15-ca-jdk11.0.26-macosx_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-macosx_x64.tar.gz"],
    +        sha256 = "11c3a142f82ad10cd9e2bfc0884c36ee66de0ac1b3ed9c018e746345813f80c8",
    +        strip_prefix = "zulu11.82.19-ca-jdk11.0.28-macosx_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-macosx_x64.tar.gz"],
             version = "11",
         ),
         struct(
             name = "remotejdk11_win",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"],
    -        sha256 = "2f48346ba05d0d1a31a6797cd0fd27a0492c0df0c90730c9eeca7fc6952a075c",
    -        strip_prefix = "zulu11.78.15-ca-jdk11.0.26-win_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.78.15-ca-jdk11.0.26-win_x64.zip"],
    +        sha256 = "728dbb971dc41be992aae950b89139e5d582f2ee7d918a06a69749fea6143fce",
    +        strip_prefix = "zulu11.82.19-ca-jdk11.0.28-win_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-win_x64.zip"],
             version = "11",
         ),
         struct(
    @@ -192,49 +192,49 @@ _REMOTE_JDK_CONFIGS_LIST = [
         struct(
             name = "remotejdk17_linux_aarch64",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"],
    -        sha256 = "9fe5d08b20546e84af517cfefc7068f7a47e98473603782264e519f935977cb3",
    -        strip_prefix = "zulu17.56.15-ca-jdk17.0.14-linux_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-linux_aarch64.tar.gz"],
    +        sha256 = "1cbb51dc9400814b8fbb79252762af5eba1f556e558128f2a4fca906b2ed04c8",
    +        strip_prefix = "zulu17.60.17-ca-jdk17.0.16-linux_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-linux_aarch64.tar.gz"],
             version = "17",
         ),
         struct(
             name = "remotejdk17_linux",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"],
    -        sha256 = "37ab75b2f5da0ff0db973b31e9d9f14f729137a0a110abd6472ac8c6f2feabb6",
    -        strip_prefix = "zulu17.56.15-ca-jdk17.0.14-linux_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-linux_x64.tar.gz"],
    +        sha256 = "e70822e4b77a9ffd57015b55f4bb645bba97b8f5247a792eceb95dbc7a5a55ab",
    +        strip_prefix = "zulu17.60.17-ca-jdk17.0.16-linux_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-linux_x64.tar.gz"],
             version = "17",
         ),
         struct(
             name = "remotejdk17_macos_aarch64",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"],
    -        sha256 = "c3b9bfb0a6dbe4c5d9efce6c46d3a89c92d7b07ba1bd0afc944612298ac284ec",
    -        strip_prefix = "zulu17.56.15-ca-jdk17.0.14-macosx_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-macosx_aarch64.tar.gz"],
    +        sha256 = "1e23895f8edddd86dbc20a2820b1bd11695e7a6ac37f1bcee90492341aa5b32d",
    +        strip_prefix = "zulu17.60.17-ca-jdk17.0.16-macosx_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-macosx_aarch64.tar.gz"],
             version = "17",
         ),
         struct(
             name = "remotejdk17_macos",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"],
    -        sha256 = "ee1a55b6b63d62d1a24d420b1550ef1736fda36db0e612893d9d26eb1d7f1611",
    -        strip_prefix = "zulu17.56.15-ca-jdk17.0.14-macosx_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-macosx_x64.tar.gz"],
    +        sha256 = "6578d84c961b23f27bc7d504cb2fc45a47296bce382927d6485d404753a8a51a",
    +        strip_prefix = "zulu17.60.17-ca-jdk17.0.16-macosx_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-macosx_x64.tar.gz"],
             version = "17",
         ),
         struct(
             name = "remotejdk17_win_arm64",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"],
    -        sha256 = "dbf51756115f7591759b2ed6d9c0d79b3b770c1a13be476c99d64934a93ff422",
    -        strip_prefix = "zulu17.56.15-ca-jdk17.0.14-win_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-win_aarch64.zip"],
    +        sha256 = "2415163925968bfcc882e919e97f48c08eaf555947bb1b0b27291fd3fae1d462",
    +        strip_prefix = "zulu17.60.17-ca-jdk17.0.16-win_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-win_aarch64.zip"],
             version = "17",
         ),
         struct(
             name = "remotejdk17_win",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"],
    -        sha256 = "11dbe0051cea65fbfc94e0074fbb26d81897f5aff2df69fed3784f380d0d9ec9",
    -        strip_prefix = "zulu17.56.15-ca-jdk17.0.14-win_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-win_x64.zip"],
    +        sha256 = "c51781710ff93fc7694668fe701c6b813aabda4e9dad6227a7d6734425b3b3ff",
    +        strip_prefix = "zulu17.60.17-ca-jdk17.0.16-win_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-win_x64.zip"],
             version = "17",
         ),
         struct(
    @@ -256,49 +256,49 @@ _REMOTE_JDK_CONFIGS_LIST = [
         struct(
             name = "remotejdk21_linux_aarch64",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"],
    -        sha256 = "2cab003bad25100a00b818ce229455d35ece03fc2e69be32c9c1c03f90b2eb89",
    -        strip_prefix = "zulu21.40.17-ca-jdk21.0.6-linux_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-linux_aarch64.tar.gz"],
    +        sha256 = "ff7f2edd1d5c153cb6cb493a3aa3523453e29a05ec513b25c24aa1477ec0c722",
    +        strip_prefix = "zulu21.44.17-ca-jdk21.0.8-linux_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-linux_aarch64.tar.gz"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_linux",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"],
    -        sha256 = "5daff61d307d18305a4022c56013cbaa8987a7dd103e310ebbeb75e0f3091a03",
    -        strip_prefix = "zulu21.40.17-ca-jdk21.0.6-linux_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-linux_x64.tar.gz"],
    +        sha256 = "63f56bbb46958cf57352fba08f2755e0953799195e5545acc0c8a92920beff1e",
    +        strip_prefix = "zulu21.44.17-ca-jdk21.0.8-linux_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-linux_x64.tar.gz"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_macos_aarch64",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"],
    -        sha256 = "1d6385f17ae2dc3b57a6d1b6fd6aeadafe1c7138bc744f62a767851eececd092",
    -        strip_prefix = "zulu21.40.17-ca-jdk21.0.6-macosx_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-macosx_aarch64.tar.gz"],
    +        sha256 = "d22ce05fea3e3f28c8c59f2c348bc78ee967bf1289a4fb28796cc0177ff6c8db",
    +        strip_prefix = "zulu21.44.17-ca-jdk21.0.8-macosx_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-macosx_aarch64.tar.gz"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_macos",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"],
    -        sha256 = "0b0f05e53e2b85f3881f1b8f5e3ef7e2e992796a1872afbc851b73127b16933d",
    -        strip_prefix = "zulu21.40.17-ca-jdk21.0.6-macosx_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-macosx_x64.tar.gz"],
    +        sha256 = "2af080500b5cc286a6353187c7c59b5aafcb3edc29c1c87d1fd71ba2d6a523f1",
    +        strip_prefix = "zulu21.44.17-ca-jdk21.0.8-macosx_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-macosx_x64.tar.gz"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_win_arm64",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"],
    -        sha256 = "57c568355b97d288f12b720760d802b1a19c55e9b0707a5c2ad76d34fd893db8",
    -        strip_prefix = "zulu21.40.17-ca-jdk21.0.6-win_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-win_aarch64.zip"],
    +        sha256 = "76379d799e766fb7ea1cdaacc67aa87f75a118f863cc68ffe32c251be94ab4f4",
    +        strip_prefix = "zulu21.44.17-ca-jdk21.0.8-win_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-win_aarch64.zip"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_win",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"],
    -        sha256 = "a1360d2ab3ee9932b5cb20a2386d6b0fb1518a68c89a08739736c38a4debbdae",
    -        strip_prefix = "zulu21.40.17-ca-jdk21.0.6-win_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.40.17-ca-jdk21.0.6-win_x64.zip"],
    +        sha256 = "f47dbd00384cb759f86a066be7545e467e5764f4653a237c32c07da96dc1c43b",
    +        strip_prefix = "zulu21.44.17-ca-jdk21.0.8-win_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-win_x64.zip"],
             version = "21",
         ),
         struct(
    
    From 402b1842d6e17e265c0b5c488f79edd851a202c2 Mon Sep 17 00:00:00 2001
    From: Benjamin Peterson 
    Date: Mon, 20 Oct 2025 02:55:06 -0700
    Subject: [PATCH 330/465] upgrade java_tools to 17.0 and wire up linux aarch64
     prebuilts (#334)
    
    https://github.com/bazelbuild/rules_java/issues/173
    
    Closes #334
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/334 from benjaminp:benjamin-java_tools 830727a7d13ccff5aeee15b2c739ab86d71f5ad5
    PiperOrigin-RevId: 821564837
    Change-Id: I97b1f8fdf8a409110701e112197c4977eab03b6a
    ---
     .bazelci/presubmit.yml |  2 +-
     MODULE.bazel           |  1 +
     java/repositories.bzl  | 37 +++++++++++++++++++++----------------
     test/repo/MODULE.bazel |  1 +
     toolchains/BUILD       |  9 +++++++++
     5 files changed, 33 insertions(+), 17 deletions(-)
    
    diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml
    index 7357c253..b77fe7dc 100644
    --- a/.bazelci/presubmit.yml
    +++ b/.bazelci/presubmit.yml
    @@ -46,7 +46,7 @@ flags_workspace_integration: &flags_workspace_integration
     buildifier: latest
     
     matrix:
    -  all_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"]
    +  all_platforms: ["rockylinux8_arm64", "ubuntu2004", "macos", "macos_arm64", "windows"]
       bazel: ["7.6.1", "8.4.0", "last_green"] # Bazel 6 tested separately, needs different flags
       modern_bazel: ["last_green", "rolling"] # Fully supported Bazel versions
     
    diff --git a/MODULE.bazel b/MODULE.bazel
    index 2da6b179..01888063 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -32,6 +32,7 @@ toolchains = use_extension("//java:extensions.bzl", "toolchains")
     # Declare remote java tools repos
     use_repo(toolchains, "remote_java_tools")
     use_repo(toolchains, "remote_java_tools_linux")
    +use_repo(toolchains, "remote_java_tools_linux_aarch64")
     use_repo(toolchains, "remote_java_tools_windows")
     use_repo(toolchains, "remote_java_tools_darwin_x86_64")
     use_repo(toolchains, "remote_java_tools_darwin_arm64")
    diff --git a/java/repositories.bzl b/java/repositories.bzl
    index ff473d4c..bf2ae489 100644
    --- a/java/repositories.bzl
    +++ b/java/repositories.bzl
    @@ -22,33 +22,38 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository")
     
     # visible for tests
     JAVA_TOOLS_CONFIG = {
    -    "version": "v16.0",
    +    "version": "v17.0",
         "release": "true",
         "artifacts": {
             "java_tools_linux": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v16.0/java_tools_linux-v16.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v16.0/java_tools_linux-v16.0.zip",
    -            "sha": "7c360c60da9b9079e31f18de198f23a22555dfb7b6e91e3c6a7103127b1a8538",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v17.0/java_tools_linux-v17.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v17.0/java_tools_linux-v17.0.zip",
    +            "sha": "5f89d5d04b41dbe1d661836b6a76c468113e0080953bcd72aaf6711c7462b86a",
    +        },
    +        "java_tools_linux_aarch64": {
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v17.0/java_tools_linux_aarch64-v17.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v17.0/java_tools_linux_aarch64-v17.0.zip",
    +            "sha": "c36a17057e895b260cb8f2f7961ed7480812ab6923dab5a39f0c93263e2f76f2",
             },
             "java_tools_windows": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v16.0/java_tools_windows-v16.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v16.0/java_tools_windows-v16.0.zip",
    -            "sha": "b41faa85fceeb2f852e48d51d000d3bf4f29da86ee61d0fc8cca46d297bccf22",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v17.0/java_tools_windows-v17.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v17.0/java_tools_windows-v17.0.zip",
    +            "sha": "3ae5075b228ce464c74bd23602a65016f662895556fa8952cba2995d50904c86",
             },
             "java_tools_darwin_x86_64": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v16.0/java_tools_darwin_x86_64-v16.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v16.0/java_tools_darwin_x86_64-v16.0.zip",
    -            "sha": "a41de64afb663bb4880af52b55886098241b9222ee8ec1a0f6258d006ba247fb",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v17.0/java_tools_darwin_x86_64-v17.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v17.0/java_tools_darwin_x86_64-v17.0.zip",
    +            "sha": "c65a181af0e723ed1a36c494aa0f70753f128adb7655a7b57f8f7e71217ad35c",
             },
             "java_tools_darwin_arm64": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v16.0/java_tools_darwin_arm64-v16.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v16.0/java_tools_darwin_arm64-v16.0.zip",
    -            "sha": "b79900dccca7c26fbae9a38c4da80987445e07194517ec53e169c45f1a88c7be",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v17.0/java_tools_darwin_arm64-v17.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v17.0/java_tools_darwin_arm64-v17.0.zip",
    +            "sha": "00787917e359e2218953dbc30e228670e83fa20c4a0a5f914e0b6ecdee85fa9d",
             },
             "java_tools": {
    -            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v16.0/java_tools-v16.0.zip",
    -            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v16.0/java_tools-v16.0.zip",
    -            "sha": "d8b126078705e91677db67b05f7b25ad6fa8865949e2dd38ff85e0553bfb0be2",
    +            "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v17.0/java_tools-v17.0.zip",
    +            "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v17.0/java_tools-v17.0.zip",
    +            "sha": "9a441ca2d4ae393edd305b0e465b0ed8ee86b22123c41c26455fb856bf9bc897",
             },
         },
     }
    diff --git a/test/repo/MODULE.bazel b/test/repo/MODULE.bazel
    index 62109333..5f300800 100644
    --- a/test/repo/MODULE.bazel
    +++ b/test/repo/MODULE.bazel
    @@ -27,6 +27,7 @@ use_repo(
         "remote_java_tools_darwin_arm64",
         "remote_java_tools_darwin_x86_64",
         "remote_java_tools_linux",
    +    "remote_java_tools_linux_aarch64",
         "remote_java_tools_windows",
         "remotejdk11_linux",
         "remotejdk11_linux_aarch64",
    diff --git a/toolchains/BUILD b/toolchains/BUILD
    index 3209930b..bb6ecf7a 100644
    --- a/toolchains/BUILD
    +++ b/toolchains/BUILD
    @@ -190,6 +190,7 @@ cc_library(
         )
         for OS in [
             "linux",
    +        "linux_aarch64",
             "darwin_x86_64",
             "darwin_arm64",
             "windows",
    @@ -207,6 +208,7 @@ alias(
             "@bazel_tools//src/conditions:darwin_arm64": ":ijar_prebuilt_binary_darwin_arm64",
             "@bazel_tools//src/conditions:darwin_x86_64": ":ijar_prebuilt_binary_darwin_x86_64",
             "@bazel_tools//src/conditions:linux_x86_64": ":ijar_prebuilt_binary_linux",
    +        "@bazel_tools//src/conditions:linux_aarch64": ":ijar_prebuilt_binary_linux_aarch64",
             "@bazel_tools//src/conditions:windows": ":ijar_prebuilt_binary_windows",
             "//conditions:default": "@remote_java_tools//:ijar_cc_binary",
         }),
    @@ -218,6 +220,7 @@ alias(
             "@bazel_tools//src/conditions:darwin_arm64": ":ijar_prebuilt_binary_darwin_arm64",
             "@bazel_tools//src/conditions:darwin_x86_64": ":ijar_prebuilt_binary_darwin_x86_64",
             "@bazel_tools//src/conditions:linux_x86_64": ":ijar_prebuilt_binary_linux",
    +        "@bazel_tools//src/conditions:linux_aarch64": "ijar_prebuilt_binary_linux_aarch64",
             "@bazel_tools//src/conditions:windows": ":ijar_prebuilt_binary_windows",
         }),
     )
    @@ -233,6 +236,7 @@ alias(
             "@bazel_tools//src/conditions:darwin_arm64": ":prebuilt_singlejar_darwin_arm64",
             "@bazel_tools//src/conditions:darwin_x86_64": ":prebuilt_singlejar_darwin_x86_64",
             "@bazel_tools//src/conditions:linux_x86_64": ":prebuilt_singlejar_linux",
    +        "@bazel_tools//src/conditions:linux_aarch64": ":prebuilt_singlejar_linux_aarch64",
             "@bazel_tools//src/conditions:windows": ":prebuilt_singlejar_windows",
             "//conditions:default": "@remote_java_tools//:singlejar_cc_bin",
         }),
    @@ -244,6 +248,7 @@ alias(
             "@bazel_tools//src/conditions:darwin_arm64": ":prebuilt_singlejar_darwin_arm64",
             "@bazel_tools//src/conditions:darwin_x86_64": ":prebuilt_singlejar_darwin_x86_64",
             "@bazel_tools//src/conditions:linux_x86_64": ":prebuilt_singlejar_linux",
    +        "@bazel_tools//src/conditions:linux_aarch64": ":prebuilt_singlejar_linux_aarch64",
             "@bazel_tools//src/conditions:windows": ":prebuilt_singlejar_windows",
         }),
     )
    @@ -259,6 +264,7 @@ alias(
             "@bazel_tools//src/conditions:darwin_arm64": ":prebuilt_one_version_darwin_arm64",
             "@bazel_tools//src/conditions:darwin_x86_64": ":prebuilt_one_version_darwin_x86_64",
             "@bazel_tools//src/conditions:linux_x86_64": ":prebuilt_one_version_linux",
    +        "@bazel_tools//src/conditions:linux_aarch64": ":prebuilt_one_version_linux_aarch64",
             "@bazel_tools//src/conditions:windows": ":prebuilt_one_version_windows",
             "//conditions:default": "@remote_java_tools//:one_version_cc_bin",
         }),
    @@ -270,6 +276,7 @@ alias(
             "@bazel_tools//src/conditions:darwin_arm64": ":prebuilt_one_version_darwin_arm64",
             "@bazel_tools//src/conditions:darwin_x86_64": ":prebuilt_one_version_darwin_x86_64",
             "@bazel_tools//src/conditions:linux_x86_64": ":prebuilt_one_version_linux",
    +        "@bazel_tools//src/conditions:linux_aarch64": ":prebuilt_one_version_linux_aarch64",
             "@bazel_tools//src/conditions:windows": ":prebuilt_one_version_windows",
         }),
     )
    @@ -285,6 +292,7 @@ alias(
             "@bazel_tools//src/conditions:darwin_arm64": ":turbine_direct_graal_darwin_arm64",
             "@bazel_tools//src/conditions:darwin_x86_64": ":turbine_direct_graal_darwin_x86_64",
             "@bazel_tools//src/conditions:linux_x86_64": ":turbine_direct_graal_linux",
    +        "@bazel_tools//src/conditions:linux_aarch64": ":turbine_direct_graal_linux_aarch64",
             "@bazel_tools//src/conditions:windows": ":turbine_direct_graal_windows",
             "//conditions:default": "@remote_java_tools//:TurbineDirect",
         }),
    @@ -296,6 +304,7 @@ alias(
             "@bazel_tools//src/conditions:darwin_arm64": ":turbine_direct_graal_darwin_arm64",
             "@bazel_tools//src/conditions:darwin_x86_64": ":turbine_direct_graal_darwin_x86_64",
             "@bazel_tools//src/conditions:linux_x86_64": ":turbine_direct_graal_linux",
    +        "@bazel_tools//src/conditions:linux_aarch64": ":turbine_direct_graal_linux_aarch64",
             "@bazel_tools//src/conditions:windows": ":turbine_direct_graal_windows",
         }),
     )
    
    From 76212e60692337b1bb10afa98a8163279fe99e17 Mon Sep 17 00:00:00 2001
    From: Liz Looney 
    Date: Wed, 22 Oct 2025 17:31:32 -0700
    Subject: [PATCH 331/465] Include the srcjar (if there is one) in the
     _validation output group so blaze will check whether the srcjar file actually
     exists.
    
    RELNOTES: If a java_import target's srcjar attribute refers to a source file, the file should exist.
    PiperOrigin-RevId: 822801332
    Change-Id: Ie5b364aa873a07b4cda6d528f1a1d69bdb5b9089
    ---
     .../rules/impl/bazel_java_import_impl.bzl     |  9 +++++-
     test/java/common/rules/java_import_tests.bzl  | 28 +++++++++++++++++++
     2 files changed, 36 insertions(+), 1 deletion(-)
    
    diff --git a/java/common/rules/impl/bazel_java_import_impl.bzl b/java/common/rules/impl/bazel_java_import_impl.bzl
    index ce338cbd..7ca9cf7d 100644
    --- a/java/common/rules/impl/bazel_java_import_impl.bzl
    +++ b/java/common/rules/impl/bazel_java_import_impl.bzl
    @@ -190,11 +190,18 @@ def bazel_java_import_rule(
         )
     
         output_group_src_jars = depset() if srcjar == None else depset([srcjar])
    +
    +    validation_group = []
    +    if jdeps_artifact != None:
    +        validation_group.append(jdeps_artifact)
    +    if srcjar != None:
    +        validation_group.append(srcjar)
    +
         target["OutputGroupInfo"] = OutputGroupInfo(
             **{
                 "_source_jars": output_group_src_jars,
                 "_direct_source_jars": output_group_src_jars,
    -            "_validation": depset() if jdeps_artifact == None else depset([jdeps_artifact]),
    +            "_validation": depset(validation_group),
                 "_hidden_top_level_INTERNAL_": target["ProguardSpecProvider"].specs,
             }
         )
    diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl
    index e949e173..37941efc 100644
    --- a/test/java/common/rules/java_import_tests.bzl
    +++ b/test/java/common/rules/java_import_tests.bzl
    @@ -293,6 +293,33 @@ def _test_src_jars_impl(env, target):
             "{package}/library.srcjar",
         ])
     
    +def _test_srcjar_added_to_validation_output_group(name):
    +    util.helper_target(
    +        java_import,
    +        name = name + "/libraryjar_with_srcjar",
    +        jars = ["import.jar"],
    +        srcjar = "library.srcjar",
    +    )
    +
    +    analysis_test(
    +        name = name,
    +        impl = _test_srcjar_added_to_validation_output_group_impl,
    +        target = name + "/libraryjar_with_srcjar",
    +        # Starlark rules are only used with Bazel 8 onwards.
    +        attr_values = {"tags": ["min_bazel_8"]},
    +    )
    +
    +def _test_srcjar_added_to_validation_output_group_impl(env, target):
    +    assert_java_info = java_info_subject.from_target(env, target)
    +    assert_java_info.outputs().source_output_jars().contains_exactly([
    +        "{package}/library.srcjar",
    +    ])
    +
    +    # Check that the srcjar is in the _validation output group.
    +    env.expect.that_target(target).output_group("_validation").contains_at_least([
    +        "{package}/library.srcjar",
    +    ])
    +
     def _test_from_genrule(name):
         target_name = name + "/library-jar"
         util.helper_target(
    @@ -933,6 +960,7 @@ def java_import_tests(name):
                 _test_java_library_allows_import_in_deps,
                 _test_module_flags,
                 _test_src_jars,
    +            _test_srcjar_added_to_validation_output_group,
                 _test_from_genrule,
                 _test_transitive_dependencies,
                 _test_exposes_java_provider,
    
    From 4a1933abf58755b35775e3c5d0c87da0b742771e Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Thu, 23 Oct 2025 21:31:09 -0700
    Subject: [PATCH 332/465] Migrate swig_include_scanning to Starlark. In native
     code, this is hard coded to True, but it's also used in starlark code. So, in
     native code, remove references to the flag. In Starlark code, refer to the
     starlark option. No OSS code here, so we can add the extra attribute to refer
     to the flag.
    
    PiperOrigin-RevId: 823331236
    Change-Id: I4adc25b86c531306e9d4491b985ea95400a875c3
    ---
     java/private/BUILD | 1 +
     1 file changed, 1 insertion(+)
    
    diff --git a/java/private/BUILD b/java/private/BUILD
    index 939fa753..bbed12b8 100644
    --- a/java/private/BUILD
    +++ b/java/private/BUILD
    @@ -38,6 +38,7 @@ bzl_library(
             "//java/common/rules:toolchain_rules",
             "//java/common/rules/impl:java_helper_bzl",
             "@bazel_skylib//lib:paths",
    +        "@bazel_skylib//rules:common_settings",
             "@rules_cc//cc:find_cc_toolchain_bzl",
             "@rules_cc//cc/common",
         ],
    
    From a27004a53d7459992a77002ef8f2a6aaeb119590 Mon Sep 17 00:00:00 2001
    From: Fabian Meumertzheim 
    Date: Tue, 4 Nov 2025 05:21:58 -0800
    Subject: [PATCH 333/465] Update JDKs to latest patch releases (#335)
    
    Also print the original URLs, not the mirror URLs, as those have to be submitted as part of the mirror request.
    
    Closes #335
    
    COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/335 from fmeum:21.0.9 6b7ba7b53eb1f56d7057efd3ae045ea3dabe2e41
    PiperOrigin-RevId: 827922427
    Change-Id: I211f3e51147acca8164d5d78276881cbedb9ffde
    ---
     java/bazel/repositories_util.bzl |  20 +--
     java/repositories.bzl            | 216 +++++++++++++++----------------
     test/check_remote_jdk_configs.sh |   4 +-
     3 files changed, 120 insertions(+), 120 deletions(-)
    
    diff --git a/java/bazel/repositories_util.bzl b/java/bazel/repositories_util.bzl
    index e9a68f5e..924bb60f 100644
    --- a/java/bazel/repositories_util.bzl
    +++ b/java/bazel/repositories_util.bzl
    @@ -18,7 +18,7 @@ visibility(["//test"])
     _RELEASE_CONFIGS = {
         "8": {
             "zulu": {
    -            "release": "8.88.0.19-ca-jdk8.0.462",
    +            "release": "8.90.0.19-ca-jdk8.0.472",
                 "platforms": {
                     "linux": ["aarch64", "x86_64"],
                     "macos": ["aarch64", "x86_64"],
    @@ -34,7 +34,7 @@ _RELEASE_CONFIGS = {
         },
         "11": {
             "zulu": {
    -            "release": "11.82.19-ca-jdk11.0.28",
    +            "release": "11.84.17-ca-jdk11.0.29",
                 "platforms": {
                     "linux": ["aarch64", "x86_64"],
                     "macos": ["aarch64", "x86_64"],
    @@ -42,13 +42,13 @@ _RELEASE_CONFIGS = {
                 },
             },
             "adoptium": {
    -            "release": "11.0.26+4",
    +            "release": "11.0.28+6",
                 "platforms": {
                     "linux": ["ppc64le", "s390x"],
                 },
             },
             "microsoft": {
    -            "release": "11.0.26",
    +            "release": "11.0.28",
                 "platforms": {
                     "windows": ["arm64"],
                 },
    @@ -56,7 +56,7 @@ _RELEASE_CONFIGS = {
         },
         "17": {
             "zulu": {
    -            "release": "17.60.17-ca-jdk17.0.16",
    +            "release": "17.62.17-ca-jdk17.0.17",
                 "platforms": {
                     "linux": ["aarch64", "x86_64"],
                     "macos": ["aarch64", "x86_64"],
    @@ -64,7 +64,7 @@ _RELEASE_CONFIGS = {
                 },
             },
             "adoptium": {
    -            "release": "17.0.14+7",
    +            "release": "17.0.16+8",
                 "platforms": {
                     "linux": ["ppc64le", "s390x"],
                 },
    @@ -72,7 +72,7 @@ _RELEASE_CONFIGS = {
         },
         "21": {
             "zulu": {
    -            "release": "21.44.17-ca-jdk21.0.8",
    +            "release": "21.46.19-ca-jdk21.0.9",
                 "platforms": {
                     "linux": ["aarch64", "x86_64"],
                     "macos": ["aarch64", "x86_64"],
    @@ -80,7 +80,7 @@ _RELEASE_CONFIGS = {
                 },
             },
             "adoptium": {
    -            "release": "21.0.6+7",
    +            "release": "21.0.8+9",
                 "platforms": {
                     "linux": ["ppc64le", "riscv64", "s390x"],
                 },
    @@ -88,7 +88,7 @@ _RELEASE_CONFIGS = {
         },
         "25": {
             "zulu": {
    -            "release": "25.28.85-ca-jdk25.0.0",
    +            "release": "25.30.17-ca-jdk25.0.1",
                 "platforms": {
                     "linux": ["aarch64", "x86_64"],
                     "macos": ["aarch64", "x86_64"],
    @@ -99,7 +99,7 @@ _RELEASE_CONFIGS = {
     }
     
     _STRIP_PREFIX_OVERRIDES = {
    -    "remotejdk11_win_arm64": "jdk-11.0.26+4",
    +    "remotejdk11_win_arm64": "jdk-11.0.28+6",
     }
     
     def _name_for_remote_jdk(version, os, cpu):
    diff --git a/java/repositories.bzl b/java/repositories.bzl
    index bf2ae489..82093756 100644
    --- a/java/repositories.bzl
    +++ b/java/repositories.bzl
    @@ -85,41 +85,41 @@ _REMOTE_JDK_CONFIGS_LIST = [
         struct(
             name = "remote_jdk8_linux_aarch64",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"],
    -        sha256 = "7f3a4f6a24f764259db98c69e759bf7cae95ce957dadd74117ed5d6037fcfcc7",
    -        strip_prefix = "zulu8.88.0.19-ca-jdk8.0.462-linux_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-linux_aarch64.tar.gz"],
    +        sha256 = "c372fb26480c052537125013cb0ba7336c404e5190ea8f6e2de247b676432a67",
    +        strip_prefix = "zulu8.90.0.19-ca-jdk8.0.472-linux_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu8.90.0.19-ca-jdk8.0.472-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.90.0.19-ca-jdk8.0.472-linux_aarch64.tar.gz"],
             version = "8",
         ),
         struct(
             name = "remote_jdk8_linux",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"],
    -        sha256 = "af194163bd9c870321f06b134f447869daafe6aef5b92b49d15b2fbc03a3b999",
    -        strip_prefix = "zulu8.88.0.19-ca-jdk8.0.462-linux_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-linux_x64.tar.gz"],
    +        sha256 = "6f9e3fa773829ac2553411fb0cdeb394980627c47c9ab8f8892d4b917b70e2dd",
    +        strip_prefix = "zulu8.90.0.19-ca-jdk8.0.472-linux_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu8.90.0.19-ca-jdk8.0.472-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.90.0.19-ca-jdk8.0.472-linux_x64.tar.gz"],
             version = "8",
         ),
         struct(
             name = "remote_jdk8_macos_aarch64",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"],
    -        sha256 = "abfb45c587b80646eedc679f5fd1c47f1851fd682a043adf5c46c0f55e4d2321",
    -        strip_prefix = "zulu8.88.0.19-ca-jdk8.0.462-macosx_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-macosx_aarch64.tar.gz"],
    +        sha256 = "823d547ab9508e3a2b8abd3c5de66a39a50a254dc5835747cf3c2617fbe55600",
    +        strip_prefix = "zulu8.90.0.19-ca-jdk8.0.472-macosx_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu8.90.0.19-ca-jdk8.0.472-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.90.0.19-ca-jdk8.0.472-macosx_aarch64.tar.gz"],
             version = "8",
         ),
         struct(
             name = "remote_jdk8_macos",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"],
    -        sha256 = "e39adde0283ff1cb5c82193654c15688ea5ea4e6f38336d001c43d81d26c102c",
    -        strip_prefix = "zulu8.88.0.19-ca-jdk8.0.462-macosx_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-macosx_x64.tar.gz"],
    +        sha256 = "96fb7bc3a2babd7f807484b1b8f1dfb8cf2c61ea27b2d0630e2237088b0a5100",
    +        strip_prefix = "zulu8.90.0.19-ca-jdk8.0.472-macosx_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu8.90.0.19-ca-jdk8.0.472-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.90.0.19-ca-jdk8.0.472-macosx_x64.tar.gz"],
             version = "8",
         ),
         struct(
             name = "remote_jdk8_windows",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"],
    -        sha256 = "4811dd4bb476f7484d132cb6393ca58344c45d43b9547f4251b15c5b8d1fd580",
    -        strip_prefix = "zulu8.88.0.19-ca-jdk8.0.462-win_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.88.0.19-ca-jdk8.0.462-win_x64.zip"],
    +        sha256 = "ff90484103d3fdb9808f737af027586c8dbfa1aa8a310ce99b0b5e0517567aee",
    +        strip_prefix = "zulu8.90.0.19-ca-jdk8.0.472-win_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu8.90.0.19-ca-jdk8.0.472-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu8.90.0.19-ca-jdk8.0.472-win_x64.zip"],
             version = "8",
         ),
         struct(
    @@ -133,249 +133,249 @@ _REMOTE_JDK_CONFIGS_LIST = [
         struct(
             name = "remotejdk11_linux_aarch64",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"],
    -        sha256 = "f90d9eb822f68cacd536144660b43402fc8a8e922358d67e84609d7828070e6b",
    -        strip_prefix = "zulu11.82.19-ca-jdk11.0.28-linux_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-linux_aarch64.tar.gz"],
    +        sha256 = "5a225a0fe0a92bc6c04c8c5aeb03c697c6fd114465829f23e494a2ad44fa1cc0",
    +        strip_prefix = "zulu11.84.17-ca-jdk11.0.29-linux_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu11.84.17-ca-jdk11.0.29-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.84.17-ca-jdk11.0.29-linux_aarch64.tar.gz"],
             version = "11",
         ),
         struct(
             name = "remotejdk11_linux",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"],
    -        sha256 = "b34a75da63dab5f61ac342290000c1a51de3023049e2b30da89393f5f0b79759",
    -        strip_prefix = "zulu11.82.19-ca-jdk11.0.28-linux_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-linux_x64.tar.gz"],
    +        sha256 = "681b2e4bf7fedf4d20666fc2a954b83ff5675ccfb916c867267d29c85c2ee310",
    +        strip_prefix = "zulu11.84.17-ca-jdk11.0.29-linux_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu11.84.17-ca-jdk11.0.29-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.84.17-ca-jdk11.0.29-linux_x64.tar.gz"],
             version = "11",
         ),
         struct(
             name = "remotejdk11_macos_aarch64",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"],
    -        sha256 = "5b104e96bb41dc38b1605d701e4482003acffbe48e25e15ba0cb7a1611821aa7",
    -        strip_prefix = "zulu11.82.19-ca-jdk11.0.28-macosx_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-macosx_aarch64.tar.gz"],
    +        sha256 = "09ed1734c2d88fadcb75fdbec1ba5467d32e7fa2b10894541aa8e3d3ce78dc2d",
    +        strip_prefix = "zulu11.84.17-ca-jdk11.0.29-macosx_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu11.84.17-ca-jdk11.0.29-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.84.17-ca-jdk11.0.29-macosx_aarch64.tar.gz"],
             version = "11",
         ),
         struct(
             name = "remotejdk11_macos",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"],
    -        sha256 = "11c3a142f82ad10cd9e2bfc0884c36ee66de0ac1b3ed9c018e746345813f80c8",
    -        strip_prefix = "zulu11.82.19-ca-jdk11.0.28-macosx_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-macosx_x64.tar.gz"],
    +        sha256 = "b7f5a37c47ed94af1c8ecf631b1dc6dec990958f3afd4222a7dd27d6ca1084bd",
    +        strip_prefix = "zulu11.84.17-ca-jdk11.0.29-macosx_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu11.84.17-ca-jdk11.0.29-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.84.17-ca-jdk11.0.29-macosx_x64.tar.gz"],
             version = "11",
         ),
         struct(
             name = "remotejdk11_win",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"],
    -        sha256 = "728dbb971dc41be992aae950b89139e5d582f2ee7d918a06a69749fea6143fce",
    -        strip_prefix = "zulu11.82.19-ca-jdk11.0.28-win_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.82.19-ca-jdk11.0.28-win_x64.zip"],
    +        sha256 = "f4002a8090662ff66bf9f3248604be0f9d226e964085bd59bbea4b8535df3de1",
    +        strip_prefix = "zulu11.84.17-ca-jdk11.0.29-win_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu11.84.17-ca-jdk11.0.29-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu11.84.17-ca-jdk11.0.29-win_x64.zip"],
             version = "11",
         ),
         struct(
             name = "remotejdk11_linux_ppc64le",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc64le"],
    -        sha256 = "42c63651125a149cee2ba781300d75ffa67a25032f95038d50ee6d6177cb2e41",
    -        strip_prefix = "jdk-11.0.26+4",
    -        urls = ["https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.26+4/OpenJDK11U-jdk_ppc64le_linux_hotspot_11.0.26_4.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.26+4/OpenJDK11U-jdk_ppc64le_linux_hotspot_11.0.26_4.tar.gz"],
    +        sha256 = "e272abd162b3de68093630929453feba3e63a5ab1bbb912379f6a4aa968ef06a",
    +        strip_prefix = "jdk-11.0.28+6",
    +        urls = ["https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.28+6/OpenJDK11U-jdk_ppc64le_linux_hotspot_11.0.28_6.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.28+6/OpenJDK11U-jdk_ppc64le_linux_hotspot_11.0.28_6.tar.gz"],
             version = "11",
         ),
         struct(
             name = "remotejdk11_linux_s390x",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:s390x"],
    -        sha256 = "0da13d990da34ecc666399cf0efa72a4b4e295f05c0686ea25a4a173a6f4414b",
    -        strip_prefix = "jdk-11.0.26+4",
    -        urls = ["https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.26+4/OpenJDK11U-jdk_s390x_linux_hotspot_11.0.26_4.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.26+4/OpenJDK11U-jdk_s390x_linux_hotspot_11.0.26_4.tar.gz"],
    +        sha256 = "ac3f94fdcc5372e90f44fad9cd03ec0e3fd3535fea06c120f85e4a7534c6de04",
    +        strip_prefix = "jdk-11.0.28+6",
    +        urls = ["https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.28+6/OpenJDK11U-jdk_s390x_linux_hotspot_11.0.28_6.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.28+6/OpenJDK11U-jdk_s390x_linux_hotspot_11.0.28_6.tar.gz"],
             version = "11",
         ),
         struct(
             name = "remotejdk11_win_arm64",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"],
    -        sha256 = "1d10cf760e4e011e830ef18ab28453a742ac84c046e4e77759e81b58716e6a8b",
    -        strip_prefix = "jdk-11.0.26+4",
    -        urls = ["https://aka.ms/download-jdk/microsoft-jdk-11.0.26-windows-aarch64.zip", "https://mirror.bazel.build/aka.ms/download-jdk/microsoft-jdk-11.0.26-windows-aarch64.zip"],
    +        sha256 = "1e7bfad513a1c2930000db1af19c813460c7a788503c39a7f1f27375310880f8",
    +        strip_prefix = "jdk-11.0.28+6",
    +        urls = ["https://aka.ms/download-jdk/microsoft-jdk-11.0.28-windows-aarch64.zip", "https://mirror.bazel.build/aka.ms/download-jdk/microsoft-jdk-11.0.28-windows-aarch64.zip"],
             version = "11",
         ),
         struct(
             name = "remotejdk17_linux_aarch64",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"],
    -        sha256 = "1cbb51dc9400814b8fbb79252762af5eba1f556e558128f2a4fca906b2ed04c8",
    -        strip_prefix = "zulu17.60.17-ca-jdk17.0.16-linux_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-linux_aarch64.tar.gz"],
    +        sha256 = "527b76fbd60e8f9644f6b70800d15160cdbd3344bc6fbf30d42e905f540a770c",
    +        strip_prefix = "zulu17.62.17-ca-jdk17.0.17-linux_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu17.62.17-ca-jdk17.0.17-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.62.17-ca-jdk17.0.17-linux_aarch64.tar.gz"],
             version = "17",
         ),
         struct(
             name = "remotejdk17_linux",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"],
    -        sha256 = "e70822e4b77a9ffd57015b55f4bb645bba97b8f5247a792eceb95dbc7a5a55ab",
    -        strip_prefix = "zulu17.60.17-ca-jdk17.0.16-linux_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-linux_x64.tar.gz"],
    +        sha256 = "1dcbbed73e95dc35f5c60402a84936f6830ff43c2a0dc0037a5657dbc25472c1",
    +        strip_prefix = "zulu17.62.17-ca-jdk17.0.17-linux_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu17.62.17-ca-jdk17.0.17-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.62.17-ca-jdk17.0.17-linux_x64.tar.gz"],
             version = "17",
         ),
         struct(
             name = "remotejdk17_macos_aarch64",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"],
    -        sha256 = "1e23895f8edddd86dbc20a2820b1bd11695e7a6ac37f1bcee90492341aa5b32d",
    -        strip_prefix = "zulu17.60.17-ca-jdk17.0.16-macosx_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-macosx_aarch64.tar.gz"],
    +        sha256 = "5558f7efe6297ecb20f422f31471555cd43e9499beb304b8f3ddc68796d2874b",
    +        strip_prefix = "zulu17.62.17-ca-jdk17.0.17-macosx_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu17.62.17-ca-jdk17.0.17-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.62.17-ca-jdk17.0.17-macosx_aarch64.tar.gz"],
             version = "17",
         ),
         struct(
             name = "remotejdk17_macos",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"],
    -        sha256 = "6578d84c961b23f27bc7d504cb2fc45a47296bce382927d6485d404753a8a51a",
    -        strip_prefix = "zulu17.60.17-ca-jdk17.0.16-macosx_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-macosx_x64.tar.gz"],
    +        sha256 = "e6b2fb0cd3f929225a179c2fb2813abd1834f839a3b4c8cdcb36067aa16b6f83",
    +        strip_prefix = "zulu17.62.17-ca-jdk17.0.17-macosx_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu17.62.17-ca-jdk17.0.17-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.62.17-ca-jdk17.0.17-macosx_x64.tar.gz"],
             version = "17",
         ),
         struct(
             name = "remotejdk17_win_arm64",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"],
    -        sha256 = "2415163925968bfcc882e919e97f48c08eaf555947bb1b0b27291fd3fae1d462",
    -        strip_prefix = "zulu17.60.17-ca-jdk17.0.16-win_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-win_aarch64.zip"],
    +        sha256 = "c1bba9148907348da93b0de2c9abd56bd180efcb6b1f35068ab9785015fcd74b",
    +        strip_prefix = "zulu17.62.17-ca-jdk17.0.17-win_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu17.62.17-ca-jdk17.0.17-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.62.17-ca-jdk17.0.17-win_aarch64.zip"],
             version = "17",
         ),
         struct(
             name = "remotejdk17_win",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"],
    -        sha256 = "c51781710ff93fc7694668fe701c6b813aabda4e9dad6227a7d6734425b3b3ff",
    -        strip_prefix = "zulu17.60.17-ca-jdk17.0.16-win_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.60.17-ca-jdk17.0.16-win_x64.zip"],
    +        sha256 = "bd8a942bb543f109a28d3eadf3ec2f29a3ee28ab53506e31d2858292f63c6949",
    +        strip_prefix = "zulu17.62.17-ca-jdk17.0.17-win_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu17.62.17-ca-jdk17.0.17-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu17.62.17-ca-jdk17.0.17-win_x64.zip"],
             version = "17",
         ),
         struct(
             name = "remotejdk17_linux_ppc64le",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc64le"],
    -        sha256 = "f4cb9ee5906a44d110fa381310cd7181d95498d27087d449e7e9b74bddd9def2",
    -        strip_prefix = "jdk-17.0.14+7",
    -        urls = ["https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14+7/OpenJDK17U-jdk_ppc64le_linux_hotspot_17.0.14_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14+7/OpenJDK17U-jdk_ppc64le_linux_hotspot_17.0.14_7.tar.gz"],
    +        sha256 = "eb020f74e00870379522be0b44fc6322c2214e77971c258400c8b5af704d5c0a",
    +        strip_prefix = "jdk-17.0.16+8",
    +        urls = ["https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.16+8/OpenJDK17U-jdk_ppc64le_linux_hotspot_17.0.16_8.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.16+8/OpenJDK17U-jdk_ppc64le_linux_hotspot_17.0.16_8.tar.gz"],
             version = "17",
         ),
         struct(
             name = "remotejdk17_linux_s390x",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:s390x"],
    -        sha256 = "3a1d896eb3a737020e5ec95ec3206b1ca36cb365538382289d3fb46d14303648",
    -        strip_prefix = "jdk-17.0.14+7",
    -        urls = ["https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14+7/OpenJDK17U-jdk_s390x_linux_hotspot_17.0.14_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14+7/OpenJDK17U-jdk_s390x_linux_hotspot_17.0.14_7.tar.gz"],
    +        sha256 = "03dd99d34d2d1b88395765df3acbec2cb81de286f64b1d9e6df3682bee365168",
    +        strip_prefix = "jdk-17.0.16+8",
    +        urls = ["https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.16+8/OpenJDK17U-jdk_s390x_linux_hotspot_17.0.16_8.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.16+8/OpenJDK17U-jdk_s390x_linux_hotspot_17.0.16_8.tar.gz"],
             version = "17",
         ),
         struct(
             name = "remotejdk21_linux_aarch64",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"],
    -        sha256 = "ff7f2edd1d5c153cb6cb493a3aa3523453e29a05ec513b25c24aa1477ec0c722",
    -        strip_prefix = "zulu21.44.17-ca-jdk21.0.8-linux_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-linux_aarch64.tar.gz"],
    +        sha256 = "a826a93c18d4388ec8d5d4057f5bb1b5c60f00ffc875ed299dea17aa947555ee",
    +        strip_prefix = "zulu21.46.19-ca-jdk21.0.9-linux_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu21.46.19-ca-jdk21.0.9-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.46.19-ca-jdk21.0.9-linux_aarch64.tar.gz"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_linux",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"],
    -        sha256 = "63f56bbb46958cf57352fba08f2755e0953799195e5545acc0c8a92920beff1e",
    -        strip_prefix = "zulu21.44.17-ca-jdk21.0.8-linux_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-linux_x64.tar.gz"],
    +        sha256 = "67e810b31427ac0ff1c249473595066a00bdf0f9265df186c32905d5f75c93b8",
    +        strip_prefix = "zulu21.46.19-ca-jdk21.0.9-linux_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu21.46.19-ca-jdk21.0.9-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.46.19-ca-jdk21.0.9-linux_x64.tar.gz"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_macos_aarch64",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"],
    -        sha256 = "d22ce05fea3e3f28c8c59f2c348bc78ee967bf1289a4fb28796cc0177ff6c8db",
    -        strip_prefix = "zulu21.44.17-ca-jdk21.0.8-macosx_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-macosx_aarch64.tar.gz"],
    +        sha256 = "b56112ad12d3dfe62802840655ecf198fe4ca48729824c939d65a69e803536c7",
    +        strip_prefix = "zulu21.46.19-ca-jdk21.0.9-macosx_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu21.46.19-ca-jdk21.0.9-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.46.19-ca-jdk21.0.9-macosx_aarch64.tar.gz"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_macos",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"],
    -        sha256 = "2af080500b5cc286a6353187c7c59b5aafcb3edc29c1c87d1fd71ba2d6a523f1",
    -        strip_prefix = "zulu21.44.17-ca-jdk21.0.8-macosx_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-macosx_x64.tar.gz"],
    +        sha256 = "3d870d823e3e101189b00ad975188c0321e31056ac8ca8b487bcf4454f3b5cfe",
    +        strip_prefix = "zulu21.46.19-ca-jdk21.0.9-macosx_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu21.46.19-ca-jdk21.0.9-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.46.19-ca-jdk21.0.9-macosx_x64.tar.gz"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_win_arm64",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"],
    -        sha256 = "76379d799e766fb7ea1cdaacc67aa87f75a118f863cc68ffe32c251be94ab4f4",
    -        strip_prefix = "zulu21.44.17-ca-jdk21.0.8-win_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-win_aarch64.zip"],
    +        sha256 = "1210b169db7b40d7305a94d41ab3eb87aaee51108b43f8f7f36f0c2865107790",
    +        strip_prefix = "zulu21.46.19-ca-jdk21.0.9-win_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu21.46.19-ca-jdk21.0.9-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.46.19-ca-jdk21.0.9-win_aarch64.zip"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_win",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"],
    -        sha256 = "f47dbd00384cb759f86a066be7545e467e5764f4653a237c32c07da96dc1c43b",
    -        strip_prefix = "zulu21.44.17-ca-jdk21.0.8-win_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.44.17-ca-jdk21.0.8-win_x64.zip"],
    +        sha256 = "0c9812c0fe527b59f48c70cb527035c8a7abe620b31f776b4ddc21bddc1cd067",
    +        strip_prefix = "zulu21.46.19-ca-jdk21.0.9-win_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu21.46.19-ca-jdk21.0.9-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu21.46.19-ca-jdk21.0.9-win_x64.zip"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_linux_ppc64le",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc64le"],
    -        sha256 = "163724b70b86d5a8461f85092165a9cc5a098ed900fee90d1b0c0be9607ae3d2",
    -        strip_prefix = "jdk-21.0.6+7",
    -        urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.6_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.6_7.tar.gz"],
    +        sha256 = "a24e869b8e563fd7b9f7776f6686ca5d737c8d1c3c33c9b72836935709b44a34",
    +        strip_prefix = "jdk-21.0.8+9",
    +        urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.8+9/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.8_9.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.8+9/OpenJDK21U-jdk_ppc64le_linux_hotspot_21.0.8_9.tar.gz"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_linux_riscv64",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:riscv64"],
    -        sha256 = "203796e4ba2689aa921b5e0cdc9e02984d88622f80fcb9acb05a118b05007be8",
    -        strip_prefix = "jdk-21.0.6+7",
    -        urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_riscv64_linux_hotspot_21.0.6_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_riscv64_linux_hotspot_21.0.6_7.tar.gz"],
    +        sha256 = "8171d95189e675e297b5cb96c7ac6247ab4e9f48da82b13f491fc46ef5d97836",
    +        strip_prefix = "jdk-21.0.8+9",
    +        urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.8+9/OpenJDK21U-jdk_riscv64_linux_hotspot_21.0.8_9.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.8+9/OpenJDK21U-jdk_riscv64_linux_hotspot_21.0.8_9.tar.gz"],
             version = "21",
         ),
         struct(
             name = "remotejdk21_linux_s390x",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:s390x"],
    -        sha256 = "5ba742c87d48fcf564def56812699f6499a1cfd3535ae43286e94e74b8165faf",
    -        strip_prefix = "jdk-21.0.6+7",
    -        urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.6_7.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.6+7/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.6_7.tar.gz"],
    +        sha256 = "a84e3cbf8bb5f8a313e06b790c7bc388687ba00262e981f5e33432ebd4d34356",
    +        strip_prefix = "jdk-21.0.8+9",
    +        urls = ["https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.8+9/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.8_9.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.8+9/OpenJDK21U-jdk_s390x_linux_hotspot_21.0.8_9.tar.gz"],
             version = "21",
         ),
         struct(
             name = "remotejdk25_linux_aarch64",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"],
    -        sha256 = "b60eb9d54c97ba4159547834a98cc5d016281dd2b3e60e7475cba4911324bcb4",
    -        strip_prefix = "zulu25.28.85-ca-jdk25.0.0-linux_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-linux_aarch64.tar.gz"],
    +        sha256 = "8c5321f16d9f1d8149f83e4e9ff8ca5d9e94320b92d205e6db42a604de3d1140",
    +        strip_prefix = "zulu25.30.17-ca-jdk25.0.1-linux_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-linux_aarch64.tar.gz"],
             version = "25",
         ),
         struct(
             name = "remotejdk25_linux",
             target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"],
    -        sha256 = "164d901e5a240b8c18516f5ab55bc11fc9689ab6e829045aea8467356dcdb340",
    -        strip_prefix = "zulu25.28.85-ca-jdk25.0.0-linux_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-linux_x64.tar.gz"],
    +        sha256 = "471b3e62bdffaed27e37005d842d8639f10d244ccce1c7cdebf7abce06c8313e",
    +        strip_prefix = "zulu25.30.17-ca-jdk25.0.1-linux_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-linux_x64.tar.gz"],
             version = "25",
         ),
         struct(
             name = "remotejdk25_macos_aarch64",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"],
    -        sha256 = "73f64f6bad7c3df31fba740fbcbbbef7c1a5cedeffbb5df386dd79bc72aba9b6",
    -        strip_prefix = "zulu25.28.85-ca-jdk25.0.0-macosx_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-macosx_aarch64.tar.gz"],
    +        sha256 = "126061d6046b0c0df0472b361ca7895951d34fef1dd522f222f2c7d8738a39d8",
    +        strip_prefix = "zulu25.30.17-ca-jdk25.0.1-macosx_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-macosx_aarch64.tar.gz"],
             version = "25",
         ),
         struct(
             name = "remotejdk25_macos",
             target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"],
    -        sha256 = "c2cde1d313d904b793c3760214eefa207ecca7df04e7c4084abdf1f6bbebc27a",
    -        strip_prefix = "zulu25.28.85-ca-jdk25.0.0-macosx_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-macosx_x64.tar.gz"],
    +        sha256 = "0154482b317aa63d5158a358e2fab7f0fd6c3c0ba2000b05655c3bcbdd202584",
    +        strip_prefix = "zulu25.30.17-ca-jdk25.0.1-macosx_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-macosx_x64.tar.gz"],
             version = "25",
         ),
         struct(
             name = "remotejdk25_win_arm64",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"],
    -        sha256 = "f5f6d8a913695649e8e2607fe0dc79c81953b2583013ac1fb977c63cb4935bfb",
    -        strip_prefix = "zulu25.28.85-ca-jdk25.0.0-win_aarch64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-win_aarch64.zip"],
    +        sha256 = "4883cf39e8d83679c8a051ace4dd72759d97195a72aaa6727a83bd4bcb97b022",
    +        strip_prefix = "zulu25.30.17-ca-jdk25.0.1-win_aarch64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-win_aarch64.zip"],
             version = "25",
         ),
         struct(
             name = "remotejdk25_win",
             target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"],
    -        sha256 = "5efcf4e6a613cae06c8041de8a3695b7346aad0307d397b66bf55281cf1a5cb6",
    -        strip_prefix = "zulu25.28.85-ca-jdk25.0.0-win_x64",
    -        urls = ["https://cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.28.85-ca-jdk25.0.0-win_x64.zip"],
    +        sha256 = "72844ba8dddf9259ab9cfda9d515d0c850179705f74278a75973d73f0c5b2d2b",
    +        strip_prefix = "zulu25.30.17-ca-jdk25.0.1-win_x64",
    +        urls = ["https://cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-win_x64.zip"],
             version = "25",
         ),
     ]
    diff --git a/test/check_remote_jdk_configs.sh b/test/check_remote_jdk_configs.sh
    index 1b58c96d..b1c509fe 100755
    --- a/test/check_remote_jdk_configs.sh
    +++ b/test/check_remote_jdk_configs.sh
    @@ -40,12 +40,12 @@ for config in "$@"; do
         fi
         if [[ -n "${mirror_url}" ]]; then
           echo "checking mirror: ${mirror_url}"
    -      curl --silent --fail -I -L ${mirror_url} > /dev/null || { _MISSING_MIRRORS+=("${mirror_url}"); }
    +      curl --silent --fail -I -L ${mirror_url} > /dev/null || { _MISSING_MIRRORS+=("${url}"); }
         fi
     done
     
     if [[ ${#_MISSING_MIRRORS[@]} -gt 0 ]]; then
    -  echo "Missing mirror URLs:"
    +  echo "URLs that aren't mirrored:"
       for m in "${_MISSING_MIRRORS[@]}"; do
         echo "  ${m}"
       done
    
    From 9073b05c545ceceedbbca001a7429c5d8a6d2219 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Tue, 4 Nov 2025 06:03:51 -0800
    Subject: [PATCH 334/465] Update `rules_cc` dep to fix CI
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 827934830
    Change-Id: Ic3416c7bcb65b8c07a2e3e62556bc02ea7e5fb9f
    ---
     MODULE.bazel | 9 ++++++++-
     1 file changed, 8 insertions(+), 1 deletion(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index 01888063..789d597d 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -6,7 +6,14 @@ module(
     )
     
     bazel_dep(name = "platforms", version = "0.0.11")
    -bazel_dep(name = "rules_cc", version = "0.2.8")
    +bazel_dep(name = "rules_cc", version = "0.2.13")
    +archive_override(
    +    module_name = "rules_cc",
    +    integrity = "sha256-y3RA9zEyB7HqBXVTgrlFmvfJARcEDzILe2ugNGC4ZrE=",
    +    strip_prefix = "rules_cc-b5a65591334f74371f4d75003768957a740cd868",
    +    urls = ["https://github.com/bazelbuild/rules_cc/archive/b5a65591334f74371f4d75003768957a740cd868.tar.gz"],
    +)
    +
     bazel_dep(name = "bazel_features", version = "1.30.0")
     bazel_dep(name = "bazel_skylib", version = "1.6.1")
     bazel_dep(name = "protobuf", version = "32.1", repo_name = "com_google_protobuf")
    
    From 8bf8a941c42906219e93fc678ebbfcbe7c38bdef Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Tue, 4 Nov 2025 06:30:43 -0800
    Subject: [PATCH 335/465] Release `@rules_java` `v9.0.0`
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 827944657
    Change-Id: I9eaeb89b7a3481e1eee615f718683ffb7ff955f7
    ---
     MODULE.bazel | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index 789d597d..e19c4e3f 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -1,6 +1,6 @@
     module(
         name = "rules_java",
    -    version = "8.16.1",
    +    version = "9.0.0",
         bazel_compatibility = [">=6.4.0"],
         compatibility_level = 1,
     )
    
    From b1376ddb00e54b7c381c43fc74dc7c269cb8d057 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Tue, 4 Nov 2025 11:14:52 -0800
    Subject: [PATCH 336/465] Add support for an unstripped bootclasspath
    
    Running the bootclasspath through ijar was added in https://github.com/bazelbuild/rules_java/pull/324 and was always enabled. This change lets us selectively disable it. This ensures we don't end up depending on the prebuilt ijar in the non-prebuilt toolchain case. This is also needed to bootstrap bazel where we don't have access to `@remote_java_tools`
    
    PiperOrigin-RevId: 828056087
    Change-Id: I38402112139221cea606b64110fb1854795a8113
    ---
     toolchains/BUILD                      | 11 +++++++++++
     toolchains/bootclasspath.bzl          |  3 ++-
     toolchains/default_java_toolchain.bzl |  1 +
     3 files changed, 14 insertions(+), 1 deletion(-)
    
    diff --git a/toolchains/BUILD b/toolchains/BUILD
    index bb6ecf7a..41a4f533 100644
    --- a/toolchains/BUILD
    +++ b/toolchains/BUILD
    @@ -351,6 +351,17 @@ bootclasspath(
         }),
     )
     
    +bootclasspath(
    +    name = "platformclasspath_unstripped",
    +    src = "DumpPlatformClassPath.java",
    +    java_runtime_alias = ":current_java_runtime",
    +    language_version_bootstrap_runtime = select({
    +        ":incompatible_language_version_bootclasspath_enabled": ":language_version_bootstrap_runtime",
    +        "//conditions:default": None,
    +    }),
    +    strip = False,
    +)
    +
     default_java_toolchain(
         name = "toolchain",
         configuration = DEFAULT_TOOLCHAIN_CONFIGURATION,
    diff --git a/toolchains/bootclasspath.bzl b/toolchains/bootclasspath.bzl
    index 5b4187c7..945a73c3 100644
    --- a/toolchains/bootclasspath.bzl
    +++ b/toolchains/bootclasspath.bzl
    @@ -231,7 +231,7 @@ Rerun with --toolchain_resolution_debug='@bazel_tools//tools/jdk:bootstrap_runti
             input = unstripped_bootclasspath,
             output = bootclasspath,
         )
    -
    +    bootclasspath = bootclasspath if ctx.attr.strip else unstripped_bootclasspath
         return [
             DefaultInfo(files = depset([bootclasspath])),
             java_common.BootClassPathInfo(
    @@ -256,6 +256,7 @@ _bootclasspath = rule(
                 cfg = "exec",
                 allow_single_file = True,
             ),
    +        "strip": attr.bool(default = True),
             "_allowlist_function_transition": attr.label(
                 default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
             ),
    diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl
    index 5d1d54a5..b08e4919 100644
    --- a/toolchains/default_java_toolchain.bzl
    +++ b/toolchains/default_java_toolchain.bzl
    @@ -143,6 +143,7 @@ NONPREBUILT_TOOLCHAIN_CONFIGURATION = dict(
         singlejar = [Label("@remote_java_tools//:singlejar_cc_bin")],
         header_compiler_direct = [Label("@remote_java_tools//:TurbineDirect")],
         oneversion = Label("@remote_java_tools//:one_version_cc_bin"),
    +    bootclasspath = [Label("//toolchains:platformclasspath_unstripped")],
     )
     
     def default_java_toolchain(name, configuration = DEFAULT_TOOLCHAIN_CONFIGURATION, toolchain_definition = True, exec_compatible_with = [], target_compatible_with = [], **kwargs):
    
    From 67e83ef06b854fef89cec3a96c158afd99456055 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 5 Nov 2025 01:22:54 -0800
    Subject: [PATCH 337/465] Release `@rules_java` `v9.0.1`
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 828351782
    Change-Id: I12177c7b9e28ad8673f4da4d6cc3bffbb5fadc41
    ---
     MODULE.bazel | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index e19c4e3f..34928f56 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -1,6 +1,6 @@
     module(
         name = "rules_java",
    -    version = "9.0.0",
    +    version = "9.0.1",
         bazel_compatibility = [">=6.4.0"],
         compatibility_level = 1,
     )
    
    From a27c7de6503387a5d3675d373979c40621413552 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 5 Nov 2025 02:07:13 -0800
    Subject: [PATCH 338/465] Cut the dependency on ijar when not stripping the
     bootclasspath
    
    Rule deps are fetched eagerly, even if unused, so we need to actually cut the edge to ijar when not stripping for bazel bootstrapping to succeed.
    
    Unfortunately, with the way Bazel integration tests are set up, there's no way to test this with Bazel without making a release. I manually verified that `bazel query deps()` reports the right results and the targets build correctly.
    
    ```
    $ bazel query 'deps(//toolchains:platformclasspath, 1)'
    //:license
    //toolchains:DumpPlatformClassPath.java
    //toolchains:current_java_runtime
    //toolchains:ijar
    //toolchains:incompatible_language_version_bootclasspath_enabled
    //toolchains:language_version_bootstrap_runtime
    //toolchains:platformclasspath
    //toolchains:utf8_environment
    @bazel_tools//tools/allowlists/function_transition_allowlist:function_transition_allowlist
    @bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type
    
    $ bazel query 'deps(//toolchains:platformclasspath_unstripped, 1)'
    //:license
    //toolchains:DumpPlatformClassPath.java
    //toolchains:current_java_runtime
    //toolchains:incompatible_language_version_bootclasspath_enabled
    //toolchains:language_version_bootstrap_runtime
    //toolchains:platformclasspath_unstripped
    //toolchains:utf8_environment
    @bazel_tools//tools/allowlists/function_transition_allowlist:function_transition_allowlist
    @bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type
    ```
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 828368783
    Change-Id: Ie29eea882ad41e4efa8f1dd752679a221a239ae1
    ---
     toolchains/bootclasspath.bzl | 23 ++++++++++++++---------
     1 file changed, 14 insertions(+), 9 deletions(-)
    
    diff --git a/toolchains/bootclasspath.bzl b/toolchains/bootclasspath.bzl
    index 945a73c3..93da5de8 100644
    --- a/toolchains/bootclasspath.bzl
    +++ b/toolchains/bootclasspath.bzl
    @@ -224,14 +224,16 @@ Rerun with --toolchain_resolution_debug='@bazel_tools//tools/jdk:bootstrap_runti
         )
     
         bootclasspath = ctx.outputs.output_jar
    -    _run_ijar(
    -        actions = ctx.actions,
    -        label = ctx.label,
    -        ijar = ctx.executable._ijar,
    -        input = unstripped_bootclasspath,
    -        output = bootclasspath,
    -    )
    -    bootclasspath = bootclasspath if ctx.attr.strip else unstripped_bootclasspath
    +    if ctx.attr.strip:
    +        _run_ijar(
    +            actions = ctx.actions,
    +            label = ctx.label,
    +            ijar = ctx.executable._ijar,
    +            input = unstripped_bootclasspath,
    +            output = bootclasspath,
    +        )
    +    else:
    +        ctx.actions.symlink(output = bootclasspath, target_file = unstripped_bootclasspath)
         return [
             DefaultInfo(files = depset([bootclasspath])),
             java_common.BootClassPathInfo(
    @@ -241,6 +243,9 @@ Rerun with --toolchain_resolution_debug='@bazel_tools//tools/jdk:bootstrap_runti
             OutputGroupInfo(jar = [bootclasspath]),
         ]
     
    +def _compute_ijar(strip):
    +    return Label("//toolchains:ijar") if strip else None
    +
     _bootclasspath = rule(
         implementation = _bootclasspath_impl,
         attrs = {
    @@ -261,7 +266,7 @@ _bootclasspath = rule(
                 default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
             ),
             "_ijar": attr.label(
    -            default = "//toolchains:ijar",
    +            default = _compute_ijar,
                 cfg = "exec",
                 executable = True,
             ),
    
    From 56177d044e0d4e193c14549dd1d0c0c0c78f3f01 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 5 Nov 2025 02:15:26 -0800
    Subject: [PATCH 339/465] Release `@rules_java` `v9.0.2`
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 828371518
    Change-Id: I1b578bf0d5e32ae4097b3c2885bb68ff8cfe64c9
    ---
     MODULE.bazel | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index 34928f56..cfae101b 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -1,6 +1,6 @@
     module(
         name = "rules_java",
    -    version = "9.0.1",
    +    version = "9.0.2",
         bazel_compatibility = [">=6.4.0"],
         compatibility_level = 1,
     )
    
    From 9b84026b40dfdba5e57db814dc70793fca0e66cc Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 5 Nov 2025 03:25:26 -0800
    Subject: [PATCH 340/465] Rename target to avoid artifact conflict
    
    The `bootclasspath` rule internally generates a (intermediate) `{name}_unstripped.jar` artifact which conflicts with the output of the `//toolchains:platformclasspath_unstripped` target
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 828390314
    Change-Id: I3a5a21a52c6697c1497db295277a2c96c52df5a9
    ---
     toolchains/BUILD                      | 2 +-
     toolchains/default_java_toolchain.bzl | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/toolchains/BUILD b/toolchains/BUILD
    index 41a4f533..0f3ef2bf 100644
    --- a/toolchains/BUILD
    +++ b/toolchains/BUILD
    @@ -352,7 +352,7 @@ bootclasspath(
     )
     
     bootclasspath(
    -    name = "platformclasspath_unstripped",
    +    name = "platformclasspath_nostrip",
         src = "DumpPlatformClassPath.java",
         java_runtime_alias = ":current_java_runtime",
         language_version_bootstrap_runtime = select({
    diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl
    index b08e4919..7b113ef6 100644
    --- a/toolchains/default_java_toolchain.bzl
    +++ b/toolchains/default_java_toolchain.bzl
    @@ -143,7 +143,7 @@ NONPREBUILT_TOOLCHAIN_CONFIGURATION = dict(
         singlejar = [Label("@remote_java_tools//:singlejar_cc_bin")],
         header_compiler_direct = [Label("@remote_java_tools//:TurbineDirect")],
         oneversion = Label("@remote_java_tools//:one_version_cc_bin"),
    -    bootclasspath = [Label("//toolchains:platformclasspath_unstripped")],
    +    bootclasspath = [Label("//toolchains:platformclasspath_nostrip")],
     )
     
     def default_java_toolchain(name, configuration = DEFAULT_TOOLCHAIN_CONFIGURATION, toolchain_definition = True, exec_compatible_with = [], target_compatible_with = [], **kwargs):
    
    From 8427063e872aa3bddf1d091c3faa129d9395a261 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 5 Nov 2025 03:38:11 -0800
    Subject: [PATCH 341/465] Release `@rules_java` `v9.0.3`
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 828394095
    Change-Id: I5d740a68b8293ef2da450371416867002e9794e2
    ---
     MODULE.bazel | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/MODULE.bazel b/MODULE.bazel
    index cfae101b..0de3d565 100644
    --- a/MODULE.bazel
    +++ b/MODULE.bazel
    @@ -1,6 +1,6 @@
     module(
         name = "rules_java",
    -    version = "9.0.2",
    +    version = "9.0.3",
         bazel_compatibility = [">=6.4.0"],
         compatibility_level = 1,
     )
    
    From aa153f057a204f6212ec766029ff9df2b4c0285c Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Fri, 14 Nov 2025 02:14:36 -0800
    Subject: [PATCH 342/465] Execute the `check_remote_java_tools_configs_test`
     only on a single platform
    
    The test is platform / bazel independent and is wasteful to run on all platforms / bazel combinations
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 832226923
    Change-Id: I74ede6ccf16f8f5ec4331ee258495e386188026d
    ---
     .bazelci/presubmit.yml | 1 +
     test/BUILD.bazel       | 1 +
     2 files changed, 2 insertions(+)
    
    diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml
    index b77fe7dc..3a603039 100644
    --- a/.bazelci/presubmit.yml
    +++ b/.bazelci/presubmit.yml
    @@ -135,4 +135,5 @@ tasks:
           - "git commit --allow-empty -m 'Fake commit message for testing'"
         test_targets:
           - "//test:check_remote_jdk_configs_test"
    +      - "//test:check_remote_java_tools_configs_test"
           - "//test:check_release_notes_test"
    diff --git a/test/BUILD.bazel b/test/BUILD.bazel
    index 084ff40c..964c77cb 100644
    --- a/test/BUILD.bazel
    +++ b/test/BUILD.bazel
    @@ -48,6 +48,7 @@ sh_test(
             ])
             for name, config in JAVA_TOOLS_CONFIG["artifacts"].items()
         ],
    +    tags = ["manual"],  # explicitly tested only on Linux
     )
     
     sh_test(
    
    From 6ea00a46a9e5498d748d6ae843c87e21c9e8b1d9 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Fri, 14 Nov 2025 08:11:13 -0800
    Subject: [PATCH 343/465] Internal change
    
    PiperOrigin-RevId: 832321939
    Change-Id: Icb4f46359980d7ed1734ade08d2834ef3265c289
    ---
     java/java_single_jar.bzl | 6 ++++++
     1 file changed, 6 insertions(+)
    
    diff --git a/java/java_single_jar.bzl b/java/java_single_jar.bzl
    index 48aa45c3..e51329ef 100644
    --- a/java/java_single_jar.bzl
    +++ b/java/java_single_jar.bzl
    @@ -59,6 +59,9 @@ def _java_single_jar(ctx):
         if ctx.attr.multi_release:
             args.add("--multi_release")
     
    +    if ctx.attr.exclude_pattern:
    +        args.add("--exclude_pattern", ctx.attr.exclude_pattern)
    +
         ctx.actions.run(
             inputs = inputs,
             outputs = [ctx.outputs.jar],
    @@ -110,6 +113,9 @@ java_single_jar = rule(
                 Whether to omit the build-data.properties file generated
                 by default."""),
             "multi_release": attr.bool(default = True, doc = """Whether to enable Multi-Release output jars."""),
    +        "exclude_pattern": attr.string(default = "", doc = """
    +            A regex pattern of files to exclude from the jar.
    +        """),
             "_singlejar": attr.label(
                 default = Label("//toolchains:singlejar"),
                 cfg = "exec",
    
    From d4159a222e9ac0635aa3b2b39d1f0ab655846344 Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 19 Nov 2025 02:49:53 -0800
    Subject: [PATCH 344/465] Fix bazel version check in
     `local_java_repository.bzl`
    
    With the latest rolling release version hitting `10.x`, we can no longer rely on simple string comparision.
    
    PiperOrigin-RevId: 834204982
    Change-Id: Idb37877d983287787b6b997d4a01385164608a46
    ---
     toolchains/local_java_repository.bzl | 4 ++--
     1 file changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/toolchains/local_java_repository.bzl b/toolchains/local_java_repository.bzl
    index 075f54d6..ba526a14 100644
    --- a/toolchains/local_java_repository.bzl
    +++ b/toolchains/local_java_repository.bzl
    @@ -14,6 +14,7 @@
     
     """Rules for importing a local JDK."""
     
    +load("@bazel_features//private:util.bzl", _bazel_version_ge = "ge")
     load("//java/toolchains:java_runtime.bzl", "java_runtime")
     load(":default_java_toolchain.bzl", "default_java_toolchain")
     
    @@ -235,8 +236,7 @@ local_java_runtime(
     )
     """ % (local_java_runtime_name, runtime_name, java_home, version)
     
    -    bazel = native.bazel_version
    -    if not bazel or bazel >= "7":
    +    if _bazel_version_ge("7.0.0"):
             # Bazel 7+ uses @platforms//host for the host platform.
             load_host_constraints = 'load("@platforms//host:constraints.bzl", "HOST_CONSTRAINTS")\n'
         else:
    
    From 19936576119852560c1bd21bcd29a0ae1d629cbc Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 19 Nov 2025 04:32:14 -0800
    Subject: [PATCH 345/465] Enable C++ rules and providers
    
    PiperOrigin-RevId: 834233788
    Change-Id: Id4d969bb98ec7121be1d41f7e4eed179090e5d63
    ---
     java/BUILD | 3 ++-
     1 file changed, 2 insertions(+), 1 deletion(-)
    
    diff --git a/java/BUILD b/java/BUILD
    index 452c7654..18bbe33e 100644
    --- a/java/BUILD
    +++ b/java/BUILD
    @@ -83,9 +83,10 @@ filegroup(
             ":core_rules",
             ":java_single_jar",
             ":rules",
    +        # TODO(bazel-team@): Add for_bazel_tests from rules_cc
    +        "//java/common:for_bazel_tests",
             "//java/bazel:for_bazel_tests",  # copybara-use-repo-external-label
             "//java/bazel/rules:for_bazel_tests",  # copybara-use-repo-external-label
    -        "//java/common:for_bazel_tests",
             "//java/private:for_bazel_tests",
             "//java/toolchains:for_bazel_tests",
             "@bazel_skylib//:test_deps",
    
    From 37b099cfd27de53495aea44763a16cd23ff929df Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 19 Nov 2025 07:40:00 -0800
    Subject: [PATCH 346/465] Refactor java_single_jar to allow custom output
     names.
    
    PiperOrigin-RevId: 834288538
    Change-Id: I18bd305a6870e74db4136f3dc78ffebefaaf91cd
    ---
     java/java_single_jar.bzl | 18 +++++++++++-------
     1 file changed, 11 insertions(+), 7 deletions(-)
    
    diff --git a/java/java_single_jar.bzl b/java/java_single_jar.bzl
    index e51329ef..bfdd21c0 100644
    --- a/java/java_single_jar.bzl
    +++ b/java/java_single_jar.bzl
    @@ -40,7 +40,7 @@ def _java_single_jar(ctx):
         args.use_param_file("@%s")
         args.set_param_file_format("multiline")
         args.add_all("--deploy_manifest_lines", ctx.attr.deploy_manifest_lines)
    -    args.add("--output", ctx.outputs.jar)
    +    args.add("--output", ctx.outputs.output)
         args.add("--normalize")
     
         # Deal with limitation of singlejar flags: tool's default behavior is
    @@ -64,15 +64,15 @@ def _java_single_jar(ctx):
     
         ctx.actions.run(
             inputs = inputs,
    -        outputs = [ctx.outputs.jar],
    +        outputs = [ctx.outputs.output],
             arguments = [args],
    -        progress_message = "Merging into %s" % ctx.outputs.jar.short_path,
    +        progress_message = "Merging into %s" % ctx.outputs.output.short_path,
             mnemonic = "JavaSingleJar",
             executable = ctx.executable._singlejar,
             use_default_shell_env = True,
         )
     
    -    files = depset([ctx.outputs.jar])
    +    files = depset([ctx.outputs.output])
         providers = [DefaultInfo(
             files = files,
             runfiles = ctx.runfiles(transitive_files = files),
    @@ -81,6 +81,11 @@ def _java_single_jar(ctx):
             providers.append(java_common.JavaRuntimeClasspathInfo(runtime_classpath = inputs))
         return providers
     
    +def _init(name, **kwargs):
    +    if "output" not in kwargs:
    +        kwargs["output"] = name + ".jar"
    +    return kwargs
    +
     java_single_jar = rule(
         attrs = {
             "deps": attr.label_list(
    @@ -122,10 +127,9 @@ java_single_jar = rule(
                 allow_single_file = True,
                 executable = True,
             ),
    +        "output": attr.output(),
         },
    -    outputs = {
    -        "jar": "%{name}.jar",
    -    },
    +    initializer = _init,
         implementation = _java_single_jar,
         doc = """
     Collects Java dependencies and jar files into a single jar
    
    From 542f5fa212472bbb4fd65cd2bb7ae08bedd79b4a Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Wed, 19 Nov 2025 21:48:40 -0800
    Subject: [PATCH 347/465] Delete non-actionable `TODO`
    
    (ignore-relnotes)
    
    PiperOrigin-RevId: 834586059
    Change-Id: I6669c6c4aaf48d632ddb1f2c6abd675160c55438
    ---
     java/BUILD | 3 +--
     1 file changed, 1 insertion(+), 2 deletions(-)
    
    diff --git a/java/BUILD b/java/BUILD
    index 18bbe33e..452c7654 100644
    --- a/java/BUILD
    +++ b/java/BUILD
    @@ -83,10 +83,9 @@ filegroup(
             ":core_rules",
             ":java_single_jar",
             ":rules",
    -        # TODO(bazel-team@): Add for_bazel_tests from rules_cc
    -        "//java/common:for_bazel_tests",
             "//java/bazel:for_bazel_tests",  # copybara-use-repo-external-label
             "//java/bazel/rules:for_bazel_tests",  # copybara-use-repo-external-label
    +        "//java/common:for_bazel_tests",
             "//java/private:for_bazel_tests",
             "//java/toolchains:for_bazel_tests",
             "@bazel_skylib//:test_deps",
    
    From e515e2df8deda5dac0deb419cd46eafc9e224d3c Mon Sep 17 00:00:00 2001
    From: Googler 
    Date: Mon, 24 Nov 2025 04:27:05 -0800
    Subject: [PATCH 348/465] Fix typo in `java_binary.bzl` comment.
    
    Removed an extra closing parenthesis from the `classpath_resources` attribute documentation.
    
    PiperOrigin-RevId: 836167105
    Change-Id: I22a2c9f6790f2a448e0ce983afcae2ae56f4d3cb
    ---
     java/common/rules/java_binary.bzl | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/java/common/rules/java_binary.bzl b/java/common/rules/java_binary.bzl
    index cdd79f29..609ca974 100644
    --- a/java/common/rules/java_binary.bzl
    +++ b/java/common/rules/java_binary.bzl
    @@ -303,7 +303,7 @@ will be ignored for this target.
             "classpath_resources": attr.label_list(
                 allow_files = True,
                 doc = """
    -DO NOT USE THIS OPTION UNLESS THERE IS NO OTHER WAY)
    +DO NOT USE THIS OPTION UNLESS THERE IS NO OTHER WAY
     

    A list of resources that must be located at the root of the java tree. This attribute's only purpose is to support third-party libraries that require that their resources be From b55339e359675d03a4f1cc001f1840d0b27966df Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 26 Nov 2025 02:20:52 -0800 Subject: [PATCH 349/465] Drop support for Bazel 6 Bazel 6.5.0 is EOL in Dec 2025 (https://bazel.build/release#support-matrix) Also bump other supported bazel versions to their latest minor/patch in CI PiperOrigin-RevId: 837025814 Change-Id: If9ea408f3f1df8e47279453d1bca2db9fefeb57e --- .bazelci/presubmit.yml | 43 +++++------------------------------------- MODULE.bazel | 2 +- 2 files changed, 6 insertions(+), 39 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 3a603039..4fe6a435 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -14,15 +14,6 @@ build_targets: &build_targets - "-//java/docs/..." - "-//test:docs_up_to_date_test" -build_targets_bazel6: &build_targets_bazel6 - - "//:all" - # build java_tools from source - - "@remote_java_tools//:ijar_cc_binary" - - "@remote_java_tools//:one_version_cc_bin" - - "@remote_java_tools//:proguard" - - "@remote_java_tools//:singlejar_cc_bin" - - "//examples/..." - build_targets_integration: &build_targets_integration - "//..." - "//:bin_deploy.jar" @@ -32,10 +23,6 @@ test_targets: &test_targets # TODO: re-enable docs after moving them out of https://bazel.build/reference/be/java - "-//test:docs_up_to_date_test" -test_targets_bazel6: &test_targets_bazel6 - - "//test/java/..." - - "-//test/java/private/..." - test_target_integration: &test_target_integration - "//:MyTest" @@ -47,7 +34,7 @@ buildifier: latest matrix: all_platforms: ["rockylinux8_arm64", "ubuntu2004", "macos", "macos_arm64", "windows"] - bazel: ["7.6.1", "8.4.0", "last_green"] # Bazel 6 tested separately, needs different flags + bazel: ["7.7.1", "8.4.2", "last_green"] modern_bazel: ["last_green", "rolling"] # Fully supported Bazel versions tasks: @@ -60,8 +47,8 @@ tasks: test_targets: *test_targets # Bazel 8.x build_and_test_bazel8: - name: "Bazel 8.4.0" - bazel: "8.4.0" + name: "Bazel 8.4.2" + bazel: "8.4.2" platform: ${{ all_platforms }} build_targets: *build_targets test_targets: *test_targets @@ -69,33 +56,13 @@ tasks: - "--test_tag_filters=-min_bazel_9" # Bazel 7.x build_and_test_bazel7: - name: "Bazel 7.6.1" - bazel: "7.6.1" + name: "Bazel 7.7.1" + bazel: "7.7.1" platform: ${{ all_platforms }} build_targets: *build_targets test_targets: *test_targets test_flags: - "--test_tag_filters=-min_bazel_8,-min_bazel_9" -# Bazel 6.x - build_and_test_bazel6: - name: "Bazel 6.5.0" - bazel: 6.5.0 - platform: ${{ all_platforms }} - build_targets: *build_targets_bazel6 - test_targets: *test_targets_bazel6 - test_flags: - - "--test_tag_filters=-min_bazel_7,-min_bazel_8,-min_bazel_9" - ubuntu2004_integration_bazel6: - name: "Integration w/ Bazel 6.5.0" - bazel: 6.5.0 - platform: ${{ all_platforms }} - working_directory: "test/repo" - shell_commands: - - sh setup.sh - batch_commands: - - setup.bat - build_targets: *build_targets_integration - test_targets: *test_target_integration # Integration tests integration_build_and_test: diff --git a/MODULE.bazel b/MODULE.bazel index 0de3d565..8c2a672a 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,7 +1,7 @@ module( name = "rules_java", version = "9.0.3", - bazel_compatibility = [">=6.4.0"], + bazel_compatibility = [">=7.0.0"], compatibility_level = 1, ) From b5b4100314da5732854f8c72d0e1c1b2902100ab Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 26 Nov 2025 03:00:41 -0800 Subject: [PATCH 350/465] Prepare to remove _LEGACY_ANY_TYPE_ATTRS workaround in java_toolchain PiperOrigin-RevId: 837039389 Change-Id: Ib484a607424abb1558651f73d7e12bea9ec8ad47 --- java/common/rules/java_toolchain.bzl | 1 + test/java/toolchains/java_toolchain_tests.bzl | 8 +++---- toolchains/default_java_toolchain.bzl | 24 +++++++++---------- 3 files changed, 17 insertions(+), 16 deletions(-) diff --git a/java/common/rules/java_toolchain.bzl b/java/common/rules/java_toolchain.bzl index fe32fc36..6aed2ecd 100644 --- a/java/common/rules/java_toolchain.bzl +++ b/java/common/rules/java_toolchain.bzl @@ -240,6 +240,7 @@ def _extract_singleton_list_value(dict, key): else: dict[key] = None +# TODO: b/463873596 - remove this in Bazel 10 _LEGACY_ANY_TYPE_ATTRS = [ "genclass", "deps_checker", diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index 378ba910..928ce00b 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -13,12 +13,12 @@ def _declare_java_toolchain(*, name, **kwargs): util.helper_target( java_toolchain, name = name, - genclass = [kwargs.get("genclass", "default_genclass.jar")], + genclass = kwargs.get("genclass", "default_genclass.jar"), jacocorunner = kwargs.get("jacocorunner", None), - javabuilder = [kwargs.get("javabuilder", "default_javabuilder.jar")], + javabuilder = kwargs.get("javabuilder", "default_javabuilder.jar"), java_runtime = kwargs["java_runtime"], - ijar = [kwargs.get("ijar", "default_ijar.jar")], - singlejar = [kwargs.get("singlejar", "default_singlejar.jar")], + ijar = kwargs.get("ijar", "default_ijar.jar"), + singlejar = kwargs.get("singlejar", "default_singlejar.jar"), ) def _test_jacocorunner(name): diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl index 7b113ef6..f4f83f66 100644 --- a/toolchains/default_java_toolchain.bzl +++ b/toolchains/default_java_toolchain.bzl @@ -77,11 +77,11 @@ _DEFAULT_JAVA_LANGUAGE_VERSION = "11" # Default java_toolchain parameters _BASE_TOOLCHAIN_CONFIGURATION = dict( forcibly_disable_header_compilation = False, - genclass = [Label("@remote_java_tools//:GenClass")], - header_compiler = [Label("@remote_java_tools//:TurbineDirect")], - header_compiler_direct = [Label("//toolchains:turbine_direct")], - ijar = [Label("//toolchains:ijar")], - javabuilder = [Label("@remote_java_tools//:JavaBuilder")], + genclass = Label("@remote_java_tools//:GenClass"), + header_compiler = Label("@remote_java_tools//:TurbineDirect"), + header_compiler_direct = Label("//toolchains:turbine_direct"), + ijar = Label("//toolchains:ijar"), + javabuilder = Label("@remote_java_tools//:JavaBuilder"), javac_supports_workers = True, jacocorunner = Label("@remote_java_tools//:jacoco_coverage_runner_filegroup"), jvm_opts = BASE_JDK9_JVM_OPTS, @@ -90,7 +90,7 @@ _BASE_TOOLCHAIN_CONFIGURATION = dict( "-XX:+UseParallelGC", ], misc = DEFAULT_JAVACOPTS, - singlejar = [Label("//toolchains:singlejar")], + singlejar = Label("//toolchains:singlejar"), # Code to enumerate target JVM boot classpath uses host JVM. Because # java_runtime-s are involved, its implementation is in @bazel_tools. bootclasspath = [Label("//toolchains:platformclasspath")], @@ -121,7 +121,7 @@ DEFAULT_TOOLCHAIN_CONFIGURATION = _BASE_TOOLCHAIN_CONFIGURATION # However it does allow using a wider range of `--host_javabase`s, including # versions newer than the current JDK. VANILLA_TOOLCHAIN_CONFIGURATION = dict( - javabuilder = [Label("@remote_java_tools//:VanillaJavaBuilder")], + javabuilder = Label("@remote_java_tools//:VanillaJavaBuilder"), jvm_opts = [], java_runtime = None, ) @@ -132,16 +132,16 @@ VANILLA_TOOLCHAIN_CONFIGURATION = dict( # same, otherwise the binaries will not work on the execution # platform. PREBUILT_TOOLCHAIN_CONFIGURATION = dict( - ijar = [Label("//toolchains:ijar_prebuilt_binary")], - singlejar = [Label("//toolchains:prebuilt_singlejar")], + ijar = Label("//toolchains:ijar_prebuilt_binary"), + singlejar = Label("//toolchains:prebuilt_singlejar"), oneversion = Label("//toolchains:prebuilt_one_version"), ) # The new toolchain is using all the tools from sources. NONPREBUILT_TOOLCHAIN_CONFIGURATION = dict( - ijar = [Label("@remote_java_tools//:ijar_cc_binary")], - singlejar = [Label("@remote_java_tools//:singlejar_cc_bin")], - header_compiler_direct = [Label("@remote_java_tools//:TurbineDirect")], + ijar = Label("@remote_java_tools//:ijar_cc_binary"), + singlejar = Label("@remote_java_tools//:singlejar_cc_bin"), + header_compiler_direct = Label("@remote_java_tools//:TurbineDirect"), oneversion = Label("@remote_java_tools//:one_version_cc_bin"), bootclasspath = [Label("//toolchains:platformclasspath_nostrip")], ) From ad7f833dddb5fd7f62ccfbb19b9603a1b4429f4b Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 27 Nov 2025 01:53:48 -0800 Subject: [PATCH 351/465] Cleanup unused Bazel 6 test filtering Follow up to https://github.com/bazelbuild/rules_java/commit/b55339e359675d03a4f1cc001f1840d0b27966df [^1] PiperOrigin-RevId: 837439832 Change-Id: I8413040e00ce2b4338b2b0dd6802c8c990edb9e1 --- test/java/common/java_common_tests.bzl | 6 ------ test/java/common/java_info_tests.bzl | 1 - test/java/common/java_plugin_info_tests.bzl | 1 - test/java/common/rules/java_binary_tests.bzl | 4 ---- test/java/common/rules/java_import_tests.bzl | 2 -- test/java/common/rules/java_test_tests.bzl | 3 --- test/java/toolchains/java_runtime_tests.bzl | 6 ------ 7 files changed, 23 deletions(-) diff --git a/test/java/common/java_common_tests.bzl b/test/java/common/java_common_tests.bzl index d4528df8..2eaf00de 100644 --- a/test/java/common/java_common_tests.bzl +++ b/test/java/common/java_common_tests.bzl @@ -91,8 +91,6 @@ def _test_compile_exports_with_sources(name): name = name, impl = _test_compile_exports_with_sources_impl, target = target_name, - # Bazel 6 JavaInfo doesn't expose compile_time_java_dependencies - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_compile_exports_with_sources_impl(env, target): @@ -138,7 +136,6 @@ def _test_compile_extend_compile_time_jdeps(name): name = name, impl = _test_compile_extend_compile_time_jdeps_impl, target = name + "/foo", - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_compile_extend_compile_time_jdeps_impl(env, target): @@ -181,7 +178,6 @@ def _test_compile_extend_compile_time_jdeps_rule_outputs(name): "bar": name + "/bar", "baz": name + "/baz", }, - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_compile_extend_compile_time_jdeps_rule_outputs_impl(env, targets): @@ -234,7 +230,6 @@ def _test_compile_bootclasspath(name): name = name, impl = _test_compile_bootclasspath_impl, target = name + "/custom", - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_compile_bootclasspath_impl(env, target): @@ -269,7 +264,6 @@ def _test_compile_override_with_empty_bootclasspath(name): name = name, impl = _test_compile_override_with_empty_bootclasspath_impl, target = name + "/custom", - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_compile_override_with_empty_bootclasspath_impl(env, target): diff --git a/test/java/common/java_info_tests.bzl b/test/java/common/java_info_tests.bzl index 5d3c6663..a646e112 100644 --- a/test/java/common/java_info_tests.bzl +++ b/test/java/common/java_info_tests.bzl @@ -1255,7 +1255,6 @@ def _output_source_jars_returns_depset_test(name): name = name, impl = _output_source_jars_returns_depset_test_impl, target = target_name, - attr_values = {"tags": ["min_bazel_7"]}, # changed in Bazel 7 ) def _output_source_jars_returns_depset_test_impl(env, target): diff --git a/test/java/common/java_plugin_info_tests.bzl b/test/java/common/java_plugin_info_tests.bzl index c3b8b378..ed742f13 100644 --- a/test/java/common/java_plugin_info_tests.bzl +++ b/test/java/common/java_plugin_info_tests.bzl @@ -124,7 +124,6 @@ def _test_without_processor_class(name): name = name, impl = _test_without_processor_class_impl, target = target_name, - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_without_processor_class_impl(env, target): diff --git a/test/java/common/rules/java_binary_tests.bzl b/test/java/common/rules/java_binary_tests.bzl index 08386ad1..97a85713 100644 --- a/test/java/common/rules/java_binary_tests.bzl +++ b/test/java/common/rules/java_binary_tests.bzl @@ -18,7 +18,6 @@ def _test_java_binary_provides_binary_java_info(name): name = name, impl = _test_java_binary_provides_binary_java_info_impl, target = Label(":bin"), - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_java_binary_provides_binary_java_info_impl(env, target): @@ -150,9 +149,6 @@ def _test_java_binary_propagates_direct_native_libraries(name): name = name, impl = _test_java_binary_propagates_direct_native_libraries_impl, target = name + "/binary", - # in Bazel 6, the windows stub was created by a bespoke, native and - # opaque-to-Starlark LauncherFileWriteAction - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_java_binary_propagates_direct_native_libraries_impl(env, target): diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 37941efc..7afbc77b 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -775,8 +775,6 @@ def _test_neverlink_is_populated(name): name = name, impl = _test_neverlink_is_populated_impl, target = target_name, - # in Bazel 6, JavaInfo._neverlink isn't exposed to Starlark - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_neverlink_is_populated_impl(env, target): diff --git a/test/java/common/rules/java_test_tests.bzl b/test/java/common/rules/java_test_tests.bzl index 4cc39ca2..f4db104b 100644 --- a/test/java/common/rules/java_test_tests.bzl +++ b/test/java/common/rules/java_test_tests.bzl @@ -56,9 +56,6 @@ def _test_java_test_propagates_direct_native_libraries(name): name = name, impl = _test_java_test_propagates_direct_native_libraries_impl, target = name + "/binary", - # in Bazel 6, the windows stub was created by a bespoke, native and - # opaque-to-Starlark LauncherFileWriteAction - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_java_test_propagates_direct_native_libraries_impl(env, target): diff --git a/test/java/toolchains/java_runtime_tests.bzl b/test/java/toolchains/java_runtime_tests.bzl index 4f1ec88a..f5014966 100644 --- a/test/java/toolchains/java_runtime_tests.bzl +++ b/test/java/toolchains/java_runtime_tests.bzl @@ -38,8 +38,6 @@ def _test_with_absolute_java_home(name): config_settings = { "//command_line_option:extra_toolchains": [Label(name + "/java_runtime_toolchain")], }, - # Bazel 6 doesn't accept Label's for the transition above - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_with_absolute_java_home_impl(env, target): @@ -80,8 +78,6 @@ def _test_with_hermetic_java_home(name): config_settings = { "//command_line_option:extra_toolchains": [Label(name + "/java_runtime_toolchain")], }, - # Bazel 6 doesn't accept Label's for the transition above - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_with_hermetic_java_home_impl(env, target): @@ -129,8 +125,6 @@ def _test_with_generated_java_executable(name): config_settings = { "//command_line_option:extra_toolchains": [Label(name + "/java_runtime_toolchain")], }, - # Bazel 6 doesn't accept Label's for the transition above - attr_values = {"tags": ["min_bazel_7"]}, ) def _test_with_generated_java_executable_impl(env, target): From 4a9881b8fd0c61dca10eef559d5d7b9a1940156f Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Thu, 27 Nov 2025 02:30:25 -0800 Subject: [PATCH 352/465] remove Bazel 6 branch (#337) Now that https://github.com/bazelbuild/rules_java/commit/b55339e359675d03a4f1cc001f1840d0b27966df has landed, remove Bazel 6-specific branch. Closes #337 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/337 from benjaminp:bazel-6 f4c631a13d6e7c3bf55e29b52cc418f4b663e141 PiperOrigin-RevId: 837452933 Change-Id: I68e8171ae4e70600cc82d09af75c15726f6d7ee6 --- toolchains/local_java_repository.bzl | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/toolchains/local_java_repository.bzl b/toolchains/local_java_repository.bzl index ba526a14..769c2d19 100644 --- a/toolchains/local_java_repository.bzl +++ b/toolchains/local_java_repository.bzl @@ -14,7 +14,6 @@ """Rules for importing a local JDK.""" -load("@bazel_features//private:util.bzl", _bazel_version_ge = "ge") load("//java/toolchains:java_runtime.bzl", "java_runtime") load(":default_java_toolchain.bzl", "default_java_toolchain") @@ -236,17 +235,10 @@ local_java_runtime( ) """ % (local_java_runtime_name, runtime_name, java_home, version) - if _bazel_version_ge("7.0.0"): - # Bazel 7+ uses @platforms//host for the host platform. - load_host_constraints = 'load("@platforms//host:constraints.bzl", "HOST_CONSTRAINTS")\n' - else: - # Bazel 6 uses @local_config_platform instead, but it's being removed in Bazel 9. - load_host_constraints = 'load("@local_config_platform//:constraints.bzl", "HOST_CONSTRAINTS")\n' - repository_ctx.file( "BUILD.bazel", 'load("@rules_java//toolchains:local_java_repository.bzl", "local_java_runtime")\n' + - load_host_constraints + + 'load("@platforms//host:constraints.bzl", "HOST_CONSTRAINTS")\n' + build_file + local_java_runtime_macro, ) From 4f806ff8d9b30a7d7dcaf501205b340dba62c74c Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 1 Dec 2025 00:40:54 -0800 Subject: [PATCH 353/465] Avoid quadratic time on string concatenation in _get_native_deps_helper. PiperOrigin-RevId: 838641853 Change-Id: Ic2447584007194e7209b856bd97b318bfa34e14a --- java/common/rules/impl/java_helper.bzl | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/java/common/rules/impl/java_helper.bzl b/java/common/rules/impl/java_helper.bzl index 683bf609..d54c8f64 100644 --- a/java/common/rules/impl/java_helper.bzl +++ b/java/common/rules/impl/java_helper.bzl @@ -170,18 +170,15 @@ def _get_shared_native_deps_path( method below is only ensured by validations in the CppLinkAction.Builder.build() method. """ - fp = "" - for artifact in linker_inputs: - fp += artifact.short_path - fp += str(len(link_opts)) - for opt in link_opts: - fp += opt - for artifact in linkstamps: - fp += artifact.short_path - for artifact in build_info_artifacts: - fp += artifact.short_path - for feature in features: - fp += feature + fp = [] + + # join() is faster than concatenating many strings individually + fp += [a.short_path for a in linker_inputs] + fp.append(str(len(link_opts))) + fp += link_opts + fp += [a.short_path for a in linkstamps] + fp += [a.short_path for a in build_info_artifacts] + fp += features # Sharing of native dependencies may cause an ActionConflictException when ThinLTO is # disabled for test and test-only targets that are statically linked, but enabled for other @@ -190,9 +187,9 @@ def _get_shared_native_deps_path( # this, we allow creation of multiple artifacts for the shared native library - one shared # among the test and test-only targets where ThinLTO is disabled, and the other shared among # other targets where ThinLTO is enabled. - fp += "1" if is_test_target_partially_disabled_thin_lto else "0" + fp.append("1" if is_test_target_partially_disabled_thin_lto else "0") - fingerprint = "%x" % hash(fp) + fingerprint = "%x" % hash("".join(fp)) return "_nativedeps/" + fingerprint def _check_and_get_one_version_attribute(ctx, attr): From b6856588ba834750a1e66b2dd1b274a1f09f66a5 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 1 Dec 2025 01:11:10 -0800 Subject: [PATCH 354/465] Release `rules_java` `v9.1.0` PiperOrigin-RevId: 838651324 Change-Id: I6a176d71930b2e8909f96a8a47a21a7e0a068211 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 8c2a672a..24653fe2 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "9.0.3", + version = "9.1.0", bazel_compatibility = [">=7.0.0"], compatibility_level = 1, ) From 8bf8bcaca17fc15ba4fff3229d4eead4b653214a Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 1 Dec 2025 03:55:59 -0800 Subject: [PATCH 355/465] Extract utility methods used in the loading phase from `impl/java_helper.bzl` into a separate bzl file Methods used only by a single other load-affecting bzl file are inlined there instead. This way `impl/java_helper.bzl` is only loaded from bzl files used during rule implementations and should not be needed for the loading-phase, so making changes to this file don't invalidate the results of `blaze query`[^1]. PiperOrigin-RevId: 838701557 Change-Id: If462c46b1b8f2e5be12322a8af7d1a27e392bdfd --- java/common/rules/BUILD | 15 ++ java/common/rules/impl/BUILD | 7 + java/common/rules/impl/java_helper.bzl | 234 +----------------- java/common/rules/java_helper.bzl | 212 ++++++++++++++++ .../rules/java_package_configuration.bzl | 2 +- java/common/rules/java_runtime.bzl | 2 +- java/common/rules/java_toolchain.bzl | 2 +- java/private/BUILD | 25 +- java/private/java_common.bzl | 2 +- java/private/java_common_internal.bzl | 49 +++- 10 files changed, 311 insertions(+), 239 deletions(-) create mode 100644 java/common/rules/java_helper.bzl diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD index 12006384..5bb5c2fb 100644 --- a/java/common/rules/BUILD +++ b/java/common/rules/BUILD @@ -25,6 +25,12 @@ bzl_library( visibility = ["//visibility:private"], ) +bzl_library( + name = "java_helper_bzl", + srcs = ["java_helper.bzl"], + visibility = ["//java:__subpackages__"], +) + bzl_library( name = "core_rules", srcs = [ @@ -58,6 +64,15 @@ bzl_library( "//java:__subpackages__", "@compatibility_proxy//:__pkg__", ], + deps = [ + ":java_helper_bzl", + "//java/common:semantics_bzl", + "//java/private:boot_class_path_info_bzl", + "//java/private:java_info_bzl", + "//java/private:native_bzl", + "@bazel_skylib//lib:paths", + "@rules_cc//cc/common", + ], ) filegroup( diff --git a/java/common/rules/impl/BUILD b/java/common/rules/impl/BUILD index aead3739..70adeccd 100644 --- a/java/common/rules/impl/BUILD +++ b/java/common/rules/impl/BUILD @@ -30,6 +30,13 @@ bzl_library( name = "java_helper_bzl", srcs = ["java_helper.bzl"], visibility = ["//java:__subpackages__"], + deps = [ + "//java/common:semantics_bzl", + "//java/common/rules:java_helper_bzl", + "@bazel_skylib//lib:paths", + "@rules_cc//cc:find_cc_toolchain_bzl", + "@rules_cc//cc/common", + ], ) filegroup( diff --git a/java/common/rules/impl/java_helper.bzl b/java/common/rules/impl/java_helper.bzl index d54c8f64..0667ee49 100644 --- a/java/common/rules/impl/java_helper.bzl +++ b/java/common/rules/impl/java_helper.bzl @@ -12,12 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Common util functions for java_* rules""" +"""Common util functions for java_* rules implementations""" load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cc_toolchain") load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_helper.bzl", _loading_phase_helper = "helper") # copybara: rules_java visibility @@ -93,7 +94,7 @@ def _primary_class(ctx): for src in ctx.files.srcs: if src.basename == main: return _full_classname(_strip_extension(src)) - return _full_classname(_get_relative(ctx.label.package, ctx.label.name)) + return _full_classname(helper.get_relative(ctx.label.package, ctx.label.name)) def _strip_extension(file): return file.dirname + "/" + ( @@ -102,41 +103,9 @@ def _strip_extension(file): # TODO(b/193629418): once out of builtins, create a canonical implementation and remove duplicates in depot def _full_classname(path): - java_segments = _java_segments(path) + java_segments = _loading_phase_helper.java_segments(path) return ".".join(java_segments) if java_segments != None else None -def _java_segments(path): - if path.startswith("/"): - fail("path must not be absolute: '%s'" % path) - segments = path.split("/") - root_idx = -1 - for idx, segment in enumerate(segments): - if segment in ["java", "javatests", "src", "testsrc"]: - root_idx = idx - break - if root_idx < 0: - return None - is_src = "src" == segments[root_idx] - check_mvn_idx = root_idx if is_src else -1 - if (root_idx == 0 or is_src): - for i in range(root_idx + 1, len(segments) - 1): - segment = segments[i] - if "src" == segment or (is_src and (segment in ["java", "javatests"])): - next = segments[i + 1] - if next in ["com", "org", "net"]: - root_idx = i - elif "src" == segment: - check_mvn_idx = i - break - - if check_mvn_idx >= 0 and check_mvn_idx < len(segments) - 2: - next = segments[check_mvn_idx + 1] - if next in ["main", "test"]: - next = segments[check_mvn_idx + 2] - if next in ["java", "resources"]: - root_idx = check_mvn_idx + 2 - return segments[(root_idx + 1):] - def _concat(*lists): result = [] for list in lists: @@ -250,19 +219,8 @@ def _get_java_executable(ctx, java_runtime_toolchain, launcher): java_executable = ctx.workspace_name + "/" + java_executable return paths.normalize(java_executable) -def _has_target_constraints(ctx, constraints): - # Constraints is a label_list. - for constraint in constraints: - constraint_value = constraint[platform_common.ConstraintValueInfo] - if ctx.target_platform_has_constraint(constraint_value): - return True - return False - -def _is_target_platform_windows(ctx): - return _has_target_constraints(ctx, ctx.attr._windows_constraints) - def _is_absolute_target_platform_path(ctx, path): - if _is_target_platform_windows(ctx): + if helper.is_target_platform_windows(ctx): return len(path) > 2 and path[1] == ":" return path.startswith("/") @@ -274,139 +232,6 @@ def _get_test_support(ctx): return ctx.attr._test_support return None -def _resource_mapper(file): - root_relative_path = paths.relativize( - path = file.path, - start = paths.join(file.root.path, file.owner.workspace_root), - ) - return "%s:%s" % ( - file.path, - semantics.get_default_resource_path(root_relative_path, segment_extractor = _java_segments), - ) - -def _create_single_jar( - actions, - toolchain, - output, - sources = depset(), - resources = depset(), - mnemonic = "JavaSingleJar", - progress_message = "Building singlejar jar %{output}", - build_target = None, - output_creator = None): - """Register singlejar action for the output jar. - - Args: - actions: (actions) ctx.actions - toolchain: (JavaToolchainInfo) The java toolchain - output: (File) Output file of the action. - sources: (depset[File]) The jar files to merge into the output jar. - resources: (depset[File]) The files to add to the output jar. - mnemonic: (str) The action identifier - progress_message: (str) The action progress message - build_target: (Label) The target label to stamp in the manifest. Optional. - output_creator: (str) The name of the tool to stamp in the manifest. Optional, - defaults to 'singlejar' - Returns: - (File) Output file which was used for registering the action. - """ - args = actions.args() - args.set_param_file_format("shell").use_param_file("@%s", use_always = True) - args.add("--output", output) - args.add_all( - [ - "--compression", - "--normalize", - "--exclude_build_data", - "--warn_duplicate_resources", - ], - ) - args.add_all("--sources", sources) - args.add_all("--resources", resources, map_each = _resource_mapper) - - args.add("--build_target", build_target) - args.add("--output_jar_creator", output_creator) - - actions.run( - mnemonic = mnemonic, - progress_message = progress_message, - executable = toolchain.single_jar, - toolchain = semantics.JAVA_TOOLCHAIN_TYPE, - inputs = depset(transitive = [resources, sources]), - tools = [toolchain.single_jar], - outputs = [output], - arguments = [args], - use_default_shell_env = True, - ) - return output - -# TODO(hvd): use skylib shell.quote() -def _shell_escape(s): - """Shell-escape a string - - Quotes a word so that it can be used, without further quoting, as an argument - (or part of an argument) in a shell command. - - Args: - s: (str) the string to escape - - Returns: - (str) the shell-escaped string - """ - if not s: - # Empty string is a special case: needs to be quoted to ensure that it - # gets treated as a separate argument. - return "''" - for c in s.elems(): - # We do this positively so as to be sure we don't inadvertently forget - # any unsafe characters. - if not c.isalnum() and c not in "@%-_+:,./": - return "'" + s.replace("'", "'\\''") + "'" - return s - -def _detokenize_javacopts(opts): - """Detokenizes a list of options to a depset. - - Args: - opts: ([str]) the javac options to detokenize - - Returns: - (depset[str]) depset of detokenized options - """ - return depset( - [" ".join([_shell_escape(opt) for opt in opts])], - order = "preorder", - ) - -def _derive_output_file(ctx, base_file, *, name_suffix = "", extension = None, extension_suffix = ""): - """Declares a new file whose name is derived from the given file - - This method allows appending a suffix to the name (before extension), changing - the extension or appending a suffix after the extension. The new file is declared - as a sibling of the given base file. At least one of the three options must be - specified. It is an error to specify both `extension` and `extension_suffix`. - - Args: - ctx: (RuleContext) the rule context. - base_file: (File) the file from which to derive the resultant file. - name_suffix: (str) Optional. The suffix to append to the name before the - extension. - extension: (str) Optional. The new extension to use (without '.'). By default, - the base_file's extension is used. - extension_suffix: (str) Optional. The suffix to append to the base_file's extension - - Returns: - (File) the derived file - """ - if not name_suffix and not extension_suffix and not extension: - fail("At least one of name_suffix, extension or extension_suffix is required") - if extension and extension_suffix: - fail("only one of extension or extension_suffix can be specified") - if extension == None: - extension = base_file.extension - new_basename = paths.replace_extension(base_file.basename, name_suffix + "." + extension + extension_suffix) - return ctx.actions.declare_file(new_basename, sibling = base_file) - def _is_stamping_enabled(ctx, stamp): if ctx.configuration.is_tool_configuration(): return 0 @@ -416,40 +241,6 @@ def _is_stamping_enabled(ctx, stamp): # stamp == -1 / auto return int(ctx.configuration.stamp_binaries()) -def _get_relative(path_a, path_b): - if paths.is_absolute(path_b): - return path_b - return paths.normalize(paths.join(path_a, path_b)) - -def _tokenize_javacopts(ctx = None, opts = []): - """Tokenizes a list or depset of options to a list. - - Iff opts is a depset, we reverse the flattened list to ensure right-most - duplicates are preserved in their correct position. - - If the ctx parameter is omitted, a slow, but pure Starlark, implementation - of shell tokenization is used. Otherwise, tokenization is performed using - ctx.tokenize() which has significantly better performance (up to 100x for - large options lists). - - Args: - ctx: (RuleContext|None) the rule context - opts: (depset[str]|[str]) the javac options to tokenize - Returns: - [str] list of tokenized options - """ - if hasattr(opts, "to_list"): - opts = reversed(opts.to_list()) - if ctx: - return [ - token - for opt in opts - for token in ctx.tokenize(opt) - ] - else: - # TODO: optimize and use the pure Starlark implementation in cc_helper - return semantics.tokenize_javacopts(opts) - helper = struct( collect_all_targets_as_deps = _collect_all_targets_as_deps, filter_launcher_for_target = _filter_launcher_for_target, @@ -466,15 +257,14 @@ helper = struct( get_coverage_config = _get_coverage_config, get_java_executable = _get_java_executable, is_absolute_target_platform_path = _is_absolute_target_platform_path, - is_target_platform_windows = _is_target_platform_windows, + is_target_platform_windows = _loading_phase_helper.is_target_platform_windows, runfiles_enabled = _runfiles_enabled, get_test_support = _get_test_support, - create_single_jar = _create_single_jar, - shell_escape = _shell_escape, - detokenize_javacopts = _detokenize_javacopts, - tokenize_javacopts = _tokenize_javacopts, - derive_output_file = _derive_output_file, + create_single_jar = _loading_phase_helper.create_single_jar, + shell_escape = _loading_phase_helper.shell_escape, + detokenize_javacopts = _loading_phase_helper.detokenize_javacopts, + tokenize_javacopts = _loading_phase_helper.tokenize_javacopts, is_stamping_enabled = _is_stamping_enabled, - get_relative = _get_relative, - has_target_constraints = _has_target_constraints, + get_relative = _loading_phase_helper.get_relative, + has_target_constraints = _loading_phase_helper.has_target_constraints, ) diff --git a/java/common/rules/java_helper.bzl b/java/common/rules/java_helper.bzl new file mode 100644 index 00000000..ee274ade --- /dev/null +++ b/java/common/rules/java_helper.bzl @@ -0,0 +1,212 @@ +# 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. + +"""Common util functions for java_* rules""" + +load("@bazel_skylib//lib:paths.bzl", "paths") +load("//java/common:java_semantics.bzl", "semantics") + +# copybara: rules_java visibility + +def _java_segments(path): + if path.startswith("/"): + fail("path must not be absolute: '%s'" % path) + segments = path.split("/") + root_idx = -1 + for idx, segment in enumerate(segments): + if segment in ["java", "javatests", "src", "testsrc"]: + root_idx = idx + break + if root_idx < 0: + return None + is_src = "src" == segments[root_idx] + check_mvn_idx = root_idx if is_src else -1 + if (root_idx == 0 or is_src): + for i in range(root_idx + 1, len(segments) - 1): + segment = segments[i] + if "src" == segment or (is_src and (segment in ["java", "javatests"])): + next = segments[i + 1] + if next in ["com", "org", "net"]: + root_idx = i + elif "src" == segment: + check_mvn_idx = i + break + + if check_mvn_idx >= 0 and check_mvn_idx < len(segments) - 2: + next = segments[check_mvn_idx + 1] + if next in ["main", "test"]: + next = segments[check_mvn_idx + 2] + if next in ["java", "resources"]: + root_idx = check_mvn_idx + 2 + return segments[(root_idx + 1):] + +def _has_target_constraints(ctx, constraints): + # Constraints is a label_list. + for constraint in constraints: + constraint_value = constraint[platform_common.ConstraintValueInfo] + if ctx.target_platform_has_constraint(constraint_value): + return True + return False + +def _is_target_platform_windows(ctx): + return _has_target_constraints(ctx, ctx.attr._windows_constraints) + +def _resource_mapper(file): + root_relative_path = paths.relativize( + path = file.path, + start = paths.join(file.root.path, file.owner.workspace_root), + ) + return "%s:%s" % ( + file.path, + semantics.get_default_resource_path(root_relative_path, segment_extractor = _java_segments), + ) + +def _create_single_jar( + actions, + toolchain, + output, + sources = depset(), + resources = depset(), + mnemonic = "JavaSingleJar", + progress_message = "Building singlejar jar %{output}", + build_target = None, + output_creator = None): + """Register singlejar action for the output jar. + + Args: + actions: (actions) ctx.actions + toolchain: (JavaToolchainInfo) The java toolchain + output: (File) Output file of the action. + sources: (depset[File]) The jar files to merge into the output jar. + resources: (depset[File]) The files to add to the output jar. + mnemonic: (str) The action identifier + progress_message: (str) The action progress message + build_target: (Label) The target label to stamp in the manifest. Optional. + output_creator: (str) The name of the tool to stamp in the manifest. Optional, + defaults to 'singlejar' + Returns: + (File) Output file which was used for registering the action. + """ + args = actions.args() + args.set_param_file_format("shell").use_param_file("@%s", use_always = True) + args.add("--output", output) + args.add_all( + [ + "--compression", + "--normalize", + "--exclude_build_data", + "--warn_duplicate_resources", + ], + ) + args.add_all("--sources", sources) + args.add_all("--resources", resources, map_each = _resource_mapper) + + args.add("--build_target", build_target) + args.add("--output_jar_creator", output_creator) + + actions.run( + mnemonic = mnemonic, + progress_message = progress_message, + executable = toolchain.single_jar, + toolchain = semantics.JAVA_TOOLCHAIN_TYPE, + inputs = depset(transitive = [resources, sources]), + tools = [toolchain.single_jar], + outputs = [output], + arguments = [args], + use_default_shell_env = True, + ) + return output + +# TODO(hvd): use skylib shell.quote() +def _shell_escape(s): + """Shell-escape a string + + Quotes a word so that it can be used, without further quoting, as an argument + (or part of an argument) in a shell command. + + Args: + s: (str) the string to escape + + Returns: + (str) the shell-escaped string + """ + if not s: + # Empty string is a special case: needs to be quoted to ensure that it + # gets treated as a separate argument. + return "''" + for c in s.elems(): + # We do this positively so as to be sure we don't inadvertently forget + # any unsafe characters. + if not c.isalnum() and c not in "@%-_+:,./": + return "'" + s.replace("'", "'\\''") + "'" + return s + +def _detokenize_javacopts(opts): + """Detokenizes a list of options to a depset. + + Args: + opts: ([str]) the javac options to detokenize + + Returns: + (depset[str]) depset of detokenized options + """ + return depset( + [" ".join([_shell_escape(opt) for opt in opts])], + order = "preorder", + ) + +def _get_relative(path_a, path_b): + if paths.is_absolute(path_b): + return path_b + return paths.normalize(paths.join(path_a, path_b)) + +def _tokenize_javacopts(ctx = None, opts = []): + """Tokenizes a list or depset of options to a list. + + Iff opts is a depset, we reverse the flattened list to ensure right-most + duplicates are preserved in their correct position. + + If the ctx parameter is omitted, a slow, but pure Starlark, implementation + of shell tokenization is used. Otherwise, tokenization is performed using + ctx.tokenize() which has significantly better performance (up to 100x for + large options lists). + + Args: + ctx: (RuleContext|None) the rule context + opts: (depset[str]|[str]) the javac options to tokenize + Returns: + [str] list of tokenized options + """ + if hasattr(opts, "to_list"): + opts = reversed(opts.to_list()) + if ctx: + return [ + token + for opt in opts + for token in ctx.tokenize(opt) + ] + else: + # TODO: optimize and use the pure Starlark implementation in cc_helper + return semantics.tokenize_javacopts(opts) + +helper = struct( + is_target_platform_windows = _is_target_platform_windows, + create_single_jar = _create_single_jar, + shell_escape = _shell_escape, + detokenize_javacopts = _detokenize_javacopts, + tokenize_javacopts = _tokenize_javacopts, + get_relative = _get_relative, + has_target_constraints = _has_target_constraints, + java_segments = _java_segments, +) diff --git a/java/common/rules/java_package_configuration.bzl b/java/common/rules/java_package_configuration.bzl index 2c24b450..e6b1885f 100644 --- a/java/common/rules/java_package_configuration.bzl +++ b/java/common/rules/java_package_configuration.bzl @@ -14,7 +14,7 @@ """Implementation for the java_package_configuration rule""" -load("//java/common/rules/impl:java_helper.bzl", "helper") +load("//java/common/rules:java_helper.bzl", "helper") load("//java/private:boot_class_path_info.bzl", "BootClassPathInfo") load("//java/private:native.bzl", "get_internal_java_common") diff --git a/java/common/rules/java_runtime.bzl b/java/common/rules/java_runtime.bzl index 47a93435..2433549c 100644 --- a/java/common/rules/java_runtime.bzl +++ b/java/common/rules/java_runtime.bzl @@ -19,7 +19,7 @@ Definition of java_runtime rule and JavaRuntimeInfo provider. load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_semantics.bzl", "semantics") -load("//java/common/rules/impl:java_helper.bzl", "helper") +load("//java/common/rules:java_helper.bzl", "helper") # copybara: default visibility diff --git a/java/common/rules/java_toolchain.bzl b/java/common/rules/java_toolchain.bzl index 6aed2ecd..d08775a5 100644 --- a/java/common/rules/java_toolchain.bzl +++ b/java/common/rules/java_toolchain.bzl @@ -17,7 +17,7 @@ Definition of java_toolchain rule and JavaToolchainInfo provider. """ load("//java/common:java_semantics.bzl", "semantics") -load("//java/common/rules/impl:java_helper.bzl", "helper") +load("//java/common/rules:java_helper.bzl", "helper") load("//java/private:boot_class_path_info.bzl", "BootClassPathInfo") load("//java/private:java_info.bzl", "JavaPluginDataInfo") load("//java/private:native.bzl", "get_internal_java_common") diff --git a/java/private/BUILD b/java/private/BUILD index bbed12b8..510c3010 100644 --- a/java/private/BUILD +++ b/java/private/BUILD @@ -23,10 +23,8 @@ bzl_library( bzl_library( name = "internals", srcs = [ - "boot_class_path_info.bzl", "java_common.bzl", "java_common_internal.bzl", - "java_info.bzl", "message_bundle_info.bzl", ], visibility = [ @@ -34,9 +32,12 @@ bzl_library( "@compatibility_proxy//:__pkg__", ], deps = [ + ":boot_class_path_info_bzl", + ":java_info_bzl", ":native_bzl", + "//java/common:semantics_bzl", + "//java/common/rules:java_helper_bzl", "//java/common/rules:toolchain_rules", - "//java/common/rules/impl:java_helper_bzl", "@bazel_skylib//lib:paths", "@bazel_skylib//rules:common_settings", "@rules_cc//cc:find_cc_toolchain_bzl", @@ -44,6 +45,24 @@ bzl_library( ], ) +bzl_library( + name = "boot_class_path_info_bzl", + srcs = ["boot_class_path_info.bzl"], + visibility = ["//java:__subpackages__"], + deps = ["@bazel_skylib//lib:paths"], +) + +bzl_library( + name = "java_info_bzl", + srcs = ["java_info.bzl"], + visibility = ["//java:__subpackages__"], + deps = [ + ":native_bzl", + "//java/common:semantics_bzl", + "@rules_cc//cc/common", + ], +) + # Exposed for use by the protobuf. bzl_library( name = "proto_support", diff --git a/java/private/java_common.bzl b/java/private/java_common.bzl index 70461632..8a465c26 100644 --- a/java/private/java_common.bzl +++ b/java/private/java_common.bzl @@ -16,9 +16,9 @@ load("@bazel_skylib//lib:paths.bzl", "paths") load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_helper.bzl", "helper") load("//java/common/rules:java_runtime.bzl", "JavaRuntimeInfo") load("//java/common/rules:java_toolchain.bzl", "JavaToolchainInfo") -load("//java/common/rules/impl:java_helper.bzl", "helper") load(":boot_class_path_info.bzl", "BootClassPathInfo") load( ":java_common_internal.bzl", diff --git a/java/private/java_common_internal.bzl b/java/private/java_common_internal.bzl index 7af3bf79..249b9255 100644 --- a/java/private/java_common_internal.bzl +++ b/java/private/java_common_internal.bzl @@ -16,8 +16,8 @@ load("@bazel_skylib//lib:paths.bzl", "paths") load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_helper.bzl", "helper") load("//java/common/rules:java_toolchain.bzl", "JavaToolchainInfo") -load("//java/common/rules/impl:java_helper.bzl", "helper") load( ":java_info.bzl", "JavaPluginInfo", @@ -222,14 +222,14 @@ def compile( header_compilation_jar = compile_jar compile_deps_proto = None elif _should_use_header_compilation(ctx, java_toolchain): - compile_jar = helper.derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jar") + compile_jar = _derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jar") # TODO: b/417791104 - remove check after a Bazel release if ctx.fragments.java.use_header_compilation_direct_deps(): - header_compilation_jar = helper.derive_output_file(ctx, output, name_suffix = "-tjar", extension = "jar") + header_compilation_jar = _derive_output_file(ctx, output, name_suffix = "-tjar", extension = "jar") else: header_compilation_jar = None - compile_deps_proto = helper.derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jdeps") + compile_deps_proto = _derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jdeps") get_internal_java_common().create_header_compilation_action( ctx, java_toolchain, @@ -266,16 +266,16 @@ def compile( header_compilation_jar = compile_jar compile_deps_proto = None - native_headers_jar = helper.derive_output_file(ctx, output, name_suffix = "-native-header") - manifest_proto = helper.derive_output_file(ctx, output, extension_suffix = "_manifest_proto") + native_headers_jar = _derive_output_file(ctx, output, name_suffix = "-native-header") + manifest_proto = _derive_output_file(ctx, output, extension_suffix = "_manifest_proto") deps_proto = None if ctx.fragments.java.generate_java_deps() and has_sources: - deps_proto = helper.derive_output_file(ctx, output, extension = "jdeps") + deps_proto = _derive_output_file(ctx, output, extension = "jdeps") generated_class_jar = None generated_source_jar = None if uses_annotation_processing: - generated_class_jar = helper.derive_output_file(ctx, output, name_suffix = "-gen") - generated_source_jar = helper.derive_output_file(ctx, output, name_suffix = "-gensrc") + generated_class_jar = _derive_output_file(ctx, output, name_suffix = "-gen") + generated_source_jar = _derive_output_file(ctx, output, name_suffix = "-gensrc") get_internal_java_common().create_compilation_action( ctx, java_toolchain, @@ -309,7 +309,7 @@ def compile( create_output_source_jar = len(source_files) > 0 or source_jars != [output_source_jar] if not output_source_jar: - output_source_jar = helper.derive_output_file(ctx, output, name_suffix = "-src", extension = "jar") + output_source_jar = _derive_output_file(ctx, output, name_suffix = "-src", extension = "jar") if create_output_source_jar: helper.create_single_jar( ctx.actions, @@ -364,6 +364,35 @@ def compile( compilation_info = compilation_info, ) +def _derive_output_file(ctx, base_file, *, name_suffix = "", extension = None, extension_suffix = ""): + """Declares a new file whose name is derived from the given file + + This method allows appending a suffix to the name (before extension), changing + the extension or appending a suffix after the extension. The new file is declared + as a sibling of the given base file. At least one of the three options must be + specified. It is an error to specify both `extension` and `extension_suffix`. + + Args: + ctx: (RuleContext) the rule context. + base_file: (File) the file from which to derive the resultant file. + name_suffix: (str) Optional. The suffix to append to the name before the + extension. + extension: (str) Optional. The new extension to use (without '.'). By default, + the base_file's extension is used. + extension_suffix: (str) Optional. The suffix to append to the base_file's extension + + Returns: + (File) the derived file + """ + if not name_suffix and not extension_suffix and not extension: + fail("At least one of name_suffix, extension or extension_suffix is required") + if extension and extension_suffix: + fail("only one of extension or extension_suffix can be specified") + if extension == None: + extension = base_file.extension + new_basename = paths.replace_extension(base_file.basename, name_suffix + "." + extension + extension_suffix) + return ctx.actions.declare_file(new_basename, sibling = base_file) + def _should_use_header_compilation(ctx, toolchain): if not ctx.fragments.java.use_header_compilation(): return False From 113827798fc6ddcd180ebe365b8b4951eb628def Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 1 Dec 2025 05:28:38 -0800 Subject: [PATCH 356/465] Internal change (ignore-relnotes) PiperOrigin-RevId: 838728638 Change-Id: I9973ebcaba675627ba2f9f6ce3a74139560cbe12 --- java/common/rules/impl/java_helper.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/common/rules/impl/java_helper.bzl b/java/common/rules/impl/java_helper.bzl index 0667ee49..efc7f0e5 100644 --- a/java/common/rules/impl/java_helper.bzl +++ b/java/common/rules/impl/java_helper.bzl @@ -101,7 +101,7 @@ def _strip_extension(file): file.basename[:-(1 + len(file.extension))] if file.extension else file.basename ) -# TODO(b/193629418): once out of builtins, create a canonical implementation and remove duplicates in depot +# TODO(b/465048589): once out of builtins, create a canonical implementation and remove duplicates in depot def _full_classname(path): java_segments = _loading_phase_helper.java_segments(path) return ".".join(java_segments) if java_segments != None else None From 686ed85f30ae22018327552d5d2d9a4f8486d772 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 2 Dec 2025 00:42:13 -0800 Subject: [PATCH 357/465] Update to `java_tools` `v18.0` https://github.com/bazelbuild/bazel/issues/27810 PiperOrigin-RevId: 839131461 Change-Id: I1ef7b762aac490c5b509e91519d65f4d11a70825 --- java/repositories.bzl | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/java/repositories.bzl b/java/repositories.bzl index 82093756..1e336502 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,38 +22,38 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v17.0", + "version": "v18.0", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v17.0/java_tools_linux-v17.0.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v17.0/java_tools_linux-v17.0.zip", - "sha": "5f89d5d04b41dbe1d661836b6a76c468113e0080953bcd72aaf6711c7462b86a", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.0/java_tools_linux-v18.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.0/java_tools_linux-v18.0.zip", + "sha": "f0b49f6fa369f581b1194a91feb55ef8bf99683c7e76867854b6372782772f00", }, "java_tools_linux_aarch64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v17.0/java_tools_linux_aarch64-v17.0.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v17.0/java_tools_linux_aarch64-v17.0.zip", - "sha": "c36a17057e895b260cb8f2f7961ed7480812ab6923dab5a39f0c93263e2f76f2", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.0/java_tools_linux_aarch64-v18.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.0/java_tools_linux_aarch64-v18.0.zip", + "sha": "8f8a436c858e39ae9f40b54a3515e0c6b5c3f9e8f0ae9ae13b968c314e7cf7f0", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v17.0/java_tools_windows-v17.0.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v17.0/java_tools_windows-v17.0.zip", - "sha": "3ae5075b228ce464c74bd23602a65016f662895556fa8952cba2995d50904c86", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.0/java_tools_windows-v18.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.0/java_tools_windows-v18.0.zip", + "sha": "66016d0c56c8f2d3f63e1076ae2b4baa598c5f51e531998336af112d4f3c72d0", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v17.0/java_tools_darwin_x86_64-v17.0.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v17.0/java_tools_darwin_x86_64-v17.0.zip", - "sha": "c65a181af0e723ed1a36c494aa0f70753f128adb7655a7b57f8f7e71217ad35c", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.0/java_tools_darwin_x86_64-v18.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.0/java_tools_darwin_x86_64-v18.0.zip", + "sha": "843b393d4a7ece1baea0d3611c6fe997d5326c36bd743501bd472a7d1e808edd", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v17.0/java_tools_darwin_arm64-v17.0.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v17.0/java_tools_darwin_arm64-v17.0.zip", - "sha": "00787917e359e2218953dbc30e228670e83fa20c4a0a5f914e0b6ecdee85fa9d", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.0/java_tools_darwin_arm64-v18.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.0/java_tools_darwin_arm64-v18.0.zip", + "sha": "657ecf25c4a8119a9e73a04a4f4f4e357250e68adbf83a77327053705877dd4f", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v17.0/java_tools-v17.0.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v17.0/java_tools-v17.0.zip", - "sha": "9a441ca2d4ae393edd305b0e465b0ed8ee86b22123c41c26455fb856bf9bc897", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.0/java_tools-v18.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.0/java_tools-v18.0.zip", + "sha": "75a5d083a72782ea66806ee447729d1ab24b6100303da6e7985fcadae5c62533", }, }, } From dbd8cb408911b79c6d7047ac4355ff89b1b90685 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 2 Dec 2025 00:50:55 -0800 Subject: [PATCH 358/465] Release `rules_java` `v9.2.0` PiperOrigin-RevId: 839134114 Change-Id: Ic149bcc8ca9b8b7e96305330716483d7f3a6a54a --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 24653fe2..527f5bf9 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "9.1.0", + version = "9.2.0", bazel_compatibility = [">=7.0.0"], compatibility_level = 1, ) From 20951906fa6a74346663acc39a6fd22378128cb6 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 3 Dec 2025 06:08:39 -0800 Subject: [PATCH 359/465] Refer to the SingleJar "executable" instead of "deploy jar." I don't think it's been a deploy jar in any environment for a while, and whatever it is, I think we run it directly as a executable. PiperOrigin-RevId: 839725877 Change-Id: I8d8e67b3eb7bd4af11387efb727853740370f565 --- java/common/rules/java_toolchain.bzl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java/common/rules/java_toolchain.bzl b/java/common/rules/java_toolchain.bzl index d08775a5..a24ae4f1 100644 --- a/java/common/rules/java_toolchain.bzl +++ b/java/common/rules/java_toolchain.bzl @@ -43,7 +43,7 @@ JavaToolchainInfo, _new_javatoolchaininfo = provider( "jvm_opt": "(depset[str]) The default options for the JVM running the java compiler and associated tools.", "label": "(label) The toolchain label.", "proguard_allowlister": "(FilesToRunProvider) The binary to validate proguard configuration.", - "single_jar": "(FilesToRunProvider) The SingleJar deploy jar.", + "single_jar": "(FilesToRunProvider) The SingleJar executable.", "source_version": "(str) The java source version.", "target_version": "(str) The java target version.", "tools": "(depset[File]) The compilation tools.", @@ -546,7 +546,7 @@ Label of the Proguard allowlister. allow_files = True, executable = True, doc = """ -Label of the SingleJar deploy jar. +Label of the SingleJar executable. """, ), "source_version": attr.string( From 14562f01110b7fb272625abe8250d438a7855993 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 3 Dec 2025 12:03:02 -0800 Subject: [PATCH 360/465] Support --library boolean flag for Android Lint in Java rules PiperOrigin-RevId: 839855551 Change-Id: I7d28e22b9fed9c8cd9f64bceb1081ac9fa8f97ab --- java/common/rules/android_lint.bzl | 4 +++- java/common/rules/impl/basic_java_library_impl.bzl | 5 ++++- java/common/rules/impl/java_binary_impl.bzl | 1 + 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/java/common/rules/android_lint.bzl b/java/common/rules/android_lint.bzl index f0a04328..032e06bc 100644 --- a/java/common/rules/android_lint.bzl +++ b/java/common/rules/android_lint.bzl @@ -22,7 +22,7 @@ def _tokenize_opts(opts_depset): opts = reversed(opts_depset.to_list()) return semantics.tokenize_javacopts(opts) -def _android_lint_action(ctx, source_files, source_jars, compilation_info): +def _android_lint_action(ctx, source_files, source_jars, compilation_info, is_library): """ Creates an action that runs Android lint against Java source files. @@ -42,6 +42,7 @@ def _android_lint_action(ctx, source_files, source_jars, compilation_info): source_jars: (list[File]) A list of .jar or .srcjar files containing source files. It should also include generated source jars. compilation_info: (struct) Information about compilation. + is_library: (bool) Whether the target is a library. Returns: (None|File) The Android lint output file or None if no source files were @@ -101,6 +102,7 @@ def _android_lint_action(ctx, source_files, source_jars, compilation_info): args.add_all("--classpath", classpath) args.add_all("--lint_rules", compilation_info.plugins.processor_jars) args.add("--target_label", ctx.label) + args.add("--library", str(is_library).lower()) javac_opts = compilation_info.javac_options if javac_opts: diff --git a/java/common/rules/impl/basic_java_library_impl.bzl b/java/common/rules/impl/basic_java_library_impl.bzl index cf7c5c19..a0105794 100644 --- a/java/common/rules/impl/basic_java_library_impl.bzl +++ b/java/common/rules/impl/basic_java_library_impl.bzl @@ -71,7 +71,8 @@ def basic_java_library( add_exports = [], add_opens = [], bootclasspath = None, - javabuilder_jvm_flags = None): + javabuilder_jvm_flags = None, + is_library = True): """ Creates actions that compile and lint Java sources, sets up coverage and returns JavaInfo, InstrumentedFilesInfo and output groups. @@ -107,6 +108,7 @@ def basic_java_library( add_opens: (list[str]) Allow this library to reflectively access the given /. bootclasspath: (Target) The JDK APIs to compile this library against. javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. + is_library: (bool) Whether the target is a library. Primarily for static analysis purposes. Returns: (dict[str, Provider], {files_to_build: list[File], @@ -168,6 +170,7 @@ def basic_java_library( source_files, source_jars + generated_source_jars, compilation_info, + is_library, ) if lint_output: validation_outputs.append(depset([lint_output])) diff --git a/java/common/rules/impl/java_binary_impl.bzl b/java/common/rules/impl/java_binary_impl.bzl index 50dcaae9..8b9b68de 100644 --- a/java/common/rules/impl/java_binary_impl.bzl +++ b/java/common/rules/impl/java_binary_impl.bzl @@ -118,6 +118,7 @@ def basic_java_binary( add_exports = ctx.attr.add_exports, add_opens = ctx.attr.add_opens, bootclasspath = ctx.attr.bootclasspath, + is_library = False, ) java_info = target["JavaInfo"] compilation_info = java_info.compilation_info From e6ba46c4e3b70797b164713ca1c01a7e25c44fa9 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 4 Dec 2025 03:09:54 -0800 Subject: [PATCH 361/465] Internal change (ignore-relnotes) PiperOrigin-RevId: 840160023 Change-Id: I0d0e965fca4bfce972b6b2fde504a4132e692f9e --- java/private/legacy_native.bzl | 2 ++ java/private/native.bzl | 2 ++ 2 files changed, 4 insertions(+) diff --git a/java/private/legacy_native.bzl b/java/private/legacy_native.bzl index 7a9e62fc..770434bc 100644 --- a/java/private/legacy_native.bzl +++ b/java/private/legacy_native.bzl @@ -17,6 +17,8 @@ """Lovely workaround to be able to expose native constants pretending to be Starlark.""" +# copybara: default visibility + # Unused with Bazel@HEAD, only used by the compatibility layer for older Bazel versions # buildifier: disable=native-java-common diff --git a/java/private/native.bzl b/java/private/native.bzl index be7ae686..cd45aa7a 100644 --- a/java/private/native.bzl +++ b/java/private/native.bzl @@ -14,6 +14,8 @@ """Redirects for private native APIs""" +# copybara: default visibility + # Used for some private native APIs that we can't replicate just yet in Starlark def get_internal_java_common(): return java_common.internal_DO_NOT_USE() # buildifier: disable=native-java-common From 92f148693341f6f7e10667af5f02a6829eda235b Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 9 Dec 2025 07:36:00 -0800 Subject: [PATCH 362/465] Update to `java_tools` `18.1` For https://github.com/bazelbuild/bazel/issues/27862 PiperOrigin-RevId: 842231974 Change-Id: I77d2196e6d5b595c9dd93344f2982e06423b0dc4 --- java/repositories.bzl | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/java/repositories.bzl b/java/repositories.bzl index 1e336502..5b1f317e 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,38 +22,38 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v18.0", + "version": "v18.1", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.0/java_tools_linux-v18.0.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.0/java_tools_linux-v18.0.zip", - "sha": "f0b49f6fa369f581b1194a91feb55ef8bf99683c7e76867854b6372782772f00", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.1/java_tools_linux-v18.1.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.1/java_tools_linux-v18.1.zip", + "sha": "e22cbb2600249576c6a0a02af3f78e26537a89b6be11ef3826c01f9019faaa61", }, "java_tools_linux_aarch64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.0/java_tools_linux_aarch64-v18.0.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.0/java_tools_linux_aarch64-v18.0.zip", - "sha": "8f8a436c858e39ae9f40b54a3515e0c6b5c3f9e8f0ae9ae13b968c314e7cf7f0", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.1/java_tools_linux_aarch64-v18.1.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.1/java_tools_linux_aarch64-v18.1.zip", + "sha": "4f75420bafb8c6554105c90ed05db3d7ff5942dbc1633459c20d2dcc06eff6ac", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.0/java_tools_windows-v18.0.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.0/java_tools_windows-v18.0.zip", - "sha": "66016d0c56c8f2d3f63e1076ae2b4baa598c5f51e531998336af112d4f3c72d0", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.1/java_tools_windows-v18.1.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.1/java_tools_windows-v18.1.zip", + "sha": "fe6dccef1b290b9e2a539cecfd57d924f719480ac04e55d03fdca5533272cd04", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.0/java_tools_darwin_x86_64-v18.0.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.0/java_tools_darwin_x86_64-v18.0.zip", - "sha": "843b393d4a7ece1baea0d3611c6fe997d5326c36bd743501bd472a7d1e808edd", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.1/java_tools_darwin_x86_64-v18.1.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.1/java_tools_darwin_x86_64-v18.1.zip", + "sha": "68f6b540a28ff1d98acd9313900c50560d52022ee2399627b9c92b1bb2c5d466", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.0/java_tools_darwin_arm64-v18.0.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.0/java_tools_darwin_arm64-v18.0.zip", - "sha": "657ecf25c4a8119a9e73a04a4f4f4e357250e68adbf83a77327053705877dd4f", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.1/java_tools_darwin_arm64-v18.1.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.1/java_tools_darwin_arm64-v18.1.zip", + "sha": "07026303be4662462733d00eaf8e956cd9589493e104934862f0b53e76758d88", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.0/java_tools-v18.0.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.0/java_tools-v18.0.zip", - "sha": "75a5d083a72782ea66806ee447729d1ab24b6100303da6e7985fcadae5c62533", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.1/java_tools-v18.1.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.1/java_tools-v18.1.zip", + "sha": "27cab59ba5ff8ee7cf3071971fe2587a295daefe82531f27b4f061111276163d", }, }, } From 9d6184b9f6979fe5680f8b99173656a45aea53e8 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 9 Dec 2025 07:42:11 -0800 Subject: [PATCH 363/465] Release `rules_java` `9.3.0` PiperOrigin-RevId: 842233855 Change-Id: Ifd52f02586754a8543cfab84469bc54ebc749be3 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 527f5bf9..23ee0cee 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "9.2.0", + version = "9.3.0", bazel_compatibility = [">=7.0.0"], compatibility_level = 1, ) From 59e9cb58e40b54035e58a1b373ee207b10912e63 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 19 Dec 2025 06:41:58 -0800 Subject: [PATCH 364/465] Automatic code cleanup. PiperOrigin-RevId: 846713425 Change-Id: Id0e2b980fc4082582556de3084d1ddd0316fc7cd --- BUILD | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILD b/BUILD index 2761f404..9f0e2239 100644 --- a/BUILD +++ b/BUILD @@ -1,6 +1,6 @@ load("@rules_license//rules:license.bzl", "license") -package(default_applicable_licenses = ["@rules_java//:license"]) +package(default_applicable_licenses = [":license"]) licenses(["notice"]) From aa0345c749ae24b4ff3e9ca92e52bbcd96bc135a Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 5 Jan 2026 08:21:14 -0800 Subject: [PATCH 365/465] Instruct `java_binary` not to compress `protobuf.meta`. Compressing the file accounts for a noticeable fraction of runtime. This CL has no effect until after a JavaBuilder that contains unknown commit. PiperOrigin-RevId: 852309989 Change-Id: I255419359afb4f0fee0ffcf7a233f385c8d81b53 --- java/common/rules/impl/java_binary_deploy_jar.bzl | 1 + 1 file changed, 1 insertion(+) diff --git a/java/common/rules/impl/java_binary_deploy_jar.bzl b/java/common/rules/impl/java_binary_deploy_jar.bzl index 8755d959..7b7d69d1 100644 --- a/java/common/rules/impl/java_binary_deploy_jar.bzl +++ b/java/common/rules/impl/java_binary_deploy_jar.bzl @@ -182,6 +182,7 @@ def create_deploy_archive( args.add("--build_target", build_target) args.add("--normalize") args.add("--compression") + args.add("--nocompress_suffixes", "protobuf.meta") if main_class: args.add("--main_class", main_class) args.add_all("--deploy_manifest_lines", manifest_lines) From 624b2083103705e583ea4a17a7f3f902aa921412 Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Thu, 8 Jan 2026 09:09:41 -0800 Subject: [PATCH 366/465] avoid loading from defs.bzl (#341) At least the example should use the preferred load paths. Closes #341 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/341 from benjaminp:no-defs 479d18ebcdf74770ffa0c4573d56d5c9399212d3 PiperOrigin-RevId: 853768220 Change-Id: Iee1770d77675a9bfb371894aaac0ac6b67320d09 --- examples/hello_world/BUILD | 2 +- .../src/main/java/com/google/devtools/build/runfiles/BUILD | 3 ++- test/java/private/android_support_tests.bzl | 3 ++- .../testutil/rules/custom_library_with_wrong_plugins_type.bzl | 3 ++- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/examples/hello_world/BUILD b/examples/hello_world/BUILD index 2e951cc2..f8ee9577 100644 --- a/examples/hello_world/BUILD +++ b/examples/hello_world/BUILD @@ -1,4 +1,4 @@ -load("//java:defs.bzl", "java_binary") +load("//java:java_binary.bzl", "java_binary") package(default_applicable_licenses = ["@rules_java//:license"]) diff --git a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD index 5b521a9b..11b8ae0f 100644 --- a/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD +++ b/java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD @@ -1,4 +1,5 @@ -load("//java:defs.bzl", "java_library", "java_plugin") +load("//java:java_library.bzl", "java_library") +load("//java:java_plugin.bzl", "java_plugin") package(default_applicable_licenses = ["@rules_java//:license"]) diff --git a/test/java/private/android_support_tests.bzl b/test/java/private/android_support_tests.bzl index 95596de2..8f9bea64 100644 --- a/test/java/private/android_support_tests.bzl +++ b/test/java/private/android_support_tests.bzl @@ -15,7 +15,8 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") -load("//java:defs.bzl", "java_library", "java_plugin") +load("//java:java_library.bzl", "java_library") +load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") load("//java/private:android_support.bzl", "android_support") # buildifier: disable=bzl-visibility load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") diff --git a/test/java/testutil/rules/custom_library_with_wrong_plugins_type.bzl b/test/java/testutil/rules/custom_library_with_wrong_plugins_type.bzl index 12535307..dc58cee1 100644 --- a/test/java/testutil/rules/custom_library_with_wrong_plugins_type.bzl +++ b/test/java/testutil/rules/custom_library_with_wrong_plugins_type.bzl @@ -1,6 +1,7 @@ """Custom rule to test java_common.compile(plugins = ...) expects JavaPluginInfo""" -load("//java:defs.bzl", "JavaInfo", "java_common") +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") def _impl(ctx): From e0bcbba9d24771be7b885676298e14ce3058d84d Mon Sep 17 00:00:00 2001 From: hvadehra Date: Fri, 30 Jan 2026 01:29:53 -0800 Subject: [PATCH 367/465] Fix javacopts make variable expansion regression (#346) Looks like this was a regression introduced when we Starlarkified the rules. Unfortunately, we apparently had no test coverage for this, and no usages internally either. No one has complained about it since either - until now. Fixes https://github.com/bazelbuild/rules_java/issues/345 Closes #346 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/346 from bazelbuild:hvd_i345 524df33e55cf73e76dea4d21fe9d0dda418621f2 PiperOrigin-RevId: 863121793 Change-Id: I50c393f85a5117401bd470b85ee62108d9f0a5fe --- java/common/java_semantics.bzl | 1 + java/common/rules/impl/compile_action.bzl | 7 ++- test/java/bazel/rules/BUILD.bazel | 6 +++ test/java/bazel/rules/java_binary_tests.bzl | 32 ++++++++++++++ test/java/bazel/rules/java_library_tests.bzl | 44 +++++++++++++++++++ test/java/bazel/rules/java_plugin_tests.bzl | 43 ++++++++++++++++++ .../testutil/rules/template_var_info_rule.bzl | 13 ++++++ 7 files changed, 144 insertions(+), 2 deletions(-) create mode 100644 test/java/bazel/rules/java_library_tests.bzl create mode 100644 test/java/bazel/rules/java_plugin_tests.bzl create mode 100644 test/java/testutil/rules/template_var_info_rule.bzl diff --git a/java/common/java_semantics.bzl b/java/common/java_semantics.bzl index 700c0d1d..31c0a006 100644 --- a/java/common/java_semantics.bzl +++ b/java/common/java_semantics.bzl @@ -113,4 +113,5 @@ semantics = struct( tokenize_javacopts = _tokenize_javacopts, PLATFORMS_ROOT = "@platforms//", INCOMPATIBLE_DISABLE_NON_EXECUTABLE_JAVA_BINARY = False, # Flip when java_single_jar is feature complete + expand_javacopts_make_variables = True, ) diff --git a/java/common/rules/impl/compile_action.bzl b/java/common/rules/impl/compile_action.bzl index bf5b9359..098c55bb 100644 --- a/java/common/rules/impl/compile_action.bzl +++ b/java/common/rules/impl/compile_action.bzl @@ -135,7 +135,10 @@ def compile_action( Files_to_build may include an empty .jar file when there are no sources or resources present, whereas runfiles in this case are empty. """ - + expanded_javacopts = javacopts + if semantics.expand_javacopts_make_variables: + expanded_javacopts = [ctx.expand_make_variables("javacopts", opt, {}) for opt in expanded_javacopts] + expanded_javacopts = [ctx.expand_location(opt) for opt in expanded_javacopts] java_info = _compile_private_for_builtins( ctx, output = output_class_jar, @@ -151,7 +154,7 @@ def compile_action( runtime_deps = runtime_deps, exports = exports, exported_plugins = exported_plugins, - javac_opts = [ctx.expand_location(opt) for opt in javacopts], + javac_opts = expanded_javacopts, neverlink = neverlink, output_source_jar = output_source_jar, strict_deps = _filter_strict_deps(strict_deps), diff --git a/test/java/bazel/rules/BUILD.bazel b/test/java/bazel/rules/BUILD.bazel index 3bf8f436..01655c20 100644 --- a/test/java/bazel/rules/BUILD.bazel +++ b/test/java/bazel/rules/BUILD.bazel @@ -1,3 +1,9 @@ load(":java_binary_tests.bzl", "java_binary_tests") +load(":java_library_tests.bzl", "java_library_tests") +load(":java_plugin_tests.bzl", "java_plugin_tests") java_binary_tests(name = "java_binary_tests") + +java_library_tests(name = "java_library_tests") + +java_plugin_tests(name = "java_plugin_tests") diff --git a/test/java/bazel/rules/java_binary_tests.bzl b/test/java/bazel/rules/java_binary_tests.bzl index 32036d82..2d015b67 100644 --- a/test/java/bazel/rules/java_binary_tests.bzl +++ b/test/java/bazel/rules/java_binary_tests.bzl @@ -3,6 +3,8 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") +load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:rules/template_var_info_rule.bzl", "template_var_info_rule") def _test_java_binary_cross_compilation_to_unix(name): # A Unix platform that: @@ -46,10 +48,40 @@ def _test_java_binary_cross_compilation_to_unix_impl(env, target): assert_action.substitutions().keys().contains("%jvm_flags%") assert_action.inputs().contains_exactly(["java/bazel/rules/java_stub_template.txt"]) +def _test_java_binary_javacopts_make_variable_expansion(name): + util.helper_target( + template_var_info_rule, + name = name + "/vars", + vars = { + "MY_CUSTOM_OPT": "MY_OPT_VALUE", + }, + ) + util.helper_target( + java_binary, + name = name + "/bin", + srcs = ["java/A.java"], + javacopts = ["$(MY_CUSTOM_OPT)"], + toolchains = [name + "/vars"], + ) + + analysis_test( + name = name, + impl = _test_java_binary_javacopts_make_variable_expansion_impl, + target = name + "/bin", + # Broken by Starlarkification in the embedded rules in Bazel 7 + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _test_java_binary_javacopts_make_variable_expansion_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + assert_java_info.compilation_info().javac_options().not_contains("$(MY_CUSTOM_OPT)") + assert_java_info.compilation_info().javac_options().contains("MY_OPT_VALUE") + def java_binary_tests(name): test_suite( name = name, tests = [ _test_java_binary_cross_compilation_to_unix, + _test_java_binary_javacopts_make_variable_expansion, ], ) diff --git a/test/java/bazel/rules/java_library_tests.bzl b/test/java/bazel/rules/java_library_tests.bzl new file mode 100644 index 00000000..770fbe60 --- /dev/null +++ b/test/java/bazel/rules/java_library_tests.bzl @@ -0,0 +1,44 @@ +"""Tests for the Bazel java_binary rule""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_library.bzl", "java_library") +load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:rules/template_var_info_rule.bzl", "template_var_info_rule") + +def _test_java_library_javacopts_make_variable_expansion(name): + util.helper_target( + template_var_info_rule, + name = name + "/vars", + vars = { + "MY_CUSTOM_OPT": "MY_OPT_VALUE", + }, + ) + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["java/A.java"], + javacopts = ["$(MY_CUSTOM_OPT)"], + toolchains = [name + "/vars"], + ) + + analysis_test( + name = name, + impl = _test_java_library_javacopts_make_variable_expansion_impl, + target = name + "/lib", + # Broken by Starlarkification in the embedded rules in Bazel 7 + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _test_java_library_javacopts_make_variable_expansion_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + assert_java_info.compilation_info().javac_options().not_contains("$(MY_CUSTOM_OPT)") + assert_java_info.compilation_info().javac_options().contains("MY_OPT_VALUE") + +def java_library_tests(name): + test_suite( + name = name, + tests = [ + _test_java_library_javacopts_make_variable_expansion, + ], + ) diff --git a/test/java/bazel/rules/java_plugin_tests.bzl b/test/java/bazel/rules/java_plugin_tests.bzl new file mode 100644 index 00000000..4df4bcca --- /dev/null +++ b/test/java/bazel/rules/java_plugin_tests.bzl @@ -0,0 +1,43 @@ +"""Tests for the Bazel java_binary rule""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_plugin.bzl", "java_plugin") +load("//test/java/testutil:rules/template_var_info_rule.bzl", "template_var_info_rule") + +def _test_java_plugin_javacopts_make_variable_expansion(name): + util.helper_target( + template_var_info_rule, + name = name + "/vars", + vars = { + "MY_CUSTOM_OPT": "MY_OPT_VALUE", + }, + ) + util.helper_target( + java_plugin, + name = name + "/plug", + srcs = ["java/A.java"], + javacopts = ["$(MY_CUSTOM_OPT)"], + toolchains = [name + "/vars"], + ) + + analysis_test( + name = name, + impl = _test_java_plugin_javacopts_make_variable_expansion_impl, + target = name + "/plug", + # Broken by Starlarkification in the embedded rules in Bazel 7 + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _test_java_plugin_javacopts_make_variable_expansion_impl(env, target): + assert_javac = env.expect.that_target(target).action_named("Javac") + assert_javac.not_contains_arg("$(MY_CUSTOM_OPT)") + assert_javac.contains_at_least_args(["MY_OPT_VALUE"]) + +def java_plugin_tests(name): + test_suite( + name = name, + tests = [ + _test_java_plugin_javacopts_make_variable_expansion, + ], + ) diff --git a/test/java/testutil/rules/template_var_info_rule.bzl b/test/java/testutil/rules/template_var_info_rule.bzl new file mode 100644 index 00000000..ebdc86cc --- /dev/null +++ b/test/java/testutil/rules/template_var_info_rule.bzl @@ -0,0 +1,13 @@ +"""Test rule to provide TemplateVariableInfo""" + +def _template_var_info_rule_impl(ctx): + return [ + platform_common.TemplateVariableInfo(ctx.attr.vars), + ] + +template_var_info_rule = rule( + _template_var_info_rule_impl, + attrs = { + "vars": attr.string_dict(default = {}), + }, +) From e910554011ae22d697ccf371d3f38f56b0721516 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 30 Jan 2026 03:00:28 -0800 Subject: [PATCH 368/465] Fix `@rules_java` CI after https://github.com/bazelbuild/buildtools/releases/tag/v8.5.1 Broken by https://github.com/bazelbuild/buildtools/pull/1386 PiperOrigin-RevId: 863149692 Change-Id: I81ca12ed891b539e0c4ccf133ffbc32478d80e43 --- java/common/rules/impl/java_helper.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/common/rules/impl/java_helper.bzl b/java/common/rules/impl/java_helper.bzl index efc7f0e5..e45fac9d 100644 --- a/java/common/rules/impl/java_helper.bzl +++ b/java/common/rules/impl/java_helper.bzl @@ -168,7 +168,7 @@ def _check_and_get_one_version_attribute(ctx, attr): def _jar_and_target_arg_mapper(jar): # Emit pretty labels for targets in the main repository. label = str(jar.owner) - if label.startswith("@@//"): + if label.startswith("@@//"): # buildifier: disable=canonical-repository label = label.lstrip("@") return jar.path + "," + label From 243a1d4f4b41d5c923868c94b3ebc6d8782580e6 Mon Sep 17 00:00:00 2001 From: Googler Date: Sat, 31 Jan 2026 02:12:28 -0800 Subject: [PATCH 369/465] Fix a `.jar` file in `java_import.runtime_deps` Wrap it in a separate `java_import` instead. This fixes a java_jars_in_deps_allowlist violation (b/479392897) and doesn't alter the meaning of the test. PiperOrigin-RevId: 863594466 Change-Id: I77bdb2cabdb7394ab95df452df6437a74b202bba --- test/java/common/rules/java_import_tests.bzl | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/java/common/rules/java_import_tests.bzl b/test/java/common/rules/java_import_tests.bzl index 7afbc77b..35b713df 100644 --- a/test/java/common/rules/java_import_tests.bzl +++ b/test/java/common/rules/java_import_tests.bzl @@ -658,11 +658,16 @@ def _test_duplicate_jars_through_filegroup_impl(env, target): def _test_runtime_deps_are_not_on_classpath(name): target_name = name + "/depends_on_runtimedep" + util.helper_target( + java_import, + name = target_name + "/import_runtime", + jars = ["import_runtime.jar"], + ) util.helper_target( java_import, name = target_name + "/import_dep", jars = ["import_compile.jar"], - runtime_deps = ["import_runtime.jar"], + runtime_deps = [target_name + "/import_runtime"], ) util.helper_target( java_library, From 7372e8ccb873074bea26cb9906fcd007b03ad8f9 Mon Sep 17 00:00:00 2001 From: Alex Eagle Date: Mon, 2 Feb 2026 07:44:42 -0800 Subject: [PATCH 370/465] chore(docs): add quickstart template link to README (#344) Added a quickstart template link for new projects. Note, this is the same destination reachable from https://bazel.build/start Closes #344 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/344 from alexeagle:patch-1 5fe92bd165e0f6f7f5d6f1c5c58828b3c24965df PiperOrigin-RevId: 864352722 Change-Id: Id64e5414c0ef7b8e339fd2717062f9f856ab5eaa --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index e4cfeb0b..52be4f9d 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,8 @@ Java Rules for Bazel https://bazel.build. For a quickstart tutorial, see https://bazel.build/start/java +The fastest way to try this in an empty project is to click the green "Use this template" button on https://github.com/bazel-starters/java. + For slightly more advanced usage, like setting up toolchains or writing your own java-like rules, see https://bazel.build/docs/bazel-and-java From 1824a5548e56ecd337687ff32baf98e37ddd6b16 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 5 Feb 2026 06:07:52 -0800 Subject: [PATCH 371/465] Add `--sun-misc-unsafe-memory-access=allow` to `JavaBuilder`'s jvm flags Fixes https://github.com/bazelbuild/rules_java/issues/348 PiperOrigin-RevId: 865909019 Change-Id: I1c7fc8857eac63b37aad775b52a4370830513dac --- test/toolchains/BUILD.bazel | 7 +++-- .../default_java_toolchain_tests.bzl | 30 +++++++++++++++++++ toolchains/default_java_toolchain.bzl | 2 ++ 3 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 test/toolchains/default_java_toolchain_tests.bzl diff --git a/test/toolchains/BUILD.bazel b/test/toolchains/BUILD.bazel index e25b3d8c..24ae5352 100644 --- a/test/toolchains/BUILD.bazel +++ b/test/toolchains/BUILD.bazel @@ -1,7 +1,8 @@ load(":bootclasspath_tests.bzl", "bootclasspath_tests") +load(":default_java_toolchain_tests.bzl", "default_java_toolchain_tests") package(default_applicable_licenses = ["@rules_java//:license"]) -bootclasspath_tests( - name = "bootclasspath_tests", -) +bootclasspath_tests(name = "bootclasspath_tests") + +default_java_toolchain_tests(name = "default_java_toolchain_tests") diff --git a/test/toolchains/default_java_toolchain_tests.bzl b/test/toolchains/default_java_toolchain_tests.bzl new file mode 100644 index 00000000..bdfa400b --- /dev/null +++ b/test/toolchains/default_java_toolchain_tests.bzl @@ -0,0 +1,30 @@ +"""Tests for the default java toolchain configuration""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_library.bzl", "java_library") + +def _test_java_builder_jvm_flags(name): + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["A.java"], + ) + analysis_test( + name = name, + impl = _test_java_builder_jvm_flags_impl, + target = name + "/lib", + ) + +def _test_java_builder_jvm_flags_impl(env, target): + env.expect.that_target(target).action_named("Javac").contains_flag_values([ + ("--sun-misc-unsafe-memory-access", "allow"), + ]) + +def default_java_toolchain_tests(name): + test_suite( + name = name, + tests = [ + _test_java_builder_jvm_flags, + ], + ) diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl index f4f83f66..df53468a 100644 --- a/toolchains/default_java_toolchain.bzl +++ b/toolchains/default_java_toolchain.bzl @@ -103,6 +103,8 @@ _BASE_TOOLCHAIN_CONFIGURATION = dict( # targeting JDK 7. java_runtime = Label("//toolchains:remotejdk_21"), oneversion = Label("//toolchains:one_version"), + # TODO: remove after https://github.com/protocolbuffers/protobuf/issues/20760 is fixed + javabuilder_jvm_opts = ["--sun-misc-unsafe-memory-access=allow"], ) DEFAULT_TOOLCHAIN_CONFIGURATION = _BASE_TOOLCHAIN_CONFIGURATION From ad1b9c839f1de28ef0413fab334b5bf8c806ed41 Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Thu, 5 Feb 2026 06:23:56 -0800 Subject: [PATCH 372/465] upgrade jdk25 to 25.0.2 (#349) Closes #349 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/349 from benjaminp:jdk25.0.2 3445d8ab420b7048314b5dcf517ec853a722d32d PiperOrigin-RevId: 865914463 Change-Id: Iab0a058d475653dd9a9c17afc9b46aaee5c4e574 --- java/bazel/repositories_util.bzl | 2 +- java/repositories.bzl | 36 ++++++++++++++++---------------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/java/bazel/repositories_util.bzl b/java/bazel/repositories_util.bzl index 924bb60f..4cf69561 100644 --- a/java/bazel/repositories_util.bzl +++ b/java/bazel/repositories_util.bzl @@ -88,7 +88,7 @@ _RELEASE_CONFIGS = { }, "25": { "zulu": { - "release": "25.30.17-ca-jdk25.0.1", + "release": "25.32.17-ca-jdk25.0.2", "platforms": { "linux": ["aarch64", "x86_64"], "macos": ["aarch64", "x86_64"], diff --git a/java/repositories.bzl b/java/repositories.bzl index 5b1f317e..e3d7d050 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -333,49 +333,49 @@ _REMOTE_JDK_CONFIGS_LIST = [ struct( name = "remotejdk25_linux_aarch64", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:aarch64"], - sha256 = "8c5321f16d9f1d8149f83e4e9ff8ca5d9e94320b92d205e6db42a604de3d1140", - strip_prefix = "zulu25.30.17-ca-jdk25.0.1-linux_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-linux_aarch64.tar.gz"], + sha256 = "f7295abb1decb2f6e0ea9f760a70917f2d47356db4366d615c7ab9b01c3c6866", + strip_prefix = "zulu25.32.17-ca-jdk25.0.2-linux_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-linux_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-linux_aarch64.tar.gz"], version = "25", ), struct( name = "remotejdk25_linux", target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:x86_64"], - sha256 = "471b3e62bdffaed27e37005d842d8639f10d244ccce1c7cdebf7abce06c8313e", - strip_prefix = "zulu25.30.17-ca-jdk25.0.1-linux_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-linux_x64.tar.gz"], + sha256 = "f1752d0051b6ca233625ddb2c18c9170edbe55c5ee6515bfefd8ea0197ee1c20", + strip_prefix = "zulu25.32.17-ca-jdk25.0.2-linux_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-linux_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-linux_x64.tar.gz"], version = "25", ), struct( name = "remotejdk25_macos_aarch64", target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:aarch64"], - sha256 = "126061d6046b0c0df0472b361ca7895951d34fef1dd522f222f2c7d8738a39d8", - strip_prefix = "zulu25.30.17-ca-jdk25.0.1-macosx_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-macosx_aarch64.tar.gz"], + sha256 = "537ac74fa1ca2c4dd8f6063ddede0138ae4a896f128bfe10b428a7dcc4aa929f", + strip_prefix = "zulu25.32.17-ca-jdk25.0.2-macosx_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-macosx_aarch64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-macosx_aarch64.tar.gz"], version = "25", ), struct( name = "remotejdk25_macos", target_compatible_with = ["@platforms//os:macos", "@platforms//cpu:x86_64"], - sha256 = "0154482b317aa63d5158a358e2fab7f0fd6c3c0ba2000b05655c3bcbdd202584", - strip_prefix = "zulu25.30.17-ca-jdk25.0.1-macosx_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-macosx_x64.tar.gz"], + sha256 = "fe22346c192920c5b84b23f4aa24e3debb0bb94fc428016f7c2b2c7790c82780", + strip_prefix = "zulu25.32.17-ca-jdk25.0.2-macosx_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-macosx_x64.tar.gz", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-macosx_x64.tar.gz"], version = "25", ), struct( name = "remotejdk25_win_arm64", target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:arm64"], - sha256 = "4883cf39e8d83679c8a051ace4dd72759d97195a72aaa6727a83bd4bcb97b022", - strip_prefix = "zulu25.30.17-ca-jdk25.0.1-win_aarch64", - urls = ["https://cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-win_aarch64.zip"], + sha256 = "5f44792a12af2100b4db9b5120c27c42af8080ad63bc9eaadc9ca25e5c7dd590", + strip_prefix = "zulu25.32.17-ca-jdk25.0.2-win_aarch64", + urls = ["https://cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-win_aarch64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-win_aarch64.zip"], version = "25", ), struct( name = "remotejdk25_win", target_compatible_with = ["@platforms//os:windows", "@platforms//cpu:x86_64"], - sha256 = "72844ba8dddf9259ab9cfda9d515d0c850179705f74278a75973d73f0c5b2d2b", - strip_prefix = "zulu25.30.17-ca-jdk25.0.1-win_x64", - urls = ["https://cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.30.17-ca-jdk25.0.1-win_x64.zip"], + sha256 = "90bcbbcbe2fb7aec43ce8fd2efa024fcc48f00bbdcd7a76b58f912d6b97e6d56", + strip_prefix = "zulu25.32.17-ca-jdk25.0.2-win_x64", + urls = ["https://cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-win_x64.zip"], version = "25", ), ] From d2d725805f1ee6ec8d109a698059ae7a683eb37f Mon Sep 17 00:00:00 2001 From: Levi Zim Date: Thu, 5 Feb 2026 07:34:09 -0800 Subject: [PATCH 373/465] Add remote JDK 25 for riscv64, ppc64le and s390x (#347) A remote JDK 25 is necessary for building Bazel 9. This PR adds remote JDK 25 for riscv64, ppc64le and s390x architectures to fix build failure of bazel 9.0 on these architectures: https://archriscv.felixc.at/.status/log.htm?url=logs/bazel/bazel-9.0.0-1.log Closes #347 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/347 from kxxt:rv25 218f68fb260e3666229289e2e646c02ee39dd3c5 PiperOrigin-RevId: 865939228 Change-Id: I669632c630a02b9fe8af671df9dec8f2c92715c3 --- MODULE.bazel | 3 +++ java/bazel/repositories_util.bzl | 6 ++++++ java/repositories.bzl | 24 ++++++++++++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/MODULE.bazel b/MODULE.bazel index 23ee0cee..7dbbc2ee 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -100,6 +100,9 @@ JDKS = { "25": [ "linux", "linux_aarch64", + "linux_ppc64le", + "linux_riscv64", + "linux_s390x", "macos", "macos_aarch64", "win", diff --git a/java/bazel/repositories_util.bzl b/java/bazel/repositories_util.bzl index 4cf69561..40101d37 100644 --- a/java/bazel/repositories_util.bzl +++ b/java/bazel/repositories_util.bzl @@ -95,6 +95,12 @@ _RELEASE_CONFIGS = { "windows": ["arm64", "x86_64"], }, }, + "adoptium": { + "release": "25.0.2+10", + "platforms": { + "linux": ["ppc64le", "riscv64", "s390x"], + }, + }, }, } diff --git a/java/repositories.bzl b/java/repositories.bzl index e3d7d050..5a290b4d 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -378,6 +378,30 @@ _REMOTE_JDK_CONFIGS_LIST = [ urls = ["https://cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-win_x64.zip", "https://mirror.bazel.build/cdn.azul.com/zulu/bin/zulu25.32.17-ca-jdk25.0.2-win_x64.zip"], version = "25", ), + struct( + name = "remotejdk25_linux_ppc64le", + target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:ppc64le"], + sha256 = "b262b735b215173003766da36588d5f717dceada0286db41b439f93fb2ada468", + strip_prefix = "jdk-25.0.2+10", + urls = ["https://github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.2+10/OpenJDK25U-jdk_ppc64le_linux_hotspot_25.0.2_10.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.2+10/OpenJDK25U-jdk_ppc64le_linux_hotspot_25.0.2_10.tar.gz"], + version = "25", + ), + struct( + name = "remotejdk25_linux_riscv64", + target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:riscv64"], + sha256 = "168119e4fba350f4e6b3ca92450a2b90a8502b89a235a04415e9adf9f5d3164e", + strip_prefix = "jdk-25.0.2+10", + urls = ["https://github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.2+10/OpenJDK25U-jdk_riscv64_linux_hotspot_25.0.2_10.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.2+10/OpenJDK25U-jdk_riscv64_linux_hotspot_25.0.2_10.tar.gz"], + version = "25", + ), + struct( + name = "remotejdk25_linux_s390x", + target_compatible_with = ["@platforms//os:linux", "@platforms//cpu:s390x"], + sha256 = "15e5cbcadcf3d43623c31b825063cdc2817b9f1ba840b51dc6ef70e5d33c84e3", + strip_prefix = "jdk-25.0.2+10", + urls = ["https://github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.2+10/OpenJDK25U-jdk_s390x_linux_hotspot_25.0.2_10.tar.gz", "https://mirror.bazel.build/github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.2+10/OpenJDK25U-jdk_s390x_linux_hotspot_25.0.2_10.tar.gz"], + version = "25", + ), ] def _make_version_to_remote_jdks(): From bef4f9893536fd1b41589a44a85863dc6b81e1b0 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 5 Feb 2026 08:48:39 -0800 Subject: [PATCH 374/465] Add testing for Bazel 9 to `@rules_java` CI Also switch from using fixed versions with latest release for each major version. PiperOrigin-RevId: 865968441 Change-Id: I9809f82cd9e6ece901b1cd7a4e5754b17196581d --- .bazelci/presubmit.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 4fe6a435..30c63935 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -34,8 +34,8 @@ buildifier: latest matrix: all_platforms: ["rockylinux8_arm64", "ubuntu2004", "macos", "macos_arm64", "windows"] - bazel: ["7.7.1", "8.4.2", "last_green"] - modern_bazel: ["last_green", "rolling"] # Fully supported Bazel versions + bazel: ["7.x", "8.x", "9.x", "last_green"] + modern_bazel: ["9.x", "last_green", "rolling"] # Fully supported Bazel versions tasks: # Bazel 9+ @@ -47,8 +47,8 @@ tasks: test_targets: *test_targets # Bazel 8.x build_and_test_bazel8: - name: "Bazel 8.4.2" - bazel: "8.4.2" + name: "Bazel 8.x" + bazel: "8.x" platform: ${{ all_platforms }} build_targets: *build_targets test_targets: *test_targets @@ -56,8 +56,8 @@ tasks: - "--test_tag_filters=-min_bazel_9" # Bazel 7.x build_and_test_bazel7: - name: "Bazel 7.7.1" - bazel: "7.7.1" + name: "Bazel 7.x" + bazel: "7.x" platform: ${{ all_platforms }} build_targets: *build_targets test_targets: *test_targets From 4566a5d621cd7943eda31aba6f63049cb43aef66 Mon Sep 17 00:00:00 2001 From: Googler Date: Sat, 7 Feb 2026 01:18:24 -0800 Subject: [PATCH 375/465] Fix `java_single_jar` compatibility with Bazel 7 Rule extension APIs weren't enabled by default in Bazel 7, so the rule was broken after https://github.com/bazelbuild/rules_java/commit/37b099cfd27de53495aea44763a16cd23ff929df Also add a dummy target under `test/repo` to build as a regression test. Fixes https://github.com/bazelbuild/rules_java/issues/350 PiperOrigin-RevId: 866808173 Change-Id: I594f0194be02f935154585e68d091172140301e1 --- java/BUILD | 4 +- java/bazel/rules/bazel_java_single_jar.bzl | 21 +++ java/common/rules/BUILD | 8 + java/common/rules/java_single_jar.bzl | 167 +++++++++++++++++++++ java/java_single_jar.bzl | 159 +------------------- test/repo/BUILD.bazel | 10 ++ 6 files changed, 212 insertions(+), 157 deletions(-) create mode 100644 java/bazel/rules/bazel_java_single_jar.bzl create mode 100644 java/common/rules/java_single_jar.bzl diff --git a/java/BUILD b/java/BUILD index 452c7654..7888daba 100644 --- a/java/BUILD +++ b/java/BUILD @@ -65,7 +65,9 @@ bzl_library( name = "java_single_jar", srcs = ["java_single_jar.bzl"], visibility = ["//visibility:public"], - deps = ["//java/common"], + deps = [ + "//java/bazel/rules", # copybara-use-repo-external-label + ], ) bzl_library( diff --git a/java/bazel/rules/bazel_java_single_jar.bzl b/java/bazel/rules/bazel_java_single_jar.bzl new file mode 100644 index 00000000..922fb638 --- /dev/null +++ b/java/bazel/rules/bazel_java_single_jar.bzl @@ -0,0 +1,21 @@ +# Copyright 2026 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. +"""Bazel java_single_jar rule""" + +load("//java/common/rules:java_single_jar.bzl", _bazel_java_single_jar = "bazel_java_single_jar") + +def java_single_jar(*, name, **kwargs): + if "output" not in kwargs: + kwargs["output"] = name + ".jar" + _bazel_java_single_jar(name = name, **kwargs) diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD index 5bb5c2fb..f6fde9d4 100644 --- a/java/common/rules/BUILD +++ b/java/common/rules/BUILD @@ -31,6 +31,13 @@ bzl_library( visibility = ["//java:__subpackages__"], ) +bzl_library( + name = "java_single_jar_bzl", + srcs = ["java_single_jar.bzl"], + visibility = ["//java:__subpackages__"], + deps = ["//java/common"], +) + bzl_library( name = "core_rules", srcs = [ @@ -81,6 +88,7 @@ filegroup( srcs = [ "BUILD", ":core_rules", + ":java_single_jar_bzl", ":toolchain_rules", "//java/common/rules/impl:for_bazel_tests", "@rules_cc//cc/private/rules_impl:srcs", diff --git a/java/common/rules/java_single_jar.bzl b/java/common/rules/java_single_jar.bzl new file mode 100644 index 00000000..95b7ca2e --- /dev/null +++ b/java/common/rules/java_single_jar.bzl @@ -0,0 +1,167 @@ +# Copyright 2026 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. +"""Definition of the java_single_jar rule.""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") + +# copybara: default visibility + +def _single_jar_inputs(deps, deploy_env): + transitive_inputs = [] + for dep in deps: + if JavaInfo in dep: + info = dep[JavaInfo] + transitive_inputs.append(info.transitive_runtime_jars) + if hasattr(info, "compilation_info"): + compilation_info = info.compilation_info + if hasattr(compilation_info, "runtime_classpath"): + transitive_inputs.append(compilation_info.runtime_classpath) + else: + files = [] + for f in dep[DefaultInfo].files.to_list(): + if not f.extension == "jar": + fail("unexpected file type in java_single_jar.deps: %s" % f.path) + files.append(f) + transitive_inputs.append(depset(files)) + inputs = depset(transitive = transitive_inputs) + + if hasattr(java_common, "JavaRuntimeClasspathInfo"): + deploy_env_jars = depset(transitive = [ + dep[java_common.JavaRuntimeClasspathInfo].runtime_classpath + for dep in deploy_env + ]) + excluded_jars = {jar: None for jar in deploy_env_jars.to_list()} + if excluded_jars: + inputs = depset([jar for jar in inputs.to_list() if jar not in excluded_jars]) + return inputs + +def _bazel_java_single_jar_impl(ctx): + inputs = _single_jar_inputs(ctx.attr.deps, ctx.attr.deploy_env) + + args = ctx.actions.args() + args.add_all("--sources", inputs) + args.use_param_file("@%s") + args.set_param_file_format("multiline") + args.add_all("--deploy_manifest_lines", ctx.attr.deploy_manifest_lines) + args.add("--output", ctx.outputs.output) + args.add("--normalize") + + # Deal with limitation of singlejar flags: tool's default behavior is + # "no", but you get that behavior only by absence of compression flags. + if ctx.attr.compress == "preserve": + args.add("--dont_change_compression") + elif ctx.attr.compress == "yes": + args.add("--compression") + elif ctx.attr.compress == "no": + pass + else: + fail("\"compress\" attribute (%s) must be: yes, no, preserve." % ctx.attr.compress) + + if ctx.attr.exclude_build_data: + args.add("--exclude_build_data") + if ctx.attr.multi_release: + args.add("--multi_release") + + if ctx.attr.exclude_pattern: + args.add("--exclude_pattern", ctx.attr.exclude_pattern) + + ctx.actions.run( + inputs = inputs, + outputs = [ctx.outputs.output], + arguments = [args], + progress_message = "Merging into %s" % ctx.outputs.output.short_path, + mnemonic = "JavaSingleJar", + executable = ctx.executable._singlejar, + use_default_shell_env = True, + ) + + files = depset([ctx.outputs.output]) + providers = [DefaultInfo( + files = files, + runfiles = ctx.runfiles(transitive_files = files), + )] + if hasattr(java_common, "JavaRuntimeClasspathInfo"): + providers.append(java_common.JavaRuntimeClasspathInfo(runtime_classpath = inputs)) + return providers + +bazel_java_single_jar = rule( + attrs = { + "deps": attr.label_list( + allow_files = True, + doc = """ + The Java targets (including java_import and java_library) to collect + transitive dependencies from. Runtime dependencies are collected via + deps, exports, and runtime_deps. Resources are also collected. + Native cc_library or java_wrap_cc dependencies are not.""", + ), + "deploy_manifest_lines": attr.string_list(doc = """ + A list of lines to add to the META-INF/manifest.mf file."""), + "deploy_env": attr.label_list( + providers = [java_common.JavaRuntimeClasspathInfo] if hasattr(java_common, "JavaRuntimeClasspathInfo") else [], + allow_files = False, + doc = """ + A list of `java_binary` or `java_single_jar` targets which represent + the deployment environment for this binary. + + Set this attribute when building a plugin which will be loaded by another + `java_binary`. + + `deploy_env` dependencies are excluded from the jar built by this rule.""", + ), + "compress": attr.string(default = "preserve", doc = """ + Whether to always deflate ("yes"), always store ("no"), or pass + through unmodified ("preserve"). The default is "preserve", and is the + most efficient option -- no extra work is done to inflate or deflate."""), + "exclude_build_data": attr.bool(default = True, doc = """ + Whether to omit the build-data.properties file generated + by default."""), + "multi_release": attr.bool(default = True, doc = """Whether to enable Multi-Release output jars."""), + "exclude_pattern": attr.string(default = "", doc = """ + A regex pattern of files to exclude from the jar. + """), + "_singlejar": attr.label( + default = Label("//toolchains:singlejar"), + cfg = "exec", + allow_single_file = True, + executable = True, + ), + "output": attr.output(), + }, + implementation = _bazel_java_single_jar_impl, + doc = """ +Collects Java dependencies and jar files into a single jar + +`java_single_jar` collects Java dependencies and jar files into a single jar. +This is similar to java_binary with everything related to executables disabled, +and provides an alternative to the java_binary "deploy jar hack". + +## Example + +```skylark +load("//tools/build_defs/java_single_jar:java_single_jar.bzl", "java_single_jar") + +java_single_jar( + name = "my_single_jar", + deps = [ + "//java/com/google/foo", + "//java/com/google/bar", + ], +) +``` + +Outputs: + {name}.jar: A single jar containing all of the inputs. +""", +) diff --git a/java/java_single_jar.bzl b/java/java_single_jar.bzl index bfdd21c0..84771614 100644 --- a/java/java_single_jar.bzl +++ b/java/java_single_jar.bzl @@ -1,158 +1,5 @@ -""" Definition of _java_single_jar. """ +"""The java_single_jar rule""" -load("//java/common:java_common.bzl", "java_common") -load("//java/common:java_info.bzl", "JavaInfo") +load("//java/bazel/rules:bazel_java_single_jar.bzl", _java_single_jar = "java_single_jar") -def _single_jar_inputs(deps, deploy_env): - transitive_inputs = [] - for dep in deps: - if JavaInfo in dep: - info = dep[JavaInfo] - transitive_inputs.append(info.transitive_runtime_jars) - if hasattr(info, "compilation_info"): - compilation_info = info.compilation_info - if hasattr(compilation_info, "runtime_classpath"): - transitive_inputs.append(compilation_info.runtime_classpath) - else: - files = [] - for f in dep[DefaultInfo].files.to_list(): - if not f.extension == "jar": - fail("unexpected file type in java_single_jar.deps: %s" % f.path) - files.append(f) - transitive_inputs.append(depset(files)) - inputs = depset(transitive = transitive_inputs) - - if hasattr(java_common, "JavaRuntimeClasspathInfo"): - deploy_env_jars = depset(transitive = [ - dep[java_common.JavaRuntimeClasspathInfo].runtime_classpath - for dep in deploy_env - ]) - excluded_jars = {jar: None for jar in deploy_env_jars.to_list()} - if excluded_jars: - inputs = depset([jar for jar in inputs.to_list() if jar not in excluded_jars]) - return inputs - -def _java_single_jar(ctx): - inputs = _single_jar_inputs(ctx.attr.deps, ctx.attr.deploy_env) - - args = ctx.actions.args() - args.add_all("--sources", inputs) - args.use_param_file("@%s") - args.set_param_file_format("multiline") - args.add_all("--deploy_manifest_lines", ctx.attr.deploy_manifest_lines) - args.add("--output", ctx.outputs.output) - args.add("--normalize") - - # Deal with limitation of singlejar flags: tool's default behavior is - # "no", but you get that behavior only by absence of compression flags. - if ctx.attr.compress == "preserve": - args.add("--dont_change_compression") - elif ctx.attr.compress == "yes": - args.add("--compression") - elif ctx.attr.compress == "no": - pass - else: - fail("\"compress\" attribute (%s) must be: yes, no, preserve." % ctx.attr.compress) - - if ctx.attr.exclude_build_data: - args.add("--exclude_build_data") - if ctx.attr.multi_release: - args.add("--multi_release") - - if ctx.attr.exclude_pattern: - args.add("--exclude_pattern", ctx.attr.exclude_pattern) - - ctx.actions.run( - inputs = inputs, - outputs = [ctx.outputs.output], - arguments = [args], - progress_message = "Merging into %s" % ctx.outputs.output.short_path, - mnemonic = "JavaSingleJar", - executable = ctx.executable._singlejar, - use_default_shell_env = True, - ) - - files = depset([ctx.outputs.output]) - providers = [DefaultInfo( - files = files, - runfiles = ctx.runfiles(transitive_files = files), - )] - if hasattr(java_common, "JavaRuntimeClasspathInfo"): - providers.append(java_common.JavaRuntimeClasspathInfo(runtime_classpath = inputs)) - return providers - -def _init(name, **kwargs): - if "output" not in kwargs: - kwargs["output"] = name + ".jar" - return kwargs - -java_single_jar = rule( - attrs = { - "deps": attr.label_list( - allow_files = True, - doc = """ - The Java targets (including java_import and java_library) to collect - transitive dependencies from. Runtime dependencies are collected via - deps, exports, and runtime_deps. Resources are also collected. - Native cc_library or java_wrap_cc dependencies are not.""", - ), - "deploy_manifest_lines": attr.string_list(doc = """ - A list of lines to add to the META-INF/manifest.mf file."""), - "deploy_env": attr.label_list( - providers = [java_common.JavaRuntimeClasspathInfo] if hasattr(java_common, "JavaRuntimeClasspathInfo") else [], - allow_files = False, - doc = """ - A list of `java_binary` or `java_single_jar` targets which represent - the deployment environment for this binary. - - Set this attribute when building a plugin which will be loaded by another - `java_binary`. - - `deploy_env` dependencies are excluded from the jar built by this rule.""", - ), - "compress": attr.string(default = "preserve", doc = """ - Whether to always deflate ("yes"), always store ("no"), or pass - through unmodified ("preserve"). The default is "preserve", and is the - most efficient option -- no extra work is done to inflate or deflate."""), - "exclude_build_data": attr.bool(default = True, doc = """ - Whether to omit the build-data.properties file generated - by default."""), - "multi_release": attr.bool(default = True, doc = """Whether to enable Multi-Release output jars."""), - "exclude_pattern": attr.string(default = "", doc = """ - A regex pattern of files to exclude from the jar. - """), - "_singlejar": attr.label( - default = Label("//toolchains:singlejar"), - cfg = "exec", - allow_single_file = True, - executable = True, - ), - "output": attr.output(), - }, - initializer = _init, - implementation = _java_single_jar, - doc = """ -Collects Java dependencies and jar files into a single jar - -`java_single_jar` collects Java dependencies and jar files into a single jar. -This is similar to java_binary with everything related to executables disabled, -and provides an alternative to the java_binary "deploy jar hack". - -## Example - -```skylark -load("//tools/build_defs/java_single_jar:java_single_jar.bzl", "java_single_jar") - -java_single_jar( - name = "my_single_jar", - deps = [ - "//java/com/google/foo", - "//java/com/google/bar", - ], -) -``` - -Outputs: - {name}.jar: A single jar containing all of the inputs. -""", -) +java_single_jar = _java_single_jar diff --git a/test/repo/BUILD.bazel b/test/repo/BUILD.bazel index b0fb6122..a251c7b7 100644 --- a/test/repo/BUILD.bazel +++ b/test/repo/BUILD.bazel @@ -1,4 +1,5 @@ load("@rules_java//java:defs.bzl", "java_binary", "java_library", "java_test") # copybara-use-repo-external-label +load("@rules_java//java:java_single_jar.bzl", "java_single_jar") # copybara-use-repo-external-label load("@rules_java//toolchains:default_java_toolchain.bzl", "NONPREBUILT_TOOLCHAIN_CONFIGURATION", "default_java_toolchain") # copybara-use-repo-external-label load("@rules_shell//shell:sh_test.bzl", "sh_test") @@ -27,6 +28,15 @@ java_test( ], ) +java_single_jar( + name = "uber", + testonly = True, + deps = [ + ":MyTest", + ":bin", + ], +) + genrule( name = "MakeVarGenruleTest", outs = ["MakeVarGenruleTestSuccess"], From 7eb8b69c07712d2502b2a78b7fe9f30e3054a422 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 9 Feb 2026 03:04:16 -0800 Subject: [PATCH 376/465] Release `@rules_java` `v9.4.0` PiperOrigin-RevId: 867508885 Change-Id: Id3610cbe51704aa8c23ea8ad6e1feca3f2fdd231 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 7dbbc2ee..4dcb582e 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "9.3.0", + version = "9.4.0", bazel_compatibility = [">=7.0.0"], compatibility_level = 1, ) From f70e12608c04cdf3467b429478439b247095c129 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 9 Feb 2026 05:13:25 -0800 Subject: [PATCH 377/465] Run `@rules_java` extra tests only with the latest Bazel release The tests only exercise internals (such as the release process or configs) and should be independent of the Bazel version. Running them (esp the remote jdk configs tests) with all Bazel versions is wasteful. PiperOrigin-RevId: 867550547 Change-Id: Ic6803c9b00b83381706005aa3e0a6528199fdabb --- .bazelci/presubmit.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 30c63935..411f490c 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -89,10 +89,9 @@ tasks: build_flags: *flags_workspace_integration test_targets: *test_target_integration test_flags: *flags_workspace_integration -# Linux-only tests - linux_only_tests: - name: "Extra tests w/ Bazel {bazel}" - bazel: ${{ bazel }} + # internal tests for configs and release process + internal_tests: + name: "Internal tests" platform: "ubuntu2004" shell_commands: - "git init" From 7e5a90c268d33254cf2b2c0ef651fba754b75efe Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Feb 2026 04:03:07 -0800 Subject: [PATCH 378/465] Fix `bzl_library` graph for `java_single_jar` Also add a `starlark_doc_extract` target as a regression test PiperOrigin-RevId: 868067494 Change-Id: I1d373d9f40a49bb3affea1eb1ec4ce263b610662 --- java/BUILD | 2 +- java/bazel/rules/BUILD.bazel | 16 +++++++++++++++- test/BUILD.bazel | 6 ++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/java/BUILD b/java/BUILD index 7888daba..b613191c 100644 --- a/java/BUILD +++ b/java/BUILD @@ -66,7 +66,7 @@ bzl_library( srcs = ["java_single_jar.bzl"], visibility = ["//visibility:public"], deps = [ - "//java/bazel/rules", # copybara-use-repo-external-label + "//java/bazel/rules:java_single_jar_bzl", # copybara-use-repo-external-label ], ) diff --git a/java/bazel/rules/BUILD.bazel b/java/bazel/rules/BUILD.bazel index e0d79586..108a3f9c 100644 --- a/java/bazel/rules/BUILD.bazel +++ b/java/bazel/rules/BUILD.bazel @@ -23,7 +23,10 @@ filegroup( bzl_library( name = "rules", - srcs = glob(["*.bzl"]), + srcs = glob( + ["*.bzl"], + exclude = ["bazel_java_single_jar.bzl"], + ), visibility = ["//visibility:public"], # for Bazel docgen deps = [ "//java/common:semantics_bzl", @@ -36,6 +39,17 @@ bzl_library( ], ) +bzl_library( + name = "java_single_jar_bzl", + srcs = ["bazel_java_single_jar.bzl"], + visibility = [ + "//java:__pkg__", + ], + deps = [ + "//java/common/rules:java_single_jar_bzl", + ], +) + filegroup( name = "for_bazel_tests", testonly = 1, diff --git a/test/BUILD.bazel b/test/BUILD.bazel index 964c77cb..951280d6 100644 --- a/test/BUILD.bazel +++ b/test/BUILD.bazel @@ -81,3 +81,9 @@ starlark_doc_extract( src = "@compatibility_proxy//:proxy.bzl", deps = ["@compatibility_proxy//:proxy_bzl"], ) + +starlark_doc_extract( + name = "java_single_jar_bzl_graph", + src = "//java:java_single_jar.bzl", + deps = ["//java:java_single_jar"], +) From aade08e392f741cf73b2f6edbde9831b3b0f066b Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Feb 2026 04:11:03 -0800 Subject: [PATCH 379/465] Release `@rules_java` `v9.4.1` PiperOrigin-RevId: 868071534 Change-Id: Idf9d65b24bf1ea7c2a018c4e2c7fe3582c2abea4 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 4dcb582e..a7621b1c 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "9.4.0", + version = "9.4.1", bazel_compatibility = [">=7.0.0"], compatibility_level = 1, ) From aa4075b7ba2057b65f787324c175c0b433dacc43 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Feb 2026 05:46:09 -0800 Subject: [PATCH 380/465] Automated rollback of commit 1824a5548e56ecd337687ff32baf98e37ddd6b16. *** Reason for rollback *** Breaks Bazel tests *** Original change description *** Add `--sun-misc-unsafe-memory-access=allow` to `JavaBuilder`'s jvm flags Fixes https://github.com/bazelbuild/rules_java/issues/348 PiperOrigin-RevId: 868102114 Change-Id: If58378b00718c8ca3a04d2559801c8540c006ad6 --- test/toolchains/BUILD.bazel | 7 ++--- .../default_java_toolchain_tests.bzl | 30 ------------------- toolchains/default_java_toolchain.bzl | 2 -- 3 files changed, 3 insertions(+), 36 deletions(-) delete mode 100644 test/toolchains/default_java_toolchain_tests.bzl diff --git a/test/toolchains/BUILD.bazel b/test/toolchains/BUILD.bazel index 24ae5352..e25b3d8c 100644 --- a/test/toolchains/BUILD.bazel +++ b/test/toolchains/BUILD.bazel @@ -1,8 +1,7 @@ load(":bootclasspath_tests.bzl", "bootclasspath_tests") -load(":default_java_toolchain_tests.bzl", "default_java_toolchain_tests") package(default_applicable_licenses = ["@rules_java//:license"]) -bootclasspath_tests(name = "bootclasspath_tests") - -default_java_toolchain_tests(name = "default_java_toolchain_tests") +bootclasspath_tests( + name = "bootclasspath_tests", +) diff --git a/test/toolchains/default_java_toolchain_tests.bzl b/test/toolchains/default_java_toolchain_tests.bzl deleted file mode 100644 index bdfa400b..00000000 --- a/test/toolchains/default_java_toolchain_tests.bzl +++ /dev/null @@ -1,30 +0,0 @@ -"""Tests for the default java toolchain configuration""" - -load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") -load("@rules_testing//lib:util.bzl", "util") -load("//java:java_library.bzl", "java_library") - -def _test_java_builder_jvm_flags(name): - util.helper_target( - java_library, - name = name + "/lib", - srcs = ["A.java"], - ) - analysis_test( - name = name, - impl = _test_java_builder_jvm_flags_impl, - target = name + "/lib", - ) - -def _test_java_builder_jvm_flags_impl(env, target): - env.expect.that_target(target).action_named("Javac").contains_flag_values([ - ("--sun-misc-unsafe-memory-access", "allow"), - ]) - -def default_java_toolchain_tests(name): - test_suite( - name = name, - tests = [ - _test_java_builder_jvm_flags, - ], - ) diff --git a/toolchains/default_java_toolchain.bzl b/toolchains/default_java_toolchain.bzl index df53468a..f4f83f66 100644 --- a/toolchains/default_java_toolchain.bzl +++ b/toolchains/default_java_toolchain.bzl @@ -103,8 +103,6 @@ _BASE_TOOLCHAIN_CONFIGURATION = dict( # targeting JDK 7. java_runtime = Label("//toolchains:remotejdk_21"), oneversion = Label("//toolchains:one_version"), - # TODO: remove after https://github.com/protocolbuffers/protobuf/issues/20760 is fixed - javabuilder_jvm_opts = ["--sun-misc-unsafe-memory-access=allow"], ) DEFAULT_TOOLCHAIN_CONFIGURATION = _BASE_TOOLCHAIN_CONFIGURATION From 6c9bc7791fedcb87208a3f2bb33818c29fa2553a Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Feb 2026 06:50:23 -0800 Subject: [PATCH 381/465] Fix javacopts expansion We need to perform location expansion first, otherwise `$(location ...)` is treated as a make variable. Actually fixes https://github.com/bazelbuild/rules_java/issues/345 PiperOrigin-RevId: 868123902 Change-Id: I74d38c34f55990d4afc76498567a7740f58aa39e --- java/common/rules/impl/compile_action.bzl | 2 +- test/java/bazel/rules/java_binary_tests.bzl | 21 +++++++++++++++++++++ test/java/testutil/java_info_subject.bzl | 2 +- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/java/common/rules/impl/compile_action.bzl b/java/common/rules/impl/compile_action.bzl index 098c55bb..f553a837 100644 --- a/java/common/rules/impl/compile_action.bzl +++ b/java/common/rules/impl/compile_action.bzl @@ -136,9 +136,9 @@ def compile_action( or resources present, whereas runfiles in this case are empty. """ expanded_javacopts = javacopts + expanded_javacopts = [ctx.expand_location(opt) for opt in expanded_javacopts] if semantics.expand_javacopts_make_variables: expanded_javacopts = [ctx.expand_make_variables("javacopts", opt, {}) for opt in expanded_javacopts] - expanded_javacopts = [ctx.expand_location(opt) for opt in expanded_javacopts] java_info = _compile_private_for_builtins( ctx, output = output_class_jar, diff --git a/test/java/bazel/rules/java_binary_tests.bzl b/test/java/bazel/rules/java_binary_tests.bzl index 2d015b67..737acea9 100644 --- a/test/java/bazel/rules/java_binary_tests.bzl +++ b/test/java/bazel/rules/java_binary_tests.bzl @@ -77,11 +77,32 @@ def _test_java_binary_javacopts_make_variable_expansion_impl(env, target): assert_java_info.compilation_info().javac_options().not_contains("$(MY_CUSTOM_OPT)") assert_java_info.compilation_info().javac_options().contains("MY_OPT_VALUE") +def _test_java_binary_javacopts_location_expansion(name): + util.helper_target( + java_binary, + name = name + "/bin", + srcs = ["A.java"], + javacopts = ["-XepOpt:foo=$(location :A.java)"], + ) + + analysis_test( + name = name, + impl = _test_java_binary_javacopts_location_expansion_impl, + target = name + "/bin", + ) + +def _test_java_binary_javacopts_location_expansion_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + assert_java_info.compilation_info().javac_options().contains( + "-XepOpt:foo={package}/A.java", + ) + def java_binary_tests(name): test_suite( name = name, tests = [ _test_java_binary_cross_compilation_to_unix, _test_java_binary_javacopts_make_variable_expansion, + _test_java_binary_javacopts_location_expansion, ], ) diff --git a/test/java/testutil/java_info_subject.bzl b/test/java/testutil/java_info_subject.bzl index e9242436..e0ec8059 100644 --- a/test/java/testutil/java_info_subject.bzl +++ b/test/java/testutil/java_info_subject.bzl @@ -58,7 +58,7 @@ def _new_java_compilation_info_subject(java_info, meta): compilation_classpath = lambda: subjects.depset_file(self.actual.compilation_classpath, self.meta.derive("compilation_classpath")), runtime_classpath = lambda: subjects.depset_file(self.actual.runtime_classpath, self.meta.derive("runtime_classpath")), runtime_classpath_list = lambda: subjects.collection(self.actual.runtime_classpath.to_list(), self.meta.derive("runtime_classpath.to_list()"), format = True), - javac_options = lambda: subjects.collection(helper.tokenize_javacopts(opts = self.actual.javac_options), self.meta.derive("javac_options")), + javac_options = lambda: subjects.collection(helper.tokenize_javacopts(opts = self.actual.javac_options), self.meta.derive("javac_options"), format = True), ) return public From 4beb813a365a97701d4dd4e56efced1b47eac3e3 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Feb 2026 06:59:47 -0800 Subject: [PATCH 382/465] Release `rules_java` `v9.4.2` PiperOrigin-RevId: 868127673 Change-Id: Id112970e9fb5a5a882d77a96ad179592eb901df3 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index a7621b1c..e4e88698 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "9.4.1", + version = "9.4.2", bazel_compatibility = [">=7.0.0"], compatibility_level = 1, ) From 06662838f1ecc7a9653b16e40f9541e729fe06d7 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Feb 2026 08:31:37 -0800 Subject: [PATCH 383/465] Update `java_tools` to `v19.0` For changes from https://github.com/bazelbuild/bazel/pull/28340 PiperOrigin-RevId: 868161177 Change-Id: I96fe102432d7c45ccf463eb32b07a70534785986 --- MODULE.bazel | 1 + java/repositories.bzl | 39 ++++++++++++++++++++------------------- java/rules_java_deps.bzl | 12 ++++++++++++ 3 files changed, 33 insertions(+), 19 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index e4e88698..fc847b0b 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -22,6 +22,7 @@ bazel_dep(name = "zlib", version = "1.3.1.bcr.5") # Required by @remote_java_tools, which is loaded via module extension. bazel_dep(name = "rules_license", version = "0.0.3") bazel_dep(name = "abseil-cpp", version = "20250814.1", repo_name = "com_google_absl") +bazel_dep(name = "re2", version = "2025-11-05.bcr.1") single_version_override( module_name = "protobuf", diff --git a/java/repositories.bzl b/java/repositories.bzl index 5a290b4d..df95f86d 100644 --- a/java/repositories.bzl +++ b/java/repositories.bzl @@ -22,38 +22,39 @@ load("//toolchains:remote_java_repository.bzl", "remote_java_repository") # visible for tests JAVA_TOOLS_CONFIG = { - "version": "v18.1", + "version": "v19.0", + "source_revision": "61972bfd7fb6f587fc4576b5114e20758b501806", "release": "true", "artifacts": { "java_tools_linux": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.1/java_tools_linux-v18.1.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.1/java_tools_linux-v18.1.zip", - "sha": "e22cbb2600249576c6a0a02af3f78e26537a89b6be11ef3826c01f9019faaa61", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v19.0/java_tools_linux-v19.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v19.0/java_tools_linux-v19.0.zip", + "sha": "7d5b0c01f99ea5596b7901a7e5f9173f3ae3c4f0b480378e87567eaf97d75d25", }, "java_tools_linux_aarch64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.1/java_tools_linux_aarch64-v18.1.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.1/java_tools_linux_aarch64-v18.1.zip", - "sha": "4f75420bafb8c6554105c90ed05db3d7ff5942dbc1633459c20d2dcc06eff6ac", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v19.0/java_tools_linux_aarch64-v19.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v19.0/java_tools_linux_aarch64-v19.0.zip", + "sha": "34b14fdfe8d6e32ed7f80e7c4d34ce79f4006e0d4b621552f507e51b9d6a3d7d", }, "java_tools_windows": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.1/java_tools_windows-v18.1.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.1/java_tools_windows-v18.1.zip", - "sha": "fe6dccef1b290b9e2a539cecfd57d924f719480ac04e55d03fdca5533272cd04", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v19.0/java_tools_windows-v19.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v19.0/java_tools_windows-v19.0.zip", + "sha": "86c5a58ccefdb9e704fddd325f5fbc7867b2cdd128fb8b9abfdf607a75d2ae71", }, "java_tools_darwin_x86_64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.1/java_tools_darwin_x86_64-v18.1.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.1/java_tools_darwin_x86_64-v18.1.zip", - "sha": "68f6b540a28ff1d98acd9313900c50560d52022ee2399627b9c92b1bb2c5d466", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v19.0/java_tools_darwin_x86_64-v19.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v19.0/java_tools_darwin_x86_64-v19.0.zip", + "sha": "78ff8ec7038ab5f9cd261cdf9ff75ea0eb2af7579f9aeef9d658459ee37fabac", }, "java_tools_darwin_arm64": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.1/java_tools_darwin_arm64-v18.1.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.1/java_tools_darwin_arm64-v18.1.zip", - "sha": "07026303be4662462733d00eaf8e956cd9589493e104934862f0b53e76758d88", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v19.0/java_tools_darwin_arm64-v19.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v19.0/java_tools_darwin_arm64-v19.0.zip", + "sha": "86f15280dd0ce121a22f061e2e301ecf746597caa4938cf56852b3d311b830d8", }, "java_tools": { - "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v18.1/java_tools-v18.1.zip", - "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v18.1/java_tools-v18.1.zip", - "sha": "27cab59ba5ff8ee7cf3071971fe2587a295daefe82531f27b4f061111276163d", + "mirror_url": "https://mirror.bazel.build/bazel_java_tools/releases/java/v19.0/java_tools-v19.0.zip", + "github_url": "https://github.com/bazelbuild/java_tools/releases/download/java_v19.0/java_tools-v19.0.zip", + "sha": "d21d4aad1a18062512bcf4e8f7a09a4f5a042c760daa779e0ddda6e41b170507", }, }, } diff --git a/java/rules_java_deps.bzl b/java/rules_java_deps.bzl index 1eb28492..b2086dc1 100644 --- a/java/rules_java_deps.bzl +++ b/java/rules_java_deps.bzl @@ -209,6 +209,17 @@ def rules_license_repo(): ], ) +def re2_repo(): + maybe( + http_archive, + name = "re2", + sha256 = "5bb6875ae1cd1e9fedde98018c346db7260655f86fdb8837e3075103acd3649b", + strip_prefix = "re2-2023-09-01", + urls = [ + "https://github.com/google/re2/releases/download/2023-09-01/re2-2023-09-01.tar.gz", + ], + ) + def rules_java_dependencies(): """An utility method to load non-toolchain dependencies of rules_java. @@ -222,3 +233,4 @@ def rules_java_dependencies(): zlib_repo() absl_repo() rules_license_repo() + re2_repo() From 14642c5529672185b07fe0a1104c62dee2a7a292 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Feb 2026 08:45:43 -0800 Subject: [PATCH 384/465] Release `rules_java` `v9.5.0` PiperOrigin-RevId: 868166803 Change-Id: I4438f95a6906264a19b5b6063376f77141e35d68 --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index fc847b0b..70e975f3 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "9.4.2", + version = "9.5.0", bazel_compatibility = [">=7.0.0"], compatibility_level = 1, ) From 2039d00740729ecc91aea49da2853315263397cb Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 11 Feb 2026 02:17:26 -0800 Subject: [PATCH 385/465] Remove handling for empty java_imports jars PiperOrigin-RevId: 868566387 Change-Id: I30797623e04eda8d7849d059655b9b036aac0d42 --- .../rules/impl/bazel_java_import_impl.bzl | 57 ++++++------------- 1 file changed, 16 insertions(+), 41 deletions(-) diff --git a/java/common/rules/impl/bazel_java_import_impl.bzl b/java/common/rules/impl/bazel_java_import_impl.bzl index 7ca9cf7d..2a107a1e 100644 --- a/java/common/rules/impl/bazel_java_import_impl.bzl +++ b/java/common/rules/impl/bazel_java_import_impl.bzl @@ -74,26 +74,6 @@ def _check_empty_jars_error(ctx, jars): if len(jars) == 0: fail("empty java_import.jars is not supported " + ctx.label.package) -def _create_java_info_with_dummy_output_file(ctx, srcjar, all_deps, exports, runtime_deps_list, neverlink, cc_info_list, add_exports, add_opens): - dummy_jar = ctx.actions.declare_file(ctx.label.name + "_dummy.jar") - dummy_src_jar = srcjar - if dummy_src_jar == None: - dummy_src_jar = ctx.actions.declare_file(ctx.label.name + "_src_dummy.java") - ctx.actions.write(dummy_src_jar, "") - return java_common.compile( - ctx, - output = dummy_jar, - java_toolchain = semantics.find_java_toolchain(ctx), - source_files = [dummy_src_jar], - deps = all_deps, - runtime_deps = runtime_deps_list, - neverlink = neverlink, - exports = [export[JavaInfo] for export in exports if JavaInfo in export], # Watchout, maybe you need to add them there manually. - native_libraries = cc_info_list, - add_exports = add_exports, - add_opens = add_opens, - ) - def bazel_java_import_rule( ctx, jars = [], @@ -135,7 +115,7 @@ def bazel_java_import_rule( jdeps_artifact = None merged_java_info = java_common.merge(all_deps) not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_deps_checking") and not ctx.attr._allowlist_java_import_deps_checking[PackageSpecificationInfo].contains(ctx.label) - if len(collected_jars) > 0 and not_in_allowlist and "incomplete-deps" not in ctx.attr.tags: + if not_in_allowlist and "incomplete-deps" not in ctx.attr.tags: jdeps_artifact = import_deps_check( ctx, collected_jars, @@ -147,26 +127,21 @@ def bazel_java_import_rule( compilation_to_runtime_jar_map = _process_with_ijars_if_needed(collected_jars, ctx) runtime_deps_list = [runtime_dep[JavaInfo] for runtime_dep in runtime_deps if JavaInfo in runtime_dep] cc_info_list = [dep[CcInfo] for dep in deps if CcInfo in dep] - java_info = None - if len(collected_jars) > 0: - java_infos = [] - for jar in collected_jars: - java_infos.append(JavaInfo( - output_jar = jar, - compile_jar = compilation_to_runtime_jar_map[jar], - deps = all_deps, - runtime_deps = runtime_deps_list, - neverlink = neverlink, - source_jar = srcjar, - exports = [export[JavaInfo] for export in exports if JavaInfo in export], # Watchout, maybe you need to add them there manually. - native_libraries = cc_info_list, - add_exports = add_exports, - add_opens = add_opens, - )) - java_info = java_common.merge(java_infos) - else: - # TODO(kotlaja): Remove next line once all java_import targets with empty jars attribute are cleaned from depot (b/246559727). - java_info = _create_java_info_with_dummy_output_file(ctx, srcjar, all_deps, exports, runtime_deps_list, neverlink, cc_info_list, add_exports, add_opens) + java_infos = [] + for jar in collected_jars: + java_infos.append(JavaInfo( + output_jar = jar, + compile_jar = compilation_to_runtime_jar_map[jar], + deps = all_deps, + runtime_deps = runtime_deps_list, + neverlink = neverlink, + source_jar = srcjar, + exports = [export[JavaInfo] for export in exports if JavaInfo in export], # Watchout, maybe you need to add them there manually. + native_libraries = cc_info_list, + add_exports = add_exports, + add_opens = add_opens, + )) + java_info = java_common.merge(java_infos) target = {"JavaInfo": java_info} From 10e179c4175c8aad26ff0b8378644fa041bb17c4 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 11 Feb 2026 02:37:42 -0800 Subject: [PATCH 386/465] Adds a test for compilation_outputs output group to java_binary_tests.bzl PiperOrigin-RevId: 868573491 Change-Id: I2188753f333db240945ff2b7e250adf8f07fe2a9 --- test/java/common/rules/java_binary_tests.bzl | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/test/java/common/rules/java_binary_tests.bzl b/test/java/common/rules/java_binary_tests.bzl index 97a85713..9ddadbd9 100644 --- a/test/java/common/rules/java_binary_tests.bzl +++ b/test/java/common/rules/java_binary_tests.bzl @@ -167,6 +167,33 @@ def _test_java_binary_propagates_direct_native_libraries_impl(env, target): matching.str_matches("-Djava.library.path=${JAVA_RUNFILES}/*/test_java_binary_propagates_direct_native_libraries"), ) +def _test_java_compile_only(name): + util.helper_target( + java_library, + name = name + "/hello_library", + srcs = ["HelloLibrary.java"], + ) + util.helper_target( + java_binary, + name = name + "/main", + srcs = ["Main.java"], + main_class = "main.Main", + deps = [name + "/hello_library"], + ) + + analysis_test( + name = name, + impl = _test_java_compile_only_impl, + target = name + "/main", + ) + +def _test_java_compile_only_impl(env, target): + # Assert that the compilation output is exactly main jar, and does not contain a variant of + # hello_library.jar. + env.expect.that_target(target).output_group( + "compilation_outputs", + ).contains_exactly(["{package}/{name}.jar"]) + def java_binary_tests(name): test_suite( name = name, @@ -175,5 +202,6 @@ def java_binary_tests(name): _test_stamp_conversion_does_not_override_int, _test_java_binary_attributes, _test_java_binary_propagates_direct_native_libraries, + _test_java_compile_only, ], ) From 42139be27a212989a3b67626e27904ca55602788 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 11 Feb 2026 08:50:44 -0800 Subject: [PATCH 387/465] Remove `add_exports` and `add_opens` parameters from `java_common.compile` PiperOrigin-RevId: 868699430 Change-Id: I10351f8187e4ff0966123e00a99cb6599f8a45ce --- java/private/java_common.bzl | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/java/private/java_common.bzl b/java/private/java_common.bzl index 8a465c26..3c11c0e8 100644 --- a/java/private/java_common.bzl +++ b/java/private/java_common.bzl @@ -65,9 +65,7 @@ def _compile( sourcepath = [], resources = [], neverlink = False, - enable_annotation_processing = True, - add_exports = [], - add_opens = []): + enable_annotation_processing = True): return _compile_internal( ctx, output = output, @@ -90,8 +88,6 @@ def _compile( resources = resources, neverlink = neverlink, enable_annotation_processing = enable_annotation_processing, - add_exports = add_exports, - add_opens = add_opens, ) def _run_ijar(actions, jar, java_toolchain, target_label = None): From 1cd7671a230ab703d7ed108998bda90ccc9a10d4 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 12 Feb 2026 03:14:31 -0800 Subject: [PATCH 388/465] Creates a first simple test for java_runtime() in java_runtime_tests.bzl PiperOrigin-RevId: 869124095 Change-Id: Ia9753cdd40d6547dab01a726a30f2fb7459a0b10 --- test/java/common/rules/BUILD | 3 ++ test/java/common/rules/java_runtime_tests.bzl | 41 +++++++++++++++++++ .../testutil/java_runtime_info_subject.bzl | 1 + 3 files changed, 45 insertions(+) create mode 100644 test/java/common/rules/java_runtime_tests.bzl diff --git a/test/java/common/rules/BUILD b/test/java/common/rules/BUILD index 2311a3f2..8a00159d 100644 --- a/test/java/common/rules/BUILD +++ b/test/java/common/rules/BUILD @@ -2,6 +2,7 @@ load(":java_binary_tests.bzl", "java_binary_tests") load(":java_import_tests.bzl", "java_import_tests") load(":java_library_tests.bzl", "java_library_tests") load(":java_plugin_tests.bzl", "java_plugin_tests") +load(":java_runtime_tests.bzl", "java_runtime_tests") load(":java_test_tests.bzl", "java_test_tests") load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") @@ -17,4 +18,6 @@ java_library_tests(name = "java_library_tests") java_import_tests(name = "java_import_tests") +java_runtime_tests(name = "java_runtime_tests") + java_test_tests(name = "java_test_tests") diff --git a/test/java/common/rules/java_runtime_tests.bzl b/test/java/common/rules/java_runtime_tests.bzl new file mode 100644 index 00000000..948f0c3b --- /dev/null +++ b/test/java/common/rules/java_runtime_tests.bzl @@ -0,0 +1,41 @@ +"""Tests for the java_runtime rule""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java/toolchains:java_runtime.bzl", "java_runtime") +load("//test/java/testutil:java_runtime_info_subject.bzl", "java_runtime_info_subject") + +def _test_java_runtime_simple(name): + util.helper_target( + java_runtime, + name = name + "/jvm-foo", + srcs = [ + "foo/a", + "foo/b", + ], + java_home = "foo", + ) + + analysis_test( + name = name, + impl = _test_java_runtime_simple_impl, + target = name + "/jvm-foo", + ) + +def _test_java_runtime_simple_impl(env, target): + java_runtime_info_subject.from_target(env, target).files().contains_exactly([ + "{package}/foo/a", + "{package}/foo/b", + ]) + env.expect.that_target(target).data_runfiles().contains_exactly([ + "{workspace}/{package}/foo/a", + "{workspace}/{package}/foo/b", + ]) + +def java_runtime_tests(name): + test_suite( + name = name, + tests = [ + _test_java_runtime_simple, + ], + ) diff --git a/test/java/testutil/java_runtime_info_subject.bzl b/test/java/testutil/java_runtime_info_subject.bzl index ef5bdf92..37a477eb 100644 --- a/test/java/testutil/java_runtime_info_subject.bzl +++ b/test/java/testutil/java_runtime_info_subject.bzl @@ -14,6 +14,7 @@ def _new_java_runtime_info_subject(java_runtime_info, meta): java_home_runfiles_path = lambda: _new_path_string_subject(self.actual.java_home_runfiles_path, self.meta.derive("java_home_runfiles_path")), java_executable_exec_path = lambda: _new_path_string_subject(self.actual.java_executable_exec_path, self.meta.derive("java_executable_exec_path")), java_executable_runfiles_path = lambda: _new_path_string_subject(self.actual.java_executable_runfiles_path, self.meta.derive("java_executable_runfiles_path")), + files = lambda: subjects.depset_file(self.actual.files, self.meta.derive("files")), ) return public From 4b00962ef9ec1646de06629d1b7940f4d94f945a Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 12 Feb 2026 04:19:22 -0800 Subject: [PATCH 389/465] Creates _test_absolute_java_home_with_srcs for java_runtime() in java_runtime_tests.bzl PiperOrigin-RevId: 869144439 Change-Id: Iceebb816a7717371bf23e3f99e3c1d607254993a --- test/java/common/rules/java_runtime_tests.bzl | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/test/java/common/rules/java_runtime_tests.bzl b/test/java/common/rules/java_runtime_tests.bzl index 948f0c3b..deaa1d49 100644 --- a/test/java/common/rules/java_runtime_tests.bzl +++ b/test/java/common/rules/java_runtime_tests.bzl @@ -1,6 +1,7 @@ """Tests for the java_runtime rule""" load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java/toolchains:java_runtime.bzl", "java_runtime") load("//test/java/testutil:java_runtime_info_subject.bzl", "java_runtime_info_subject") @@ -32,10 +33,31 @@ def _test_java_runtime_simple_impl(env, target): "{workspace}/{package}/foo/b", ]) +def _test_absolute_java_home_with_srcs(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + srcs = ["dummy.txt"], + java_home = "/absolute/path", + ) + + analysis_test( + name = name, + impl = _test_absolute_java_home_with_srcs_impl, + target = name + "/jvm", + expect_failure = True, + ) + +def _test_absolute_java_home_with_srcs_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("'java_home' with an absolute path requires 'srcs' to be empty."), + ) + def java_runtime_tests(name): test_suite( name = name, tests = [ _test_java_runtime_simple, + _test_absolute_java_home_with_srcs, ], ) From 5450a510bb236d7d618e2f026415a7ce6ca4d321 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 12 Feb 2026 05:05:00 -0800 Subject: [PATCH 390/465] Creates _test_absolute_java_home_with_java for java_runtime() in java_runtime_tests.bzl PiperOrigin-RevId: 869158248 Change-Id: I26ecc40f891cb6dcb0a8443aa94975a52054afe7 --- test/java/common/rules/java_runtime_tests.bzl | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/test/java/common/rules/java_runtime_tests.bzl b/test/java/common/rules/java_runtime_tests.bzl index deaa1d49..12c24022 100644 --- a/test/java/common/rules/java_runtime_tests.bzl +++ b/test/java/common/rules/java_runtime_tests.bzl @@ -53,11 +53,32 @@ def _test_absolute_java_home_with_srcs_impl(env, target): matching.str_matches("'java_home' with an absolute path requires 'srcs' to be empty."), ) +def _test_absolute_java_home_with_java(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + java = "bin/java", + java_home = "/absolute/path", + ) + + analysis_test( + name = name, + impl = _test_absolute_java_home_with_java_impl, + target = name + "/jvm", + expect_failure = True, + ) + +def _test_absolute_java_home_with_java_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("'java_home' with an absolute path requires 'java' to be empty."), + ) + def java_runtime_tests(name): test_suite( name = name, tests = [ _test_java_runtime_simple, _test_absolute_java_home_with_srcs, + _test_absolute_java_home_with_java, ], ) From 2d0ba3d072bbf6e81f893cdb7a4d3aa15623a9dc Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 12 Feb 2026 05:27:12 -0800 Subject: [PATCH 391/465] Creates _test_bin_java_path_name for java_runtime() in java_runtime_tests.bzl PiperOrigin-RevId: 869165526 Change-Id: Ia89c8e0dd671678e1b687cbb6b349bef02971415 --- test/java/common/rules/java_runtime_tests.bzl | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/test/java/common/rules/java_runtime_tests.bzl b/test/java/common/rules/java_runtime_tests.bzl index 12c24022..94659dd4 100644 --- a/test/java/common/rules/java_runtime_tests.bzl +++ b/test/java/common/rules/java_runtime_tests.bzl @@ -73,6 +73,25 @@ def _test_absolute_java_home_with_java_impl(env, target): matching.str_matches("'java_home' with an absolute path requires 'java' to be empty."), ) +def _test_bin_java_path_name(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + java = "java", + ) + + analysis_test( + name = name, + impl = _test_bin_java_path_name_impl, + target = name + "/jvm", + expect_failure = True, + ) + +def _test_bin_java_path_name_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("the path to 'java' must end in 'bin/java'."), + ) + def java_runtime_tests(name): test_suite( name = name, @@ -80,5 +99,6 @@ def java_runtime_tests(name): _test_java_runtime_simple, _test_absolute_java_home_with_srcs, _test_absolute_java_home_with_java, + _test_bin_java_path_name, ], ) From 281421633bdd3fbcc31e5ce8acd7394371e48ee8 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 12 Feb 2026 05:55:25 -0800 Subject: [PATCH 392/465] Creates _test_absolute_java_home for java_runtime() in java_runtime_tests.bzl PiperOrigin-RevId: 869173032 Change-Id: Icdfe10c4f5c01dd6b021bcd3f5da03b2032d78da --- test/java/common/rules/java_runtime_tests.bzl | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/test/java/common/rules/java_runtime_tests.bzl b/test/java/common/rules/java_runtime_tests.bzl index 94659dd4..2a2e7545 100644 --- a/test/java/common/rules/java_runtime_tests.bzl +++ b/test/java/common/rules/java_runtime_tests.bzl @@ -92,6 +92,22 @@ def _test_bin_java_path_name_impl(env, target): matching.str_matches("the path to 'java' must end in 'bin/java'."), ) +def _test_absolute_java_home(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + java_home = "/absolute/path", + ) + + analysis_test( + name = name, + impl = _test_absolute_java_home_impl, + target = name + "/jvm", + ) + +def _test_absolute_java_home_impl(env, target): + java_runtime_info_subject.from_target(env, target).java_home().equals("/absolute/path") + def java_runtime_tests(name): test_suite( name = name, @@ -100,5 +116,6 @@ def java_runtime_tests(name): _test_absolute_java_home_with_srcs, _test_absolute_java_home_with_java, _test_bin_java_path_name, + _test_absolute_java_home, ], ) From 55d2f9a04464ecda289eb0af5ab3d09f25bf5d12 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 12 Feb 2026 06:20:36 -0800 Subject: [PATCH 393/465] Creates _test_relative_java_home for java_runtime() in java_runtime_tests.bzl PiperOrigin-RevId: 869182739 Change-Id: I70bf1e5f83ad908280479938d3c25d45f914220f --- test/java/common/rules/java_runtime_tests.bzl | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/test/java/common/rules/java_runtime_tests.bzl b/test/java/common/rules/java_runtime_tests.bzl index 2a2e7545..e23cdf66 100644 --- a/test/java/common/rules/java_runtime_tests.bzl +++ b/test/java/common/rules/java_runtime_tests.bzl @@ -108,6 +108,22 @@ def _test_absolute_java_home(name): def _test_absolute_java_home_impl(env, target): java_runtime_info_subject.from_target(env, target).java_home().equals("/absolute/path") +def _test_relative_java_home(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + java_home = "b/c", + ) + + analysis_test( + name = name, + impl = _test_relative_java_home_impl, + target = name + "/jvm", + ) + +def _test_relative_java_home_impl(env, target): + java_runtime_info_subject.from_target(env, target).java_home().equals("{package}/b/c") + def java_runtime_tests(name): test_suite( name = name, @@ -117,5 +133,6 @@ def java_runtime_tests(name): _test_absolute_java_home_with_java, _test_bin_java_path_name, _test_absolute_java_home, + _test_relative_java_home, ], ) From db9b3616d5ce80e5cce7f61ff6c2e6196133a676 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 13 Feb 2026 07:10:08 -0800 Subject: [PATCH 394/465] Creates _test_runtime_alias for java_runtime() in toolchains/java_runtime_tests.bzl PiperOrigin-RevId: 869716975 Change-Id: Ifab9e3a643c66d5815d19c5330ee809ff3ec3e2a --- test/java/toolchains/java_runtime_tests.bzl | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/test/java/toolchains/java_runtime_tests.bzl b/test/java/toolchains/java_runtime_tests.bzl index f5014966..2cc617bf 100644 --- a/test/java/toolchains/java_runtime_tests.bzl +++ b/test/java/toolchains/java_runtime_tests.bzl @@ -135,6 +135,22 @@ def _test_with_generated_java_executable_impl(env, target): assert_info.java_executable_exec_path().starts_with("{bindir}/{package}/foo/bar/bin/java") assert_info.java_executable_runfiles_path().starts_with("{package}/foo/bar/bin/java") +def _test_runtime_alias(name): + util.helper_target( + java_runtime_alias, + name = name + "/alias", + ) + + analysis_test( + name = name, + impl = _test_runtime_alias_impl, + target = name + "/alias", + ) + +def _test_runtime_alias_impl(env, target): + env.expect.that_target(target).has_provider(platform_common.ToolchainInfo) + env.expect.that_target(target).has_provider(platform_common.TemplateVariableInfo) + def java_runtime_tests(name): test_suite( name = name, @@ -142,5 +158,6 @@ def java_runtime_tests(name): _test_with_absolute_java_home, _test_with_hermetic_java_home, _test_with_generated_java_executable, + _test_runtime_alias, ], ) From de9e229c24bd52b61cf98a1bb37b459faf668961 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 13 Feb 2026 07:31:25 -0800 Subject: [PATCH 395/465] Creates _test_runtime_alias for java_runtime() in rules/java_runtime_tests.bzl PiperOrigin-RevId: 869724124 Change-Id: Iaf93555211c88b4a4d94a51abee0c7eec8e83630 --- test/java/common/rules/java_runtime_tests.bzl | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/test/java/common/rules/java_runtime_tests.bzl b/test/java/common/rules/java_runtime_tests.bzl index e23cdf66..454aa9cd 100644 --- a/test/java/common/rules/java_runtime_tests.bzl +++ b/test/java/common/rules/java_runtime_tests.bzl @@ -124,6 +124,25 @@ def _test_relative_java_home(name): def _test_relative_java_home_impl(env, target): java_runtime_info_subject.from_target(env, target).java_home().equals("{package}/b/c") +def _test_java_home_with_invalid_make_variables(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + java_home = "/opt/$(WTF)", + ) + + analysis_test( + name = name, + impl = _test_java_home_with_invalid_make_variables_impl, + target = name + "/jvm", + expect_failure = True, + ) + +def _test_java_home_with_invalid_make_variables_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("$(WTF) not defined"), + ) + def java_runtime_tests(name): test_suite( name = name, @@ -134,5 +153,6 @@ def java_runtime_tests(name): _test_bin_java_path_name, _test_absolute_java_home, _test_relative_java_home, + _test_java_home_with_invalid_make_variables, ], ) From eaf868ea2ad1177836ff1178f03408f6371a27a2 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 16 Feb 2026 00:50:06 -0800 Subject: [PATCH 396/465] Move java_runtime tests to the toolchains directory. The tests for the `java_runtime` rule are now located in `test/java/toolchains/java_runtime_tests.bzl`, aligning with the location of the `java_runtime` rule itself. PiperOrigin-RevId: 870739029 Change-Id: I56d58653eb9e9b8ed700adad7a9fce7750ae1645 --- test/java/common/rules/BUILD | 3 - test/java/common/rules/java_runtime_tests.bzl | 158 ------------------ test/java/toolchains/java_runtime_tests.bzl | 145 ++++++++++++++++ 3 files changed, 145 insertions(+), 161 deletions(-) delete mode 100644 test/java/common/rules/java_runtime_tests.bzl diff --git a/test/java/common/rules/BUILD b/test/java/common/rules/BUILD index 8a00159d..2311a3f2 100644 --- a/test/java/common/rules/BUILD +++ b/test/java/common/rules/BUILD @@ -2,7 +2,6 @@ load(":java_binary_tests.bzl", "java_binary_tests") load(":java_import_tests.bzl", "java_import_tests") load(":java_library_tests.bzl", "java_library_tests") load(":java_plugin_tests.bzl", "java_plugin_tests") -load(":java_runtime_tests.bzl", "java_runtime_tests") load(":java_test_tests.bzl", "java_test_tests") load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") @@ -18,6 +17,4 @@ java_library_tests(name = "java_library_tests") java_import_tests(name = "java_import_tests") -java_runtime_tests(name = "java_runtime_tests") - java_test_tests(name = "java_test_tests") diff --git a/test/java/common/rules/java_runtime_tests.bzl b/test/java/common/rules/java_runtime_tests.bzl deleted file mode 100644 index 454aa9cd..00000000 --- a/test/java/common/rules/java_runtime_tests.bzl +++ /dev/null @@ -1,158 +0,0 @@ -"""Tests for the java_runtime rule""" - -load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") -load("@rules_testing//lib:truth.bzl", "matching") -load("@rules_testing//lib:util.bzl", "util") -load("//java/toolchains:java_runtime.bzl", "java_runtime") -load("//test/java/testutil:java_runtime_info_subject.bzl", "java_runtime_info_subject") - -def _test_java_runtime_simple(name): - util.helper_target( - java_runtime, - name = name + "/jvm-foo", - srcs = [ - "foo/a", - "foo/b", - ], - java_home = "foo", - ) - - analysis_test( - name = name, - impl = _test_java_runtime_simple_impl, - target = name + "/jvm-foo", - ) - -def _test_java_runtime_simple_impl(env, target): - java_runtime_info_subject.from_target(env, target).files().contains_exactly([ - "{package}/foo/a", - "{package}/foo/b", - ]) - env.expect.that_target(target).data_runfiles().contains_exactly([ - "{workspace}/{package}/foo/a", - "{workspace}/{package}/foo/b", - ]) - -def _test_absolute_java_home_with_srcs(name): - util.helper_target( - java_runtime, - name = name + "/jvm", - srcs = ["dummy.txt"], - java_home = "/absolute/path", - ) - - analysis_test( - name = name, - impl = _test_absolute_java_home_with_srcs_impl, - target = name + "/jvm", - expect_failure = True, - ) - -def _test_absolute_java_home_with_srcs_impl(env, target): - env.expect.that_target(target).failures().contains_predicate( - matching.str_matches("'java_home' with an absolute path requires 'srcs' to be empty."), - ) - -def _test_absolute_java_home_with_java(name): - util.helper_target( - java_runtime, - name = name + "/jvm", - java = "bin/java", - java_home = "/absolute/path", - ) - - analysis_test( - name = name, - impl = _test_absolute_java_home_with_java_impl, - target = name + "/jvm", - expect_failure = True, - ) - -def _test_absolute_java_home_with_java_impl(env, target): - env.expect.that_target(target).failures().contains_predicate( - matching.str_matches("'java_home' with an absolute path requires 'java' to be empty."), - ) - -def _test_bin_java_path_name(name): - util.helper_target( - java_runtime, - name = name + "/jvm", - java = "java", - ) - - analysis_test( - name = name, - impl = _test_bin_java_path_name_impl, - target = name + "/jvm", - expect_failure = True, - ) - -def _test_bin_java_path_name_impl(env, target): - env.expect.that_target(target).failures().contains_predicate( - matching.str_matches("the path to 'java' must end in 'bin/java'."), - ) - -def _test_absolute_java_home(name): - util.helper_target( - java_runtime, - name = name + "/jvm", - java_home = "/absolute/path", - ) - - analysis_test( - name = name, - impl = _test_absolute_java_home_impl, - target = name + "/jvm", - ) - -def _test_absolute_java_home_impl(env, target): - java_runtime_info_subject.from_target(env, target).java_home().equals("/absolute/path") - -def _test_relative_java_home(name): - util.helper_target( - java_runtime, - name = name + "/jvm", - java_home = "b/c", - ) - - analysis_test( - name = name, - impl = _test_relative_java_home_impl, - target = name + "/jvm", - ) - -def _test_relative_java_home_impl(env, target): - java_runtime_info_subject.from_target(env, target).java_home().equals("{package}/b/c") - -def _test_java_home_with_invalid_make_variables(name): - util.helper_target( - java_runtime, - name = name + "/jvm", - java_home = "/opt/$(WTF)", - ) - - analysis_test( - name = name, - impl = _test_java_home_with_invalid_make_variables_impl, - target = name + "/jvm", - expect_failure = True, - ) - -def _test_java_home_with_invalid_make_variables_impl(env, target): - env.expect.that_target(target).failures().contains_predicate( - matching.str_matches("$(WTF) not defined"), - ) - -def java_runtime_tests(name): - test_suite( - name = name, - tests = [ - _test_java_runtime_simple, - _test_absolute_java_home_with_srcs, - _test_absolute_java_home_with_java, - _test_bin_java_path_name, - _test_absolute_java_home, - _test_relative_java_home, - _test_java_home_with_invalid_make_variables, - ], - ) diff --git a/test/java/toolchains/java_runtime_tests.bzl b/test/java/toolchains/java_runtime_tests.bzl index 2cc617bf..a32c3a99 100644 --- a/test/java/toolchains/java_runtime_tests.bzl +++ b/test/java/toolchains/java_runtime_tests.bzl @@ -1,6 +1,7 @@ """Tests for the java_runtime rule""" load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java/common:java_semantics.bzl", "semantics") load("//java/toolchains:java_runtime.bzl", "java_runtime") @@ -151,6 +152,143 @@ def _test_runtime_alias_impl(env, target): env.expect.that_target(target).has_provider(platform_common.ToolchainInfo) env.expect.that_target(target).has_provider(platform_common.TemplateVariableInfo) +def _test_java_runtime_simple(name): + util.helper_target( + java_runtime, + name = name + "/jvm-foo", + srcs = [ + "foo/a", + "foo/b", + ], + java_home = "foo", + ) + + analysis_test( + name = name, + impl = _test_java_runtime_simple_impl, + target = name + "/jvm-foo", + ) + +def _test_java_runtime_simple_impl(env, target): + java_runtime_info_subject.from_target(env, target).files().contains_exactly([ + "{package}/foo/a", + "{package}/foo/b", + ]) + env.expect.that_target(target).data_runfiles().contains_exactly([ + "{workspace}/{package}/foo/a", + "{workspace}/{package}/foo/b", + ]) + +def _test_absolute_java_home_with_srcs(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + srcs = ["dummy.txt"], + java_home = "/absolute/path", + ) + + analysis_test( + name = name, + impl = _test_absolute_java_home_with_srcs_impl, + target = name + "/jvm", + expect_failure = True, + ) + +def _test_absolute_java_home_with_srcs_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("'java_home' with an absolute path requires 'srcs' to be empty."), + ) + +def _test_absolute_java_home_with_java(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + java = "bin/java", + java_home = "/absolute/path", + ) + + analysis_test( + name = name, + impl = _test_absolute_java_home_with_java_impl, + target = name + "/jvm", + expect_failure = True, + ) + +def _test_absolute_java_home_with_java_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("'java_home' with an absolute path requires 'java' to be empty."), + ) + +def _test_bin_java_path_name(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + java = "java", + ) + + analysis_test( + name = name, + impl = _test_bin_java_path_name_impl, + target = name + "/jvm", + expect_failure = True, + ) + +def _test_bin_java_path_name_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("the path to 'java' must end in 'bin/java'."), + ) + +def _test_absolute_java_home(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + java_home = "/absolute/path", + ) + + analysis_test( + name = name, + impl = _test_absolute_java_home_impl, + target = name + "/jvm", + ) + +def _test_absolute_java_home_impl(env, target): + java_runtime_info_subject.from_target(env, target).java_home().equals("/absolute/path") + +def _test_relative_java_home(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + java_home = "b/c", + ) + + analysis_test( + name = name, + impl = _test_relative_java_home_impl, + target = name + "/jvm", + ) + +def _test_relative_java_home_impl(env, target): + java_runtime_info_subject.from_target(env, target).java_home().equals("{package}/b/c") + +def _test_java_home_with_invalid_make_variables(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + java_home = "/opt/$(WTF)", + ) + + analysis_test( + name = name, + impl = _test_java_home_with_invalid_make_variables_impl, + target = name + "/jvm", + expect_failure = True, + ) + +def _test_java_home_with_invalid_make_variables_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("$(WTF) not defined"), + ) + def java_runtime_tests(name): test_suite( name = name, @@ -159,5 +297,12 @@ def java_runtime_tests(name): _test_with_hermetic_java_home, _test_with_generated_java_executable, _test_runtime_alias, + _test_java_runtime_simple, + _test_absolute_java_home_with_srcs, + _test_absolute_java_home_with_java, + _test_bin_java_path_name, + _test_absolute_java_home, + _test_relative_java_home, + _test_java_home_with_invalid_make_variables, ], ) From d6d662848ecdbd874d9ed351e3c072997c0ced2b Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 16 Feb 2026 04:11:31 -0800 Subject: [PATCH 397/465] Internal change PiperOrigin-RevId: 870821103 Change-Id: I7890323adef19ec859bbbcb64ce8ddcd2c833bb6 --- java/private/java_common.bzl | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/java/private/java_common.bzl b/java/private/java_common.bzl index 3c11c0e8..6d877d76 100644 --- a/java/private/java_common.bzl +++ b/java/private/java_common.bzl @@ -299,7 +299,6 @@ def _make_java_common(): "default_javac_opts": _default_javac_opts, "default_javac_opts_depset": _default_javac_opts_depset, "merge": _merge, - "make_non_strict": _make_non_strict, "JavaPluginInfo": JavaPluginInfo, "JavaToolchainInfo": JavaToolchainInfo, "JavaRuntimeInfo": JavaRuntimeInfo, @@ -314,6 +313,10 @@ def _make_java_common(): set_annotation_processing = _set_annotation_processing, java_toolchain_label = _java_toolchain_label, ) + if semantics.IS_BAZEL: + methods.update( + make_non_strict = _make_non_strict, + ) return struct(**methods) java_common = _make_java_common() From 5265486294c2a0f5269495424a5df9ad569cc543 Mon Sep 17 00:00:00 2001 From: hvadehra Date: Tue, 17 Feb 2026 05:56:40 -0800 Subject: [PATCH 398/465] Add releasing and publish-to-bcr workflows (#351) Work towards https://github.com/bazelbuild/rules_java/issues/307 Closes #351 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/351 from bazelbuild:hvd_gh_release 8a853c71d68ed1ff8c32ea1187ae81b046c422b7 PiperOrigin-RevId: 871272493 Change-Id: I18daeeddd75f73b936de1a7dd0d3e2c7b8b09b9b --- .github/workflows/publish.yaml | 32 +++++++++++++++++++++++++++++++ .github/workflows/release.yaml | 27 ++++++++++++++++++++++++++ .github/workflows/release_prep.sh | 17 ++++++++++++++++ MODULE.bazel | 2 +- 4 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/publish.yaml create mode 100644 .github/workflows/release.yaml create mode 100755 .github/workflows/release_prep.sh diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml new file mode 100644 index 00000000..3652a521 --- /dev/null +++ b/.github/workflows/publish.yaml @@ -0,0 +1,32 @@ +name: Publish to BCR +on: + # Run the publish workflow after a successful release + # Will be triggered from the release.yaml workflow + workflow_call: + inputs: + tag_name: + required: true + type: string + # Permit release engineers to retry manually from the GitHub UI + workflow_dispatch: + inputs: + tag_name: + description: git tag being released + required: true + type: string +jobs: + publish: + uses: bazel-contrib/publish-to-bcr/.github/workflows/publish.yaml@v1.1.0 + with: + tag_name: ${{ inputs.tag_name }} + # GitHub repository which is a fork of the upstream where the Pull Request will be opened. + registry_fork: bazel-io/bazel-central-registry + draft: false + attest: true + permissions: + contents: write + id-token: write + attestations: write + secrets: + # Necessary to push to the BCR fork, and to open a pull request against a registry + publish_token: ${{ secrets.BCR_PUBLISH_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 00000000..29c7bfbb --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,27 @@ +# Automatically perform a release whenever a new "release-like" tag is pushed to the repo. +name: Release + +on: + push: + tags: + # Detect tags that look like a release. + - "*.*.*" +permissions: + id-token: write + attestations: write + contents: write +jobs: + release: + uses: bazel-contrib/.github/.github/workflows/release_ruleset.yaml@v7.2.3 + with: + tag_name: ${{ github.ref_name }} + prerelease: false + draft: false + generate_release_notes: true + release_files: bazel-bin/distro/rules_java-*.tar.gz + bazel_test_command: "bazel test //test/... -//test:docs_up_to_date_test" + publish: + needs: release + uses: ./.github/workflows/publish.yaml + with: + tag_name: ${{ github.ref_name }} diff --git a/.github/workflows/release_prep.sh b/.github/workflows/release_prep.sh new file mode 100755 index 00000000..3173376a --- /dev/null +++ b/.github/workflows/release_prep.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash + +set -o errexit -o nounset -o pipefail + +RELEASE_VERSION=${1} + +# update MODULE.bazel with the version number +sed -i "3s/version = \"0.0.0\"/version = \"${RELEASE_VERSION}\"/" MODULE.bazel + +# create release artifacts +bazel build //distro:relnotes //distro:rules_java-${RELEASE_VERSION}.tar.gz + +# revert change to MODULE.bazel +git checkout -- MODULE.bazel + +# print the release notes for release.yaml +cat bazel-bin/distro/relnotes.txt diff --git a/MODULE.bazel b/MODULE.bazel index 70e975f3..47354f67 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "rules_java", - version = "9.5.0", + version = "0.0.0", bazel_compatibility = [">=7.0.0"], compatibility_level = 1, ) From 188850bf0b98b4f2b8084f0b9f508c542b1dcba9 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 17 Feb 2026 06:58:08 -0800 Subject: [PATCH 399/465] `JavaStarlarkApiTest`: starlarkify `javaInfoConstructorWithNeverlink` This seems like a pretty trivial test. Do we even need it? Should I consider appropriate coverage or is that out of scope of the "Starlarkify the coverage we already have" task? PiperOrigin-RevId: 871294944 Change-Id: I404acea5e0734ee7f7cb83b1c932d096f9937cbe --- test/java/common/java_info_tests.bzl | 19 +++++++++++++++++++ test/java/testutil/java_info_subject.bzl | 1 + 2 files changed, 20 insertions(+) diff --git a/test/java/common/java_info_tests.bzl b/test/java/common/java_info_tests.bzl index a646e112..ce82df2b 100644 --- a/test/java/common/java_info_tests.bzl +++ b/test/java/common/java_info_tests.bzl @@ -1261,6 +1261,24 @@ def _output_source_jars_returns_depset_test_impl(env, target): source_jars = target[JavaInfo].java_outputs[0].source_jars env.expect.that_str(type(source_jars)).equals(type(depset())) +def _java_info_constructor_with_neverlink_test(name): + target_name = name + "/my_starlark_rule" + util.helper_target( + custom_java_info_rule, + name = target_name, + output_jar = target_name + "/my_starlark_rule_lib.jar", + neverlink = True, + ) + + analysis_test( + name = name, + impl = _java_info_constructor_with_neverlink_test_impl, + target = target_name, + ) + +def _java_info_constructor_with_neverlink_test_impl(env, target): + java_info_subject.from_target(env, target).is_neverlink().equals(True) + def java_info_tests(name): test_suite( name = name, @@ -1305,5 +1323,6 @@ def java_info_tests(name): _annotation_processing_test, _compilation_info_test, _output_source_jars_returns_depset_test, + _java_info_constructor_with_neverlink_test, ], ) diff --git a/test/java/testutil/java_info_subject.bzl b/test/java/testutil/java_info_subject.bzl index e0ec8059..8471706f 100644 --- a/test/java/testutil/java_info_subject.bzl +++ b/test/java/testutil/java_info_subject.bzl @@ -27,6 +27,7 @@ def _new_java_info_subject(java_info, meta): transitive_source_jars_list = lambda: subjects.collection(java_info.transitive_source_jars.to_list(), self.meta.derive("transitive_source_jars.to_list()")), runtime_output_jars = lambda: subjects.depset_file(java_info.runtime_output_jars, self.meta.derive("runtime_output_jars")), module_flags = lambda: _new_java_module_flags_subject(self.actual, self.meta), + is_neverlink = lambda: subjects.bool(getattr(java_info, "_neverlink", False), self.meta.derive("_neverlink")), ) return public From 6710ecd8efdea80d8b0da92db5b699202343c2e7 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 18 Feb 2026 05:51:22 -0800 Subject: [PATCH 400/465] Creates _test_make_variables for java_runtime() in toolchains/java_runtime_tests.bzl PiperOrigin-RevId: 871826344 Change-Id: I787659e6082a48e0e7a7003e1ae47bc66fd3fa83 --- MODULE.bazel | 6 +++--- test/java/toolchains/java_runtime_tests.bzl | 24 ++++++++++++++++++++- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index 47354f67..de8fe111 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -131,9 +131,9 @@ bazel_dep(name = "rules_shell", version = "0.2.0", dev_dependency = True) bazel_dep(name = "rules_testing", dev_dependency = True) archive_override( module_name = "rules_testing", - integrity = "sha256-0+3pLjeZCqn+K1qS7HNr7HbwMXBjxLvJm+pMSUhDel8=", - strip_prefix = "rules_testing-db007bfee840cebcb6f955b80973ba866de38947", - urls = ["https://github.com/bazelbuild/rules_testing/archive/db007bfee840cebcb6f955b80973ba866de38947.tar.gz"], + integrity = "sha256-TqwTCQnzt/hRKQtdJ7d8ebtZ8+I8IMgmWiEjOKvo6mI=", + strip_prefix = "rules_testing-f8e869d452507fa4a59748c9d69cfab63ec9385a", + urls = ["https://github.com/bazelbuild/rules_testing/archive/f8e869d452507fa4a59748c9d69cfab63ec9385a.tar.gz"], ) test_repositories = use_extension("//test:repositories.bzl", "test_repositories_ext", dev_dependency = True) diff --git a/test/java/toolchains/java_runtime_tests.bzl b/test/java/toolchains/java_runtime_tests.bzl index a32c3a99..a1865140 100644 --- a/test/java/toolchains/java_runtime_tests.bzl +++ b/test/java/toolchains/java_runtime_tests.bzl @@ -1,7 +1,7 @@ """Tests for the java_runtime rule""" load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") -load("@rules_testing//lib:truth.bzl", "matching") +load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") load("//java/common:java_semantics.bzl", "semantics") load("//java/toolchains:java_runtime.bzl", "java_runtime") @@ -289,6 +289,27 @@ def _test_java_home_with_invalid_make_variables_impl(env, target): matching.str_matches("$(WTF) not defined"), ) +def _test_make_variables(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + java_home = "/foo/bar", + ) + + analysis_test( + name = name, + impl = _test_make_variables_impl, + target = name + "/jvm", + ) + +def _test_make_variables_impl(env, target): + env.expect.that_target(target).provider( + platform_common.TemplateVariableInfo, + ).variables().contains_at_least({"JAVABASE": "/foo/bar"}) + env.expect.that_target(target).provider( + platform_common.TemplateVariableInfo, + ).variables().get("JAVA", factory = subjects.str).starts_with("/foo/bar/bin/java") + def java_runtime_tests(name): test_suite( name = name, @@ -304,5 +325,6 @@ def java_runtime_tests(name): _test_absolute_java_home, _test_relative_java_home, _test_java_home_with_invalid_make_variables, + _test_make_variables, ], ) From 4b4390839f3b838d9a846af1ba020bb1de61b4aa Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 18 Feb 2026 07:27:40 -0800 Subject: [PATCH 401/465] Creates _test_no_srcs for java_runtime() in toolchains/java_runtime_tests.bzl PiperOrigin-RevId: 871861263 Change-Id: I8fc85bb0970576b0e3e9bdecec2fb4a0c27f168f --- test/java/toolchains/java_runtime_tests.bzl | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/java/toolchains/java_runtime_tests.bzl b/test/java/toolchains/java_runtime_tests.bzl index a1865140..8efa5d2f 100644 --- a/test/java/toolchains/java_runtime_tests.bzl +++ b/test/java/toolchains/java_runtime_tests.bzl @@ -310,6 +310,24 @@ def _test_make_variables_impl(env, target): platform_common.TemplateVariableInfo, ).variables().get("JAVA", factory = subjects.str).starts_with("/foo/bar/bin/java") +def _test_no_srcs(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + java_home = "/opt/jvm", + ) + + analysis_test( + name = name, + impl = _test_no_srcs_impl, + target = name + "/jvm", + ) + +def _test_no_srcs_impl(env, target): + assert_info = java_runtime_info_subject.from_target(env, target) + assert_info.java_home().equals("/opt/jvm") + assert_info.files().contains_exactly([]) + def java_runtime_tests(name): test_suite( name = name, @@ -326,5 +344,6 @@ def java_runtime_tests(name): _test_relative_java_home, _test_java_home_with_invalid_make_variables, _test_make_variables, + _test_no_srcs, ], ) From 3ed922825db30a419b8c8487d5b3b8e1533d0303 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 18 Feb 2026 08:32:54 -0800 Subject: [PATCH 402/465] `JavaStarlarkApiTest`: starlarkify neverlink, native lib tests. PiperOrigin-RevId: 871885265 Change-Id: I3b50a3a2e18391741e745b258fa343fa5ba2385d --- test/java/common/java_info_tests.bzl | 118 +++++++++++++++++- test/java/common/rules/java_library_tests.bzl | 2 - test/java/testutil/rules/java_info_merge.bzl | 17 +++ 3 files changed, 133 insertions(+), 4 deletions(-) create mode 100644 test/java/testutil/rules/java_info_merge.bzl diff --git a/test/java/common/java_info_tests.bzl b/test/java/common/java_info_tests.bzl index ce82df2b..4f82d3eb 100644 --- a/test/java/common/java_info_tests.bzl +++ b/test/java/common/java_info_tests.bzl @@ -10,7 +10,9 @@ load("//java/common:java_info.bzl", "JavaInfo") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:rules/bad_java_info_rules.bzl", "bad_deps", "bad_exports", "bad_libs", "bad_runtime_deps", "compile_jar_not_set", "compile_jar_set_to_none") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") +load("//test/java/testutil:rules/custom_library.bzl", "custom_library") load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") +load("//test/java/testutil:rules/java_info_merge.bzl", "java_info_merge_rule") def _with_output_jar_only_test(name): target_name = name + "/my_starlark_rule" @@ -168,8 +170,6 @@ def _with_native_libraries_test(name): name = name, impl = _with_native_libraries_test_impl, target = target_name, - # LibraryToLink.library_indentifier only available from Bazel 8 - attr_values = {"tags": ["min_bazel_8"]}, ) def _with_native_libraries_test_impl(env, target): @@ -1279,6 +1279,117 @@ def _java_info_constructor_with_neverlink_test(name): def _java_info_constructor_with_neverlink_test_impl(env, target): java_info_subject.from_target(env, target).is_neverlink().equals(True) +def _java_common_merge_with_neverlink_test(name): + target_name = name + "/merged" + util.helper_target( + custom_java_info_rule, + name = target_name + "/with_neverlink", + output_jar = target_name + "/with_neverlink.jar", + neverlink = True, + ) + util.helper_target( + custom_java_info_rule, + name = target_name + "/without_neverlink", + output_jar = target_name + "/without_neverlink.jar", + neverlink = False, + ) + util.helper_target( + java_info_merge_rule, + name = target_name, + deps = [target_name + "/with_neverlink", target_name + "/without_neverlink"], + ) + + analysis_test( + name = name, + impl = _java_common_merge_with_neverlink_test_impl, + target = target_name, + ) + +def _java_common_merge_with_neverlink_test_impl(env, target): + java_info_subject.from_target(env, target).is_neverlink().equals(True) + +def _java_common_compile_with_neverlink_test(name): + target_name = name + "/compiled" + util.helper_target( + custom_library, + name = target_name, + srcs = ["A.java"], + neverlink = True, + ) + + analysis_test( + name = name, + impl = _java_common_compile_with_neverlink_test_impl, + target = target_name, + ) + +def _java_common_compile_with_neverlink_test_impl(env, target): + java_info_subject.from_target(env, target).is_neverlink().equals(True) + +# Tests that java_common.compile propagates native libraries from deps, +# runtime_deps, and exports. +def _java_common_compile_native_libraries_propagate_test(name): + target_name = name + "/compiled" + + util.helper_target( + cc_library, + name = target_name + "/native_dep", + srcs = ["a.cc"], + ) + util.helper_target( + java_library, + name = target_name + "/lib_dep", + srcs = ["B.java"], + deps = [target_name + "/native_dep"], + ) + + util.helper_target( + cc_library, + name = target_name + "/native_rdep", + srcs = ["c.cc"], + ) + util.helper_target( + java_library, + name = target_name + "/lib_rdep", + srcs = ["D.java"], + deps = [target_name + "/native_rdep"], + ) + + util.helper_target( + cc_library, + name = target_name + "/native_export", + srcs = ["e.cc"], + ) + util.helper_target( + java_library, + name = target_name + "/lib_export", + srcs = ["F.java"], + deps = [target_name + "/native_export"], + ) + + util.helper_target( + custom_library, + name = target_name, + srcs = ["G.java"], + deps = [target_name + "/lib_dep"], + runtime_deps = [target_name + "/lib_rdep"], + exports = [target_name + "/lib_export"], + ) + + analysis_test( + name = name, + impl = _java_common_compile_native_libraries_propagate_test_impl, + target = target_name, + ) + +def _java_common_compile_native_libraries_propagate_test_impl(env, target): + assert_native_libs = java_info_subject.from_target(env, target).transitive_native_libraries() + assert_native_libs.static_libraries().contains_exactly_predicates([ + matching.str_matches("*native_rdep*"), + matching.str_matches("*native_export*"), + matching.str_matches("*native_dep*"), + ]) + def java_info_tests(name): test_suite( name = name, @@ -1324,5 +1435,8 @@ def java_info_tests(name): _compilation_info_test, _output_source_jars_returns_depset_test, _java_info_constructor_with_neverlink_test, + _java_common_merge_with_neverlink_test, + _java_common_compile_with_neverlink_test, + _java_common_compile_native_libraries_propagate_test, ], ) diff --git a/test/java/common/rules/java_library_tests.bzl b/test/java/common/rules/java_library_tests.bzl index 58a282f9..c6bb282a 100644 --- a/test/java/common/rules/java_library_tests.bzl +++ b/test/java/common/rules/java_library_tests.bzl @@ -267,8 +267,6 @@ def _test_propagates_direct_native_libraries(name): name = name, impl = _test_propagates_direct_native_libraries_impl, target = target_name, - # LibraryToLink.library_indentifier only available from Bazel 8 - attr_values = {"tags": ["min_bazel_8"]}, ) def _test_propagates_direct_native_libraries_impl(env, target): diff --git a/test/java/testutil/rules/java_info_merge.bzl b/test/java/testutil/rules/java_info_merge.bzl new file mode 100644 index 00000000..e31201d9 --- /dev/null +++ b/test/java/testutil/rules/java_info_merge.bzl @@ -0,0 +1,17 @@ +"""Helper rule for testing java_common.merge""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") + +def _impl(ctx): + java_infos = [dep[JavaInfo] for dep in ctx.attr.deps] + merged_info = java_common.merge(java_infos) + return [merged_info] + +java_info_merge_rule = rule( + implementation = _impl, + attrs = { + "deps": attr.label_list(providers = [JavaInfo]), + }, + provides = [JavaInfo], +) From 4586a5bb4278d625922a3fb3f87b06fecf93ceda Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 19 Feb 2026 00:52:33 -0800 Subject: [PATCH 403/465] Creates _test_java_home_generated for java_runtime() in toolchains/java_runtime_tests.bzl PiperOrigin-RevId: 872258802 Change-Id: I812815c2aa1c0b3671f7661f5fec358f2029a9c8 --- .../testutil/java_runtime_info_subject.bzl | 1 + test/java/toolchains/java_runtime_tests.bzl | 26 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/test/java/testutil/java_runtime_info_subject.bzl b/test/java/testutil/java_runtime_info_subject.bzl index 37a477eb..ad68fead 100644 --- a/test/java/testutil/java_runtime_info_subject.bzl +++ b/test/java/testutil/java_runtime_info_subject.bzl @@ -41,6 +41,7 @@ def _from_target(env, target): "name": target.label.name, "package": target.label.package, "bindir": target[TestingAspectInfo].bin_path, + "gendir": env.ctx.configuration.genfiles_dir.path, }, ), ) diff --git a/test/java/toolchains/java_runtime_tests.bzl b/test/java/toolchains/java_runtime_tests.bzl index 8efa5d2f..5ec2a061 100644 --- a/test/java/toolchains/java_runtime_tests.bzl +++ b/test/java/toolchains/java_runtime_tests.bzl @@ -328,6 +328,31 @@ def _test_no_srcs_impl(env, target): assert_info.java_home().equals("/opt/jvm") assert_info.files().contains_exactly([]) +def _test_java_home_generated(name): + util.helper_target( + native.genrule, + name = name + "/gen", + outs = ["generated_java_home/bin/java"], + cmd = "touch $@", + ) + util.helper_target( + java_runtime, + name = name + "/jvm", + java = "generated_java_home/bin/java", + java_home = "generated_java_home", + ) + + analysis_test( + name = name, + impl = _test_java_home_generated_impl, + target = name + "/jvm", + ) + +def _test_java_home_generated_impl(env, target): + java_runtime_info_subject.from_target(env, target).java_home().equals( + "{gendir}/{package}/generated_java_home", + ) + def java_runtime_tests(name): test_suite( name = name, @@ -345,5 +370,6 @@ def java_runtime_tests(name): _test_java_home_with_invalid_make_variables, _test_make_variables, _test_no_srcs, + _test_java_home_generated, ], ) From 2e5f415c8ff81763efa0bdd4cb2dd6a20ee19381 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 23 Feb 2026 02:09:50 -0800 Subject: [PATCH 404/465] Update to `release_ruleset.yaml` `v7.3.0` PiperOrigin-RevId: 873950161 Change-Id: I96843bcdfa95bc8d68f1629c75eaee7a85793326 --- .github/workflows/release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 29c7bfbb..2bd13f25 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -12,7 +12,7 @@ permissions: contents: write jobs: release: - uses: bazel-contrib/.github/.github/workflows/release_ruleset.yaml@v7.2.3 + uses: bazel-contrib/.github/.github/workflows/release_ruleset.yaml@v7.3.0 with: tag_name: ${{ github.ref_name }} prerelease: false From 03a8aed7e18ff28bd8a218505f9b05f160ba81ca Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 23 Feb 2026 03:45:04 -0800 Subject: [PATCH 405/465] Clean up references to disabled test PiperOrigin-RevId: 873985222 Change-Id: Ie7bfadfc788830da6a4e5a98139f2a7949e2de2e --- .bazelci/presubmit.yml | 4 ---- .github/workflows/release.yaml | 2 +- test/BUILD.bazel | 2 ++ 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 411f490c..704e6eb1 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -10,9 +10,7 @@ build_targets: &build_targets - "@remote_java_tools//:singlejar_cc_bin" # can't build @remote_java_tools_X repos for other platforms - "-//toolchains/..." - # TODO: re-enable docs after moving them out of https://bazel.build/reference/be/java - "-//java/docs/..." - - "-//test:docs_up_to_date_test" build_targets_integration: &build_targets_integration - "//..." @@ -20,8 +18,6 @@ build_targets_integration: &build_targets_integration test_targets: &test_targets - "//test/..." - # TODO: re-enable docs after moving them out of https://bazel.build/reference/be/java - - "-//test:docs_up_to_date_test" test_target_integration: &test_target_integration - "//:MyTest" diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 2bd13f25..06ee719b 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -19,7 +19,7 @@ jobs: draft: false generate_release_notes: true release_files: bazel-bin/distro/rules_java-*.tar.gz - bazel_test_command: "bazel test //test/... -//test:docs_up_to_date_test" + bazel_test_command: "bazel test -- //test/..." publish: needs: release uses: ./.github/workflows/publish.yaml diff --git a/test/BUILD.bazel b/test/BUILD.bazel index 951280d6..fdc241fb 100644 --- a/test/BUILD.bazel +++ b/test/BUILD.bazel @@ -72,6 +72,8 @@ diff_test( """, file1 = "//java/docs:rules.md", file2 = "//java/docs:rules_docs", + # TODO: b/369123329 - re-enable docs after moving them out of https://bazel.build/reference/be/java + tags = ["manual"], ) validate_configs() From d3280ec2fa55739f45205fc25683c9a67d37b450 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 23 Feb 2026 04:52:32 -0800 Subject: [PATCH 406/465] Fix workflow test command The reusable workflow adds flags after our command so we can't use `--` PiperOrigin-RevId: 874008604 Change-Id: Ia46f2639620566509599ea5362b1ac3f0fcaed74 --- .github/workflows/release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 06ee719b..dcd3d167 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -19,7 +19,7 @@ jobs: draft: false generate_release_notes: true release_files: bazel-bin/distro/rules_java-*.tar.gz - bazel_test_command: "bazel test -- //test/..." + bazel_test_command: "bazel test //test/..." publish: needs: release uses: ./.github/workflows/publish.yaml From ddcdff8a6c948a6624a3af33e6da2cbd2d13fcf9 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 23 Feb 2026 06:28:15 -0800 Subject: [PATCH 407/465] Fix publish workflow Secrets are not passed to reusable workflows by default. Ref: https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows#passing-inputs-and-secrets-to-a-reusable-workflow PiperOrigin-RevId: 874040719 Change-Id: Icca60ffc830c576b165d389eaaab3b49a17f137c --- .github/workflows/release.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index dcd3d167..4bfb5090 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -25,3 +25,4 @@ jobs: uses: ./.github/workflows/publish.yaml with: tag_name: ${{ github.ref_name }} + secrets: inherit From f31c1a8818dd75775353d884bec604b18ee66697 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 23 Feb 2026 08:16:19 -0800 Subject: [PATCH 408/465] Starlarkify JavaToolchainTest.javac_getsOptionsFromToolchain() PiperOrigin-RevId: 874081635 Change-Id: Ie56e4c40878e781e130a229b60bf2e7bdf0386c3 --- test/java/testutil/javac_action_subject.bzl | 19 +++- test/java/toolchains/java_toolchain_tests.bzl | 93 +++++++++++++++++-- 2 files changed, 98 insertions(+), 14 deletions(-) diff --git a/test/java/testutil/javac_action_subject.bzl b/test/java/testutil/javac_action_subject.bzl index 0a14c777..ef23812c 100644 --- a/test/java/testutil/javac_action_subject.bzl +++ b/test/java/testutil/javac_action_subject.bzl @@ -4,10 +4,10 @@ load("@rules_testing//lib:truth.bzl", "subjects", "truth") load("@rules_testing//lib:util.bzl", "TestingAspectInfo") def _new_javac_action_subject(env, target, output): - action = env.expect.that_target(target).action_generating(output).actual + action_subject = env.expect.that_target(target).action_generating(output) self = struct( - actual = action, - parsed_flags = _parse_flags(action.argv), + actual = action_subject.actual, + parsed_flags = _parse_flags(action_subject.actual.argv), meta = truth.expect(env).meta.derive( "Javac", format_str_kwargs = { @@ -17,8 +17,15 @@ def _new_javac_action_subject(env, target, output): }, ), ) + public = struct( - direct_dependencies = lambda: subjects.collection(self.parsed_flags["--direct_dependencies"], self.meta.derive("--direct_dependencies"), format = True), + direct_dependencies = lambda: _create_subject_for_flag("--direct_dependencies", self.parsed_flags, self.meta), + source = lambda: _create_subject_for_flag("-source", self.parsed_flags, self.meta), + target = lambda: _create_subject_for_flag("-target", self.parsed_flags, self.meta), + xmaxerrs = lambda: _create_subject_for_flag("-Xmaxerrs", self.parsed_flags, self.meta), + jar = lambda: _create_subject_for_flag("-jar", self.parsed_flags, self.meta), + inputs = action_subject.inputs, + argv = action_subject.argv, ) return public @@ -43,6 +50,10 @@ def _parse_flags(argv): return flag_values +def _create_subject_for_flag(flag_name, parsed_flags, meta): + """Helper to create a collection subject for a given flag.""" + return subjects.collection(parsed_flags[flag_name], meta.derive(flag_name), format = True) + javac_action_subject = struct( of = _new_javac_action_subject, parse_flags = _parse_flags, # exposed for testing this method itself diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index 928ce00b..976bb082 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -2,28 +2,100 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") +load("//java:java_library.bzl", "java_library") +load("//java/common:java_semantics.bzl", "semantics") load("//java/toolchains:java_runtime.bzl", "java_runtime") load("//java/toolchains:java_toolchain.bzl", "java_toolchain") load("//test/java/testutil:java_toolchain_info_subject.bzl", "java_toolchain_info_subject") +load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") def _declare_java_toolchain(*, name, **kwargs): - if "java_runtime" not in kwargs: - kwargs["java_runtime"] = name + "/runtime" - java_runtime(name = name + "/runtime") + java_runtime_name = name + "/runtime" + java_runtime(name = java_runtime_name) + toolchain_attrs = { + "source_version": "6", + "target_version": "6", + "bootclasspath": ["rt.jar"], + "xlint": ["toto"], + "javacopts": ["-Xmaxerrs 500"], + "compatible_javacopts": { + "android": ["-XDandroidCompatible"], + "testonly": ["-XDtestOnly"], + "public_visibility": ["-XDpublicVisibility"], + }, + "tools": [":javac_canary.jar"], + "javabuilder": ":JavaBuilder_deploy.jar", + "header_compiler": ":turbine_canary_deploy.jar", + "header_compiler_direct": ":turbine_direct", + "singlejar": "singlejar", + "ijar": "ijar", + "genclass": "GenClass_deploy.jar", + "timezone_data": "tzdata.jar", + "header_compiler_builtin_processors": ["BuiltinProc1", "BuiltinProc2"], + "reduced_classpath_incompatible_processors": [ + "IncompatibleProc1", + "IncompatibleProc2", + ], + "java_runtime": java_runtime_name, + } + toolchain_attrs.update(kwargs) util.helper_target( java_toolchain, + name = name + "/java_toolchain", + **toolchain_attrs + ) + util.helper_target( + native.toolchain, + name = name + "/toolchain", + toolchain = name + "/java_toolchain", + toolchain_type = semantics.JAVA_TOOLCHAIN_TYPE, + ) + +def _test_javac_gets_options(name): + _declare_java_toolchain(name = name) + util.helper_target( + java_library, + name = name + "/b", + srcs = ["b.java"], + ) + util.helper_target( + java_library, + name = name + "/a", + srcs = ["a.java"], + deps = [Label(name + "/b")], + ) + + analysis_test( name = name, - genclass = kwargs.get("genclass", "default_genclass.jar"), - jacocorunner = kwargs.get("jacocorunner", None), - javabuilder = kwargs.get("javabuilder", "default_javabuilder.jar"), - java_runtime = kwargs["java_runtime"], - ijar = kwargs.get("ijar", "default_ijar.jar"), - singlejar = kwargs.get("singlejar", "default_singlejar.jar"), + impl = _test_javac_gets_options_impl, + targets = { + "a": name + "/a", + "b": name + "/b", + }, + config_settings = { + "//command_line_option:java_header_compilation": "true", + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, ) +def _test_javac_gets_options_impl(env, targets): + assert_javac_action = javac_action_subject.of(env, targets.a, "{package}/lib{name}.jar") + assert_javac_action.source().contains_exactly(["6"]) + assert_javac_action.target().contains_exactly(["6"]) + assert_javac_action.xmaxerrs().contains_exactly(["500"]) + assert_javac_action.jar().contains_exactly(["{package}/JavaBuilder_deploy.jar"]) + assert_javac_action.inputs().contains("{package}/rt.jar") + + assert_argv = assert_javac_action.argv() + assert_argv.contains("-Xlint:toto") + assert_argv.not_contains("-g") + + assert_header_action = javac_action_subject.of(env, targets.b, "{package}/lib{name}-hjar.jar") + assert_header_action.argv().contains("{package}/turbine_direct") + def _test_jacocorunner(name): _declare_java_toolchain( - name = name + "/java_toolchain", + name = name, jacocorunner = "myjacocorunner.jar", ) @@ -43,5 +115,6 @@ def java_toolchain_tests(name): name = name, tests = [ _test_jacocorunner, + _test_javac_gets_options, ], ) From 737f145f16decfae668f07448dcd479686dd3865 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 23 Feb 2026 10:09:22 -0800 Subject: [PATCH 409/465] Migrate JavaPluginConfiguredTargetTest to Starlark. This deletes and does not replace TestNoConstraintsAttribute, because it checks for a loading phase error. PiperOrigin-RevId: 874134416 Change-Id: I8e18dc44c391fd7ec4832adf4576778af5bb333a --- test/java/common/rules/java_plugin_tests.bzl | 304 +++++++++++++++++++ 1 file changed, 304 insertions(+) diff --git a/test/java/common/rules/java_plugin_tests.bzl b/test/java/common/rules/java_plugin_tests.bzl index 646de647..71c2d156 100644 --- a/test/java/common/rules/java_plugin_tests.bzl +++ b/test/java/common/rules/java_plugin_tests.bzl @@ -1,10 +1,12 @@ """Tests for the java_plugin rule""" load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "subjects") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") +load("//java/common:proguard_spec_info.bzl", "ProguardSpecInfo") load("//test/java/testutil:java_info_subject.bzl", "java_plugin_info_subject") def _test_exposes_plugins_to_starlark(name): @@ -75,11 +77,313 @@ def _test_exposes_api_generating_plugins_to_starlark_impl(env, target): assert_api_plugin_data.processor_data().contains_exactly(["{package}/pluginfile.dat"]) assert_api_plugin_data.equals(target[JavaPluginInfo].plugins) +def _test_not_empty_processor_class(name): + util.helper_target( + java_library, + name = name + "/deps", + srcs = ["Deps.java"], + ) + util.helper_target( + java_plugin, + name = name + "/processor", + srcs = ["Processor.java"], + processor_class = "com.google.test.Processor", + deps = [name + "/deps"], + ) + + analysis_test( + name = name, + impl = _test_not_empty_processor_class_impl, + target = name + "/processor", + ) + +def _test_not_empty_processor_class_impl(env, target): + plugin_info = java_plugin_info_subject.from_target(env, target) + plugin_info.plugins().processor_classes().contains_exactly(["com.google.test.Processor"]) + + plugin_info.plugins().processor_jars().contains_exactly([ + "{package}/lib{name}.jar", + "{package}/lib{test_name}/deps.jar", + ]) + +def _test_empty_processor_class(name): + util.helper_target( + java_library, + name = name + "/deps", + srcs = ["Deps.java"], + ) + util.helper_target( + java_plugin, + name = name + "/bugchecker", + srcs = ["BugChecker.java"], + deps = [":" + name + "/deps"], + ) + + analysis_test( + name = name, + impl = _test_empty_processor_class_impl, + target = name + "/bugchecker", + ) + +def _test_empty_processor_class_impl(env, target): + plugin_info = java_plugin_info_subject.from_target(env, target) + plugin_info.plugins().processor_classes().contains_exactly([]) + plugin_info.plugins().processor_jars().contains_exactly([ + "{package}/lib{name}.jar", + "{package}/lib{test_name}/deps.jar", + ]) + +def _test_empty_processor_class_target(name): + util.helper_target( + java_library, + name = name + "/deps", + srcs = ["Deps.java"], + ) + util.helper_target( + java_plugin, + name = name + "/bugchecker", + srcs = ["BugChecker.java"], + deps = [":" + name + "/deps"], + ) + util.helper_target( + java_library, + name = name + "/empty", + plugins = [":" + name + "/bugchecker"], + ) + + analysis_test( + name = name, + impl = _test_empty_processor_class_target_impl, + target = name + "/empty", + ) + +def _test_empty_processor_class_target_impl(env, target): + env.expect.that_target(target).action_generating("{package}/lib{name}.jar").inputs().contains_at_least([ + "{package}/lib{test_name}/bugchecker.jar", + "{package}/lib{test_name}/deps.jar", + ]) + +def _new_proguard_info_subject(info, meta): + return struct( + specs = lambda: subjects.depset_file(info.specs, meta.derive("specs")), + ) + +def _test_java_plugin_exports_transitive_proguard_specs(name): + util.helper_target( + java_plugin, + name = name + "/plugin", + srcs = ["Plugin.java"], + proguard_specs = ["plugin.pro"], + ) + util.helper_target( + java_library, + name = name + "/dep", + srcs = ["Dep.java"], + proguard_specs = ["dep.pro"], + ) + util.helper_target( + java_plugin, + name = name + "/top", + srcs = ["Top.java"], + plugins = [":" + name + "/plugin"], + proguard_specs = ["top.pro"], + deps = [":" + name + "/dep"], + ) + + analysis_test( + name = name, + impl = _test_java_plugin_exports_transitive_proguard_specs_impl, + target = name + "/top", + # Before Bazel 8, native rules use the native ProguardSpecProvider + attr_values = {"tags": ["min_bazel_8"]}, + provider_subject_factories = [struct( + type = ProguardSpecInfo, + name = "ProguardInfo", + factory = _new_proguard_info_subject, + )], + ) + +def _test_java_plugin_exports_transitive_proguard_specs_impl(env, target): + env.expect.that_target(target).provider(ProguardSpecInfo).specs().contains_exactly( + [ + "{package}/validated_proguard/{test_name}/top/{package}/top.pro_valid", + "{package}/validated_proguard/{test_name}/dep/{package}/dep.pro_valid", + ], + ) + +def _test_java_plugin_validates_proguard_specs(name): + util.helper_target( + java_plugin, + name = name + "/plugin", + srcs = ["Plugin.java"], + proguard_specs = ["plugin.pro"], + ) + + analysis_test( + name = name, + impl = _test_java_plugin_validates_proguard_specs_impl, + target = name + "/plugin", + ) + +def _test_java_plugin_validates_proguard_specs_impl(env, target): + output_file = None + for f in target.output_groups["_hidden_top_level_INTERNAL_"].to_list(): + if f.basename == "plugin.pro_valid": + output_file = f + break + env.expect.that_target(target).action_generating( + output_file.short_path, + ).inputs().contains_at_least( + ["{package}/plugin.pro"], + ) + +def _test_java_plugin_validates_transitive_proguard_specs(name): + util.helper_target( + java_library, + name = name + "/transitive", + srcs = ["Transitive.java"], + proguard_specs = ["transitive.pro"], + ) + util.helper_target( + java_plugin, + name = name + "/plugin", + srcs = ["Plugin.java"], + deps = [":" + name + "/transitive"], + ) + + analysis_test( + name = name, + impl = _test_java_plugin_validates_transitive_proguard_specs_impl, + targets = { + "transitive": name + "/transitive", + "plugin": name + "/plugin", + }, + ) + +def _test_java_plugin_validates_transitive_proguard_specs_impl(env, targets): + output_file = None + for f in targets.plugin.output_groups["_hidden_top_level_INTERNAL_"].to_list(): + if f.basename == "transitive.pro_valid": + output_file = f + break + + env.expect.that_target(targets.transitive).action_generating( + output_file.short_path, + ).inputs().contains_at_least(["{package}/transitive.pro"]) + +def _test_generates_api(name): + util.helper_target( + java_plugin, + name = name + "/api_generating", + srcs = ["ApiGeneratingPlugin.java"], + generates_api = True, + processor_class = "ApiGeneratingPlugin", + ) + + analysis_test( + name = name, + impl = _test_generates_api_impl, + target = name + "/api_generating", + ) + +def _test_generates_api_impl(env, target): + plugin_info = java_plugin_info_subject.from_target(env, target) + plugin_info.plugins().processor_classes().contains_exactly(["ApiGeneratingPlugin"]) + plugin_info.api_generating_plugins().processor_classes().contains_exactly(["ApiGeneratingPlugin"]) + plugin_info.plugins().processor_jars().contains_exactly([ + "{package}/lib{name}.jar", + ]) + plugin_info.api_generating_plugins().processor_jars().contains_exactly([ + "{package}/lib{name}.jar", + ]) + +def _test_generates_implementation(name): + util.helper_target( + java_plugin, + name = name + "/impl_generating", + srcs = ["ImplGeneratingPlugin.java"], + generates_api = False, + processor_class = "ImplGeneratingPlugin", + ) + + analysis_test( + name = name, + impl = _test_generates_implementation_impl, + target = name + "/impl_generating", + ) + +def _test_generates_implementation_impl(env, target): + plugin_info = java_plugin_info_subject.from_target(env, target) + plugin_info.plugins().processor_classes().contains_exactly(["ImplGeneratingPlugin"]) + plugin_info.api_generating_plugins().processor_classes().contains_exactly([]) + plugin_info.plugins().processor_jars().contains_exactly([ + "{package}/lib{test_name}/impl_generating.jar", + ]) + plugin_info.api_generating_plugins().processor_jars().contains_exactly([]) + +def _test_plugin_data_in_provider(name): + util.helper_target( + java_plugin, + name = name + "/impl_generating", + srcs = ["ImplGeneratingPlugin.java"], + data = ["data.txt"], + generates_api = False, + processor_class = "ImplGeneratingPlugin", + ) + + analysis_test( + name = name, + impl = _test_plugin_data_in_provider_impl, + target = name + "/impl_generating", + ) + +def _test_plugin_data_in_provider_impl(env, target): + plugin_info = java_plugin_info_subject.from_target(env, target) + plugin_info.plugins().processor_data().contains_exactly([ + "{package}/data.txt", + ]) + +def _test_plugin_data_in_action_inputs(name): + util.helper_target( + java_plugin, + name = name + "/impl_generating_lib", + srcs = ["ImplGeneratingPlugin.java"], + data = ["data.txt"], + generates_api = False, + processor_class = "ImplGeneratingPlugin", + ) + util.helper_target( + java_library, + name = name + "/lib", + plugins = [":" + name + "/impl_generating_lib"], + ) + + analysis_test( + name = name, + impl = _test_plugin_data_in_action_inputs_impl, + target = name + "/lib", + ) + +def _test_plugin_data_in_action_inputs_impl(env, target): + env.expect.that_target(target).action_generating("{package}/lib{name}.jar").inputs().contains_at_least([ + "{package}/data.txt", + ]) + def java_plugin_tests(name): test_suite( name = name, tests = [ _test_exposes_plugins_to_starlark, _test_exposes_api_generating_plugins_to_starlark, + _test_not_empty_processor_class, + _test_empty_processor_class, + _test_empty_processor_class_target, + _test_generates_api, + _test_plugin_data_in_provider, + _test_plugin_data_in_action_inputs, + _test_java_plugin_exports_transitive_proguard_specs, + _test_java_plugin_validates_proguard_specs, + _test_java_plugin_validates_transitive_proguard_specs, + _test_generates_implementation, ], ) From 7ba5fecb9e077f3854501089efdedf5b9bd90e06 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 24 Feb 2026 00:37:51 -0800 Subject: [PATCH 410/465] Internal change PiperOrigin-RevId: 874441487 Change-Id: Id054a171e3f5f2e8a477353c16bf2cc1ff8b8c3a --- .../common/rules/impl/bazel_java_import_impl.bzl | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/java/common/rules/impl/bazel_java_import_impl.bzl b/java/common/rules/impl/bazel_java_import_impl.bzl index 2a107a1e..c402fc44 100644 --- a/java/common/rules/impl/bazel_java_import_impl.bzl +++ b/java/common/rules/impl/bazel_java_import_impl.bzl @@ -63,11 +63,10 @@ def _process_with_ijars_if_needed(jars, ctx): return file_dict -def _check_export_error(ctx, exports): - not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_exports") and not getattr(ctx.attr, "_allowlist_java_import_exports")[PackageSpecificationInfo].contains(ctx.label) +def _check_export_error(ctx, exports, permit_exports): disallow_java_import_exports = ctx.fragments.java.disallow_java_import_exports() - if len(exports) != 0 and (disallow_java_import_exports or not_in_allowlist): + if len(exports) != 0 and (disallow_java_import_exports or not permit_exports): fail("java_import.exports is no longer supported; use java_import.deps instead") def _check_empty_jars_error(ctx, jars): @@ -84,7 +83,9 @@ def bazel_java_import_rule( neverlink = False, proguard_specs = [], add_exports = [], - add_opens = []): + add_opens = [], + permit_exports = True, + skip_incomplete_deps_check = True): """Implements java_import. This rule allows the use of precompiled .jar files as libraries in other Java rules. @@ -100,6 +101,8 @@ def bazel_java_import_rule( proguard_specs: (list[File]) Files to be used as Proguard specification. add_exports: (list[str]) Allow this library to access the given /. add_opens: (list[str]) Allow this library to reflectively access the given /. + permit_exports: (bool) Allow using exports + skip_incomplete_deps_check: (bool) If this target is allowed to have incomplete deps Returns: (list[provider]) A list containing DefaultInfo, JavaInfo, @@ -107,15 +110,14 @@ def bazel_java_import_rule( """ _check_empty_jars_error(ctx, jars) - _check_export_error(ctx, exports) + _check_export_error(ctx, exports, permit_exports) collected_jars = _collect_jars(ctx, jars) all_deps = _filter_provider(JavaInfo, deps, exports) jdeps_artifact = None merged_java_info = java_common.merge(all_deps) - not_in_allowlist = hasattr(ctx.attr, "_allowlist_java_import_deps_checking") and not ctx.attr._allowlist_java_import_deps_checking[PackageSpecificationInfo].contains(ctx.label) - if not_in_allowlist and "incomplete-deps" not in ctx.attr.tags: + if not skip_incomplete_deps_check and "incomplete-deps" not in ctx.attr.tags: jdeps_artifact = import_deps_check( ctx, collected_jars, From c4133ab9a0735b85a98c7ffd5543437db6d7a725 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 24 Feb 2026 01:32:03 -0800 Subject: [PATCH 411/465] Get the last tag at `HEAD~1` for generating release notes Now that we're relying on a tag push for making releases, the latest tag at HEAD is the release we're currently making, and we want the previous tag. (in the earlier release process, we generated the release notes *before* creating the tag) (ignore-relnotes) PiperOrigin-RevId: 874468315 Change-Id: I1deb413ff6db4803f6c2eaf51da80c287ca78183 --- .bazelci/presubmit.yml | 1 + distro/relnotes.bzl | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index 704e6eb1..6ff8d263 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -95,6 +95,7 @@ tasks: - "git commit --allow-empty -m 'Fake init commit'" - "git tag -a 'fake-tag-for-testing' -m 'ignore'" - "git commit --allow-empty -m 'Fake commit message for testing'" + - "git tag -a 'fake-tag-for-testing2' -m 'ignore'" test_targets: - "//test:check_remote_jdk_configs_test" - "//test:check_remote_java_tools_configs_test" diff --git a/distro/relnotes.bzl b/distro/relnotes.bzl index 9d76230a..9c0806af 100644 --- a/distro/relnotes.bzl +++ b/distro/relnotes.bzl @@ -5,7 +5,7 @@ def print_rel_notes(*, name, version, archive): name = name, outs = [name + ".txt"], cmd = """ - last_rel=$$(git describe --tags --abbrev=0) + last_rel=$$(git describe --tags --abbrev=0 HEAD~1) changelog=$$(/usr/bin/git log tags/$$last_rel..HEAD --format=oneline --invert-grep --grep 'ignore-relnotes' --) sha=$$(/usr/bin/sha256sum $(SRCS) | cut -d ' ' -f1) cat > $@ < Date: Tue, 24 Feb 2026 04:33:49 -0800 Subject: [PATCH 412/465] Fix build with Bazel@HEAD Broken by https://github.com/bazelbuild/bazel/pull/27674 (ignore-relnotes) PiperOrigin-RevId: 874542646 Change-Id: I4f1e8c9baae8330d703d6f7eb145e5a3ee2923fc --- java/BUILD | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/java/BUILD b/java/BUILD index b613191c..bcb113a7 100644 --- a/java/BUILD +++ b/java/BUILD @@ -61,6 +61,11 @@ bzl_library( visibility = ["//visibility:public"], ) +exports_files( + ["java_single_jar.bzl"], + visibility = ["//test:__pkg__"], +) + bzl_library( name = "java_single_jar", srcs = ["java_single_jar.bzl"], From 28e7687fc6896e81439d8db71f234d43dcf2bc9f Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 24 Feb 2026 04:57:00 -0800 Subject: [PATCH 413/465] Work around the shallow checkout behavior of `release_ruleset.yaml`[^1] We need the full history of commits and tags to generate release notes. [^1]: While https://github.com/actions/checkout/blob/main/action.yml supports deep checkouts, we can't pass parameters to it unless https://github.com/bazel-contrib/.github/blob/master/.github/workflows/release_ruleset.yaml exposes a parameter for it. (ignore-relnotes) PiperOrigin-RevId: 874550299 Change-Id: I498f09063adaebb0d0709f1cebdfc9b0067215ae --- distro/relnotes.bzl | 1 + 1 file changed, 1 insertion(+) diff --git a/distro/relnotes.bzl b/distro/relnotes.bzl index 9c0806af..e47c3c95 100644 --- a/distro/relnotes.bzl +++ b/distro/relnotes.bzl @@ -5,6 +5,7 @@ def print_rel_notes(*, name, version, archive): name = name, outs = [name + ".txt"], cmd = """ + [ "$$(/usr/bin/git rev-parse --is-shallow-repository)" == "true" ] && /usr/bin/git fetch --unshallow last_rel=$$(git describe --tags --abbrev=0 HEAD~1) changelog=$$(/usr/bin/git log tags/$$last_rel..HEAD --format=oneline --invert-grep --grep 'ignore-relnotes' --) sha=$$(/usr/bin/sha256sum $(SRCS) | cut -d ' ' -f1) From 3a85c8f5c1da1acbcef426af4e2d6536310a36fa Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 26 Feb 2026 13:59:32 -0800 Subject: [PATCH 414/465] Migrate *_getCommandLineFromToolchain Java tests to Starlark PiperOrigin-RevId: 875878855 Change-Id: Idf86d2f3c0529fd1749035b2f22d3c5447fdf632 --- test/java/testutil/javac_action_subject.bzl | 1 + test/java/toolchains/java_toolchain_tests.bzl | 49 +++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/test/java/testutil/javac_action_subject.bzl b/test/java/testutil/javac_action_subject.bzl index ef23812c..5dfbab4a 100644 --- a/test/java/testutil/javac_action_subject.bzl +++ b/test/java/testutil/javac_action_subject.bzl @@ -24,6 +24,7 @@ def _new_javac_action_subject(env, target, output): target = lambda: _create_subject_for_flag("-target", self.parsed_flags, self.meta), xmaxerrs = lambda: _create_subject_for_flag("-Xmaxerrs", self.parsed_flags, self.meta), jar = lambda: _create_subject_for_flag("-jar", self.parsed_flags, self.meta), + executable_file_name = lambda: subjects.str(action_subject.actual.argv[0], self.meta), inputs = action_subject.inputs, argv = action_subject.argv, ) diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index 976bb082..a13e0868 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -2,6 +2,7 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") +load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") load("//java/common:java_semantics.bzl", "semantics") load("//java/toolchains:java_runtime.bzl", "java_runtime") @@ -110,11 +111,59 @@ def _test_jacocorunner_impl(env, target): assert_toolchain.jacocorunner().short_path_equals("{package}/myjacocorunner.jar") +def _test_singlejar_get_command_line(name): + _declare_java_toolchain(name = name) + util.helper_target( + java_binary, + name = name + "/a", + srcs = ["a.java"], + ) + + analysis_test( + name = name, + impl = _test_singlejar_get_command_line_impl, + target = name + "/a", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + # This crashes in earlier Bazel versions where native rules handled deploy jars differently. + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _test_singlejar_get_command_line_impl(env, target): + assert_javac_action = javac_action_subject.of(env, target, "{package}/{name}_deploy.jar") + assert_javac_action.executable_file_name().equals(target.label.package + "/singlejar") + +def _test_genclass_get_command_line(name): + _declare_java_toolchain(name = name) + util.helper_target( + java_library, + name = name + "/a", + srcs = ["a.java"], + javacopts = ["-processor NOSUCH"], + ) + + analysis_test( + name = name, + impl = _test_genclass_get_command_line_impl, + target = name + "/a", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + ) + +def _test_genclass_get_command_line_impl(env, target): + assert_javac_action = javac_action_subject.of(env, target, "{package}/lib{name}-gen.jar") + + assert_javac_action.jar().contains_exactly(["{package}/GenClass_deploy.jar"]) + def java_toolchain_tests(name): test_suite( name = name, tests = [ _test_jacocorunner, _test_javac_gets_options, + _test_singlejar_get_command_line, + _test_genclass_get_command_line, ], ) From 69e858e86a6981f3744efd9f594f9d7b48eda775 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 26 Feb 2026 14:01:04 -0800 Subject: [PATCH 415/465] Migrate JavaToolchain timezone data tests to Starlark. PiperOrigin-RevId: 875879430 Change-Id: Iae180a7ebfb2dd4e3dc42eb23fbcb229c7bb443f --- .../testutil/java_toolchain_info_subject.bzl | 1 + test/java/testutil/javac_action_subject.bzl | 1 + test/java/toolchains/java_toolchain_tests.bzl | 39 +++++++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/test/java/testutil/java_toolchain_info_subject.bzl b/test/java/testutil/java_toolchain_info_subject.bzl index af6934b1..e52302ab 100644 --- a/test/java/testutil/java_toolchain_info_subject.bzl +++ b/test/java/testutil/java_toolchain_info_subject.bzl @@ -6,6 +6,7 @@ load("//java/common:java_common.bzl", "java_common") def _new_java_toolchain_info_subject(info, meta): public = struct( jacocorunner = lambda: subjects.file(info.jacocorunner.executable, meta.derive("jacocorunner.executable")), + timezone_data = lambda: subjects.file(info._timezone_data, meta.derive("_timezone_data")), ) return public diff --git a/test/java/testutil/javac_action_subject.bzl b/test/java/testutil/javac_action_subject.bzl index 5dfbab4a..28d19165 100644 --- a/test/java/testutil/javac_action_subject.bzl +++ b/test/java/testutil/javac_action_subject.bzl @@ -24,6 +24,7 @@ def _new_javac_action_subject(env, target, output): target = lambda: _create_subject_for_flag("-target", self.parsed_flags, self.meta), xmaxerrs = lambda: _create_subject_for_flag("-Xmaxerrs", self.parsed_flags, self.meta), jar = lambda: _create_subject_for_flag("-jar", self.parsed_flags, self.meta), + sources = lambda: _create_subject_for_flag("--sources", self.parsed_flags, self.meta), executable_file_name = lambda: subjects.str(action_subject.actual.argv[0], self.meta), inputs = action_subject.inputs, argv = action_subject.argv, diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index a13e0868..93776476 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -1,6 +1,7 @@ """Tests for the java_toolchain rule""" load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") @@ -157,6 +158,42 @@ def _test_genclass_get_command_line_impl(env, target): assert_javac_action.jar().contains_exactly(["{package}/GenClass_deploy.jar"]) +def _test_timezone_data_is_correct(name): + _declare_java_toolchain(name = name) + + analysis_test( + name = name, + impl = _test_timezone_data_is_correct_impl, + target = name + "/java_toolchain", + ) + +def _test_timezone_data_is_correct_impl(env, target): + java_toolchain_info_subject.from_target(env, target).timezone_data().short_path_equals( + "{package}/tzdata.jar", + ) + +def _test_java_binary_uses_timezone_data(name): + _declare_java_toolchain(name = name) + util.helper_target( + java_binary, + name = name + "/a", + srcs = ["a.java"], + ) + + analysis_test( + name = name, + impl = _test_java_binary_uses_timezone_data_impl, + target = name + "/a", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + ) + +def _test_java_binary_uses_timezone_data_impl(env, target): + assert_action = javac_action_subject.of(env, target, "{package}/{name}.jar") + assert_action.sources().contains("{package}/tzdata.jar") + assert_action.inputs().contains_predicate(matching.file_basename_equals("tzdata.jar")) + def java_toolchain_tests(name): test_suite( name = name, @@ -165,5 +202,7 @@ def java_toolchain_tests(name): _test_javac_gets_options, _test_singlejar_get_command_line, _test_genclass_get_command_line, + _test_timezone_data_is_correct, + _test_java_binary_uses_timezone_data, ], ) From f4481046b84c90596fe21a178ca9123615b3cf4c Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 26 Feb 2026 14:14:24 -0800 Subject: [PATCH 416/465] Migrate ijar unit test to starlark PiperOrigin-RevId: 875885779 Change-Id: Ic86ea8607c6ffd13ebfe3c31c60d31579c2ae099 --- test/java/toolchains/java_toolchain_tests.bzl | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index 93776476..7bcbb38a 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -8,6 +8,7 @@ load("//java:java_library.bzl", "java_library") load("//java/common:java_semantics.bzl", "semantics") load("//java/toolchains:java_runtime.bzl", "java_runtime") load("//java/toolchains:java_toolchain.bzl", "java_toolchain") +load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:java_toolchain_info_subject.bzl", "java_toolchain_info_subject") load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") @@ -194,6 +195,30 @@ def _test_java_binary_uses_timezone_data_impl(env, target): assert_action.sources().contains("{package}/tzdata.jar") assert_action.inputs().contains_predicate(matching.file_basename_equals("tzdata.jar")) +def _test_ijar_get_command_line(name): + _declare_java_toolchain(name = name) + util.helper_target( + java_library, + name = name + "/a", + srcs = ["a.java"], + ) + + analysis_test( + name = name, + impl = _test_ijar_get_command_line_impl, + target = name + "/a", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + "//command_line_option:java_header_compilation": "false", + }, + ) + +def _test_ijar_get_command_line_impl(env, target): + compile_jar = java_info_subject.from_target(env, target).java_outputs().singleton().compile_jar().actual + env.expect.that_target(target).action_generating(compile_jar.short_path).argv().contains( + "{package}/ijar", + ) + def java_toolchain_tests(name): test_suite( name = name, @@ -204,5 +229,6 @@ def java_toolchain_tests(name): _test_genclass_get_command_line, _test_timezone_data_is_correct, _test_java_binary_uses_timezone_data, + _test_ijar_get_command_line, ], ) From 3789f0580fe0a19213ca30683bcf7db9eb419ca5 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 27 Feb 2026 05:02:34 -0800 Subject: [PATCH 417/465] Add a test for `java_binary`'s use of the transitive validation output group Regression test for https://github.com/bazelbuild/rules_java/issues/342 Fixes https://github.com/bazelbuild/rules_java/issues/342 PiperOrigin-RevId: 876195296 Change-Id: Iee5f646fde01dc9c604f3d62187a99f92ba1cadf --- test/java/common/rules/java_binary_tests.bzl | 56 ++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/test/java/common/rules/java_binary_tests.bzl b/test/java/common/rules/java_binary_tests.bzl index 9ddadbd9..10728fb3 100644 --- a/test/java/common/rules/java_binary_tests.bzl +++ b/test/java/common/rules/java_binary_tests.bzl @@ -1,5 +1,6 @@ """Tests for the java_binary rule""" +load("@bazel_features//:features.bzl", "bazel_features") load("@rules_cc//cc:cc_binary.bzl", "cc_binary") load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") @@ -7,6 +8,7 @@ load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") +load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") @@ -194,6 +196,59 @@ def _test_java_compile_only_impl(env, target): "compilation_outputs", ).contains_exactly(["{package}/{name}.jar"]) +def _test_java_binary_can_set_transitive_validation(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + # exit early because this test case would be a loading phase error otherwise + always_passes(name) + return + + env_name = name + "_env" + util.helper_target( + java_library, + name = env_name + "_leaf", + srcs = ["A.java"], + neverlink = True, # add runtime_classpath to validation output group + ) + util.helper_target( + java_binary, + name = env_name, + srcs = ["Env.java"], + deps = [env_name + "_leaf"], + neverlink = True, # add runtime_classpath to validation output group + ) + util.helper_target( + java_binary, + name = name + "_bin", + srcs = ["Bin.java"], + data = [env_name], + deploy_env = [env_name], + create_executable = False, + ) + + analysis_test( + name = name, + impl = _test_java_binary_can_set_transitive_validation_impl, + targets = { + "bin": name + "_bin", + "env": env_name, + }, + # Turn off other validations + config_settings = { + "//command_line_option:experimental_run_android_lint_on_java_rules": False, + "//command_line_option:experimental_one_version_enforcement": "OFF", + }, + ) + +def _test_java_binary_can_set_transitive_validation_impl(env, targets): + # ensure the env target has validation outputs + env.expect.that_target(targets.env).output_group("_validation").contains_at_least([ + "{package}/{name}.jar", + "{package}/lib{name}_leaf.jar", + ]) + + # ensure they don't propagate to `bin` because they're a part of the `deploy_env` + env.expect.that_target(targets.bin).output_group("_validation").contains_exactly([]) + def java_binary_tests(name): test_suite( name = name, @@ -203,5 +258,6 @@ def java_binary_tests(name): _test_java_binary_attributes, _test_java_binary_propagates_direct_native_libraries, _test_java_compile_only, + _test_java_binary_can_set_transitive_validation, ], ) From ec317b1f24d41c169f4d4586c695f8079972c6d7 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 2 Mar 2026 02:55:48 -0800 Subject: [PATCH 418/465] Remove `java_common.add_constraints` PiperOrigin-RevId: 877302145 Change-Id: Ib389d091ec6dea4ef1cf89ed1de1b359aa46da1c --- java/private/java_common.bzl | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/java/private/java_common.bzl b/java/private/java_common.bzl index 6d877d76..174f4e6a 100644 --- a/java/private/java_common.bzl +++ b/java/private/java_common.bzl @@ -29,7 +29,6 @@ load( ":java_info.bzl", "JavaInfo", "JavaPluginInfo", - _java_info_add_constraints = "add_constraints", _java_info_make_non_strict = "make_non_strict", _java_info_merge = "merge", _java_info_set_annotation_processing = "set_annotation_processing", @@ -215,21 +214,6 @@ def _make_non_strict(java_info): def _get_message_bundle_info(): return None if semantics.IS_BAZEL else MessageBundleInfo -def _add_constraints(java_info, constraints = []): - """Returns a copy of the given JavaInfo with the given constraints added. - - Args: - java_info: (JavaInfo) The JavaInfo to enhance - constraints: ([str]) Constraints to add - - Returns: - (JavaInfo) - """ - if semantics.IS_BAZEL: - return java_info - - return _java_info_add_constraints(java_info, constraints = constraints) - def _get_constraints(java_info): """Returns a set of constraints added. @@ -308,7 +292,6 @@ def _make_java_common(): if get_internal_java_common().google_legacy_api_enabled(): methods.update( MessageBundleInfo = _get_message_bundle_info(), # struct field that is None in bazel - add_constraints = _add_constraints, get_constraints = _get_constraints, set_annotation_processing = _set_annotation_processing, java_toolchain_label = _java_toolchain_label, From 26c3467b1861a9b8d73464e5c531c1b3d015b5b1 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 2 Mar 2026 07:08:39 -0800 Subject: [PATCH 419/465] Migrate JavaToolchain header compilation tests to Starlark. PiperOrigin-RevId: 877382139 Change-Id: Ia255bf27ee9041670ac074c8466c8d5dc4336034 --- test/java/toolchains/java_toolchain_tests.bzl | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index 7bcbb38a..07a3ce5c 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -219,6 +219,89 @@ def _test_ijar_get_command_line_impl(env, target): "{package}/ijar", ) +def _test_no_header_compiler_header_compilation_enabled_fails(name): + _declare_java_toolchain( + name = name, + header_compiler = None, + ) + util.helper_target( + java_library, + name = name + "/a", + srcs = ["a.java"], + ) + + analysis_test( + name = name, + impl = _test_no_header_compiler_header_compilation_enabled_fails_impl, + target = name + "/a", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + "//command_line_option:java_header_compilation": "true", + }, + expect_failure = True, + ) + +def _test_no_header_compiler_header_compilation_enabled_fails_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.contains("header compilation was requested but it is not supported by the " + + "current Java toolchain"), + ) + +def _test_no_header_compiler_direct_header_compilation_enabled_fails(name): + _declare_java_toolchain( + name = name, + header_compiler_direct = None, + ) + util.helper_target( + java_library, + name = name + "/a", + srcs = ["a.java"], + ) + + analysis_test( + name = name, + impl = _test_no_header_compiler_direct_header_compilation_enabled_fails_impl, + target = name + "/a", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + "//command_line_option:java_header_compilation": "true", + }, + expect_failure = True, + ) + +def _test_no_header_compiler_direct_header_compilation_enabled_fails_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.contains("header compilation was requested but it is not supported by the " + + "current Java toolchain"), + ) + +def _test_no_header_compiler_header_compilation_disabled_analyzes_successfully(name): + _declare_java_toolchain( + name = name, + header_compiler = None, + ) + util.helper_target( + java_library, + name = name + "/a", + srcs = ["a.java"], + ) + + analysis_test( + name = name, + impl = _test_no_header_compiler_header_compilation_disabled_analyzes_successfully_impl, + target = name + "/a", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + "//command_line_option:java_header_compilation": "false", + }, + ) + +def _test_no_header_compiler_header_compilation_disabled_analyzes_successfully_impl( + env, # @unused + target): # @unused + # Implicitly succeeds. + pass + def java_toolchain_tests(name): test_suite( name = name, @@ -230,5 +313,8 @@ def java_toolchain_tests(name): _test_timezone_data_is_correct, _test_java_binary_uses_timezone_data, _test_ijar_get_command_line, + _test_no_header_compiler_header_compilation_enabled_fails, + _test_no_header_compiler_direct_header_compilation_enabled_fails, + _test_no_header_compiler_header_compilation_disabled_analyzes_successfully, ], ) From 07ba1c0d36508926099ec1e3e1f44ea1f602b4da Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 2 Mar 2026 07:17:21 -0800 Subject: [PATCH 420/465] Migrate JavaToolchainProvider tests to Starlark. PiperOrigin-RevId: 877385412 Change-Id: I1095c37592ce0ee1d4847cec8893219df5ff5a9c --- .../testutil/java_toolchain_info_subject.bzl | 2 ++ test/java/toolchains/java_toolchain_tests.bzl | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/test/java/testutil/java_toolchain_info_subject.bzl b/test/java/testutil/java_toolchain_info_subject.bzl index e52302ab..a3304f42 100644 --- a/test/java/testutil/java_toolchain_info_subject.bzl +++ b/test/java/testutil/java_toolchain_info_subject.bzl @@ -7,6 +7,8 @@ def _new_java_toolchain_info_subject(info, meta): public = struct( jacocorunner = lambda: subjects.file(info.jacocorunner.executable, meta.derive("jacocorunner.executable")), timezone_data = lambda: subjects.file(info._timezone_data, meta.derive("_timezone_data")), + header_compiler_builtin_processors = lambda: subjects.collection(info._header_compiler_builtin_processors.to_list(), meta.derive("_header_compiler_builtin_processors")), + reduced_classpath_incompatible_processors = lambda: subjects.collection(info._reduced_classpath_incompatible_processors.to_list(), meta.derive("_reduced_classpath_incompatible_processors")), ) return public diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index 07a3ce5c..1beca093 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -302,6 +302,40 @@ def _test_no_header_compiler_header_compilation_disabled_analyzes_successfully_i # Implicitly succeeds. pass +def _test_header_compiler_builtin_processors(name): + util.helper_target( + java_toolchain, + name = name + "/java_toolchain", + header_compiler_builtin_processors = ["BuiltinProc1", "BuiltinProc2"], + singlejar = "singlejar", + ) + + analysis_test( + name = name, + impl = _test_header_compiler_builtin_processors_impl, + target = name + "/java_toolchain", + ) + +def _test_header_compiler_builtin_processors_impl(env, target): + java_toolchain_info_subject.from_target(env, target).header_compiler_builtin_processors().contains_exactly(["BuiltinProc1", "BuiltinProc2"]) + +def _test_reduced_classpath_incompatible_processors(name): + util.helper_target( + java_toolchain, + name = name + "/java_toolchain", + reduced_classpath_incompatible_processors = ["IncompatibleProc1", "IncompatibleProc2"], + singlejar = "singlejar", + ) + + analysis_test( + name = name, + impl = _test_reduced_classpath_incompatible_processors_impl, + target = name + "/java_toolchain", + ) + +def _test_reduced_classpath_incompatible_processors_impl(env, target): + java_toolchain_info_subject.from_target(env, target).reduced_classpath_incompatible_processors().contains_exactly(["IncompatibleProc1", "IncompatibleProc2"]) + def java_toolchain_tests(name): test_suite( name = name, @@ -316,5 +350,7 @@ def java_toolchain_tests(name): _test_no_header_compiler_header_compilation_enabled_fails, _test_no_header_compiler_direct_header_compilation_enabled_fails, _test_no_header_compiler_header_compilation_disabled_analyzes_successfully, + _test_header_compiler_builtin_processors, + _test_reduced_classpath_incompatible_processors, ], ) From e7b4e1d1c956ea550f51840537d682cc10149853 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 2 Mar 2026 07:36:06 -0800 Subject: [PATCH 421/465] Move javaToolchain_* tests to starlark. PiperOrigin-RevId: 877391792 Change-Id: I4a260a12861387cf5cbc5f229fcd7294c1d4c824 --- test/java/toolchains/java_toolchain_tests.bzl | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index 1beca093..3019a667 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -336,6 +336,85 @@ def _test_reduced_classpath_incompatible_processors(name): def _test_reduced_classpath_incompatible_processors_impl(env, target): java_toolchain_info_subject.from_target(env, target).reduced_classpath_incompatible_processors().contains_exactly(["IncompatibleProc1", "IncompatibleProc2"]) +def _test_location_expansion_in_jvm_opts(name): + _declare_java_toolchain( + name = name, + tools = [name + "/jsr305.jar", name + "/javac"], + jvm_opts = [ + "--patch-module=jdk.compiler=$(location " + name + "/javac)", + "--patch-module=java.xml.ws.annotation=$(location " + name + "/jsr305.jar)", + ], + javabuilder_jvm_opts = ["-Xshare:auto"], + ) + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["a.java"], + ) + + analysis_test( + name = name, + impl = _test_location_expansion_in_jvm_opts_impl, + target = name + "/lib", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + ) + +def _test_location_expansion_in_jvm_opts_impl(env, target): + assert_javac_action = env.expect.that_target(target).action_generating("{package}/lib{name}.jar") + assert_javac_action.argv().contains("--patch-module=jdk.compiler={package}/{test_name}/javac") + assert_javac_action.argv().contains("--patch-module=java.xml.ws.annotation={package}/{test_name}/jsr305.jar") + assert_javac_action.argv().contains("-Xshare:auto") + assert_javac_action.inputs().contains("{package}/{test_name}/jsr305.jar") + +def _test_location_expansion_with_multiple_artifacts_fails(name): + util.helper_target( + native.filegroup, + name = name + "/fg", + srcs = ["one", "two"], + ) + _declare_java_toolchain( + name = name, + tools = [name + "/fg"], + javabuilder_jvm_opts = ["$(location " + name + "/fg)"], + ) + + analysis_test( + name = name, + impl = _test_location_expansion_with_multiple_artifacts_fails_impl, + target = name + "/java_toolchain", + expect_failure = True, + ) + +def _test_location_expansion_with_multiple_artifacts_fails_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.contains("$(location) expression expands to more than one file"), + ) + +def _test_timezone_data_with_multiple_artifacts_fails(name): + util.helper_target( + native.filegroup, + name = name + "/fg", + srcs = ["one", "two"], + ) + _declare_java_toolchain( + name = name, + timezone_data = name + "/fg", + ) + + analysis_test( + name = name, + impl = _test_timezone_data_with_multiple_artifacts_fails_impl, + target = name + "/java_toolchain", + expect_failure = True, + ) + +def _test_timezone_data_with_multiple_artifacts_fails_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.contains("must produce a single file"), + ) + def java_toolchain_tests(name): test_suite( name = name, @@ -352,5 +431,8 @@ def java_toolchain_tests(name): _test_no_header_compiler_header_compilation_disabled_analyzes_successfully, _test_header_compiler_builtin_processors, _test_reduced_classpath_incompatible_processors, + _test_location_expansion_in_jvm_opts, + _test_location_expansion_with_multiple_artifacts_fails, + _test_timezone_data_with_multiple_artifacts_fails, ], ) From 617f16791f16889ca73db9a526ec83022c03385d Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 3 Mar 2026 07:17:21 -0800 Subject: [PATCH 422/465] Migrate JavaToolchainTest cases to Starlark analysis tests. PiperOrigin-RevId: 877933571 Change-Id: I271712beef84d4d0b1e5b1b2646f5d375b5ae7b7 --- MODULE.bazel | 6 +- test/java/testutil/javac_action_subject.bzl | 11 +- .../testutil/javac_action_subject_tests.bzl | 20 ++- test/java/toolchains/java_toolchain_tests.bzl | 129 +++++++++++++++++- 4 files changed, 145 insertions(+), 21 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index de8fe111..204b8e88 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -131,9 +131,9 @@ bazel_dep(name = "rules_shell", version = "0.2.0", dev_dependency = True) bazel_dep(name = "rules_testing", dev_dependency = True) archive_override( module_name = "rules_testing", - integrity = "sha256-TqwTCQnzt/hRKQtdJ7d8ebtZ8+I8IMgmWiEjOKvo6mI=", - strip_prefix = "rules_testing-f8e869d452507fa4a59748c9d69cfab63ec9385a", - urls = ["https://github.com/bazelbuild/rules_testing/archive/f8e869d452507fa4a59748c9d69cfab63ec9385a.tar.gz"], + integrity = "sha256-d/94Ix5IoGXk9rP1HjYKxPMH8ccwX5b1Qxs8BKg4WRg=", + strip_prefix = "rules_testing-ac97ba507116056cd489161b5e99dd8014685adc", + urls = ["https://github.com/bazelbuild/rules_testing/archive/ac97ba507116056cd489161b5e99dd8014685adc.tar.gz"], ) test_repositories = use_extension("//test:repositories.bzl", "test_repositories_ext", dev_dependency = True) diff --git a/test/java/testutil/javac_action_subject.bzl b/test/java/testutil/javac_action_subject.bzl index 28d19165..ed6e9fa2 100644 --- a/test/java/testutil/javac_action_subject.bzl +++ b/test/java/testutil/javac_action_subject.bzl @@ -20,9 +20,7 @@ def _new_javac_action_subject(env, target, output): public = struct( direct_dependencies = lambda: _create_subject_for_flag("--direct_dependencies", self.parsed_flags, self.meta), - source = lambda: _create_subject_for_flag("-source", self.parsed_flags, self.meta), - target = lambda: _create_subject_for_flag("-target", self.parsed_flags, self.meta), - xmaxerrs = lambda: _create_subject_for_flag("-Xmaxerrs", self.parsed_flags, self.meta), + javacopts = lambda: _create_subject_for_flag("--javacopts", self.parsed_flags, self.meta), jar = lambda: _create_subject_for_flag("-jar", self.parsed_flags, self.meta), sources = lambda: _create_subject_for_flag("--sources", self.parsed_flags, self.meta), executable_file_name = lambda: subjects.str(action_subject.actual.argv[0], self.meta), @@ -37,7 +35,12 @@ def _parse_flags(argv): for idx, arg in enumerate(argv): if idx == 0: continue # java command - if arg.startswith("-"): + + if current_flag_name == "--javacopts" and arg == "--": + current_flag_name = None + continue + + if arg.startswith("-") and current_flag_name != "--javacopts": if "=" in arg: parts = arg.split("=", 1) flag_values.setdefault(parts[0], []).append(parts[1]) diff --git a/test/java/testutil/javac_action_subject_tests.bzl b/test/java/testutil/javac_action_subject_tests.bzl index eba3f76b..c1e577be 100644 --- a/test/java/testutil/javac_action_subject_tests.bzl +++ b/test/java/testutil/javac_action_subject_tests.bzl @@ -18,6 +18,7 @@ def _parse_flags_test_impl(ctx): "JavaBuilder_deploy.jar", "--output", "blaze-out/k8/bin/pkg/libfoo.jar", + "--javacopts", "-source", "21", "-target", @@ -49,13 +50,18 @@ def _parse_flags_test_impl(ctx): ], "-jar": ["JavaBuilder_deploy.jar"], "--output": ["blaze-out/k8/bin/pkg/libfoo.jar"], - "-source": ["21"], - "-target": ["17"], - "-g": [], - "-parameters": [], - "-sourcepath": [":"], - "-Xmaxerrs": ["123"], - "--": [], + "--javacopts": [ + "-source", + "21", + "-target", + "17", + "-g", + "-parameters", + "-sourcepath", + ":", + "-Xmaxerrs", + "123", + ], "--strict_java_deps": ["ERROR"], "--classpath": ["pkg/bar-hjar.jar", "other/pkg/baz.jar"], }, flags) diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index 3019a667..f685fddd 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -1,10 +1,11 @@ """Tests for the java_toolchain rule""" load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") -load("@rules_testing//lib:truth.bzl", "matching") +load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") +load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_semantics.bzl", "semantics") load("//java/toolchains:java_runtime.bzl", "java_runtime") load("//java/toolchains:java_toolchain.bzl", "java_toolchain") @@ -83,15 +84,19 @@ def _test_javac_gets_options(name): def _test_javac_gets_options_impl(env, targets): assert_javac_action = javac_action_subject.of(env, targets.a, "{package}/lib{name}.jar") - assert_javac_action.source().contains_exactly(["6"]) - assert_javac_action.target().contains_exactly(["6"]) - assert_javac_action.xmaxerrs().contains_exactly(["500"]) + assert_javac_action.javacopts().contains_at_least([ + "-source", + "6", + "-target", + "6", + "-Xlint:toto", + "-Xmaxerrs", + "500", + ]) assert_javac_action.jar().contains_exactly(["{package}/JavaBuilder_deploy.jar"]) assert_javac_action.inputs().contains("{package}/rt.jar") - assert_argv = assert_javac_action.argv() - assert_argv.contains("-Xlint:toto") - assert_argv.not_contains("-g") + assert_javac_action.javacopts().not_contains("-g") assert_header_action = javac_action_subject.of(env, targets.b, "{package}/lib{name}-hjar.jar") assert_header_action.argv().contains("{package}/turbine_direct") @@ -415,6 +420,113 @@ def _test_timezone_data_with_multiple_artifacts_fails_impl(env, target): matching.contains("must produce a single file"), ) +def _test_java_compile_action_target_gets_javacopts_from_toolchain(name): + _declare_java_toolchain( + name = name, + javacopts = ["-XDtoolchainJavacFlag"], + ) + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["a.java"], + ) + analysis_test( + name = name, + impl = _test_java_compile_action_target_gets_javacopts_from_toolchain_impl, + target = name + "/lib", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + "//command_line_option:javacopt": ["-XDcommandLineJavacFlag"], + "//command_line_option:host_javacopt": ["-XDhostCommandLineJavacFlag"], + }, + ) + +def _test_java_compile_action_target_gets_javacopts_from_toolchain_impl(env, target): + assert_javacopts = javac_action_subject.of(env, target, "{package}/lib{name}.jar").javacopts() + assert_javacopts.contains_exactly([ + "-source", + "6", + "-target", + "6", + "-Xlint:toto", + "-XDtoolchainJavacFlag", + "-XDcommandLineJavacFlag", + ]) + +def _test_java_compile_action_exec_gets_javacopts_from_toolchain(name): + _declare_java_toolchain( + name = name, + javacopts = ["-XDtoolchainJavacFlag"], + ) + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["a.java"], + ) + util.helper_target( + util.force_exec_config, + name = name + "/exec_lib", + tools = [name + "/lib"], + ) + analysis_test( + name = name, + impl = _test_java_compile_action_exec_gets_javacopts_from_toolchain_impl, + target = name + "/exec_lib", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + "//command_line_option:javacopt": ["-XDcommandLineJavacFlag"], + "//command_line_option:host_javacopt": ["-XDhostCommandLineJavacFlag"], + }, + ) + +def _test_java_compile_action_exec_gets_javacopts_from_toolchain_impl(env, target): + lib = env.expect.that_target(target).attr("tools", factory = subjects.collection).actual[0] + assert_javacopts = javac_action_subject.of(env, lib, "{package}/lib{name}.jar").javacopts() + assert_javacopts.contains_exactly([ + "-source", + "6", + "-target", + "6", + "-Xlint:toto", + "-XDtoolchainJavacFlag", + "-XDhostCommandLineJavacFlag", + ]) + +def _test_java_compile_action_uses_tool_specific_jvm_opts(name): + _declare_java_toolchain( + name = name, + jvm_opts = ["-Xbase"], + javabuilder_jvm_opts = ["-DjavabuilderFlag=1"], + turbine_jvm_opts = ["-DturbineFlag=1"], + ) + util.helper_target( + java_plugin, + name = name + "/plugin", + processor_class = "Proc", + generates_api = True, + ) + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["a.java"], + plugins = [name + "/plugin"], + ) + analysis_test( + name = name, + impl = _test_java_compile_action_uses_tool_specific_jvm_opts_impl, + target = name + "/lib", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + ) + +def _test_java_compile_action_uses_tool_specific_jvm_opts_impl(env, target): + javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + javac_action.argv().contains("-DjavabuilderFlag=1") + + header_action = env.expect.that_target(target).action_generating("{package}/lib{name}-hjar.jar") + header_action.argv().contains("-DturbineFlag=1") + def java_toolchain_tests(name): test_suite( name = name, @@ -434,5 +546,8 @@ def java_toolchain_tests(name): _test_location_expansion_in_jvm_opts, _test_location_expansion_with_multiple_artifacts_fails, _test_timezone_data_with_multiple_artifacts_fails, + _test_java_compile_action_target_gets_javacopts_from_toolchain, + _test_java_compile_action_exec_gets_javacopts_from_toolchain, + _test_java_compile_action_uses_tool_specific_jvm_opts, ], ) From 85d5bf8293301a58933de3e1119ad99604b5873b Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 3 Mar 2026 07:38:27 -0800 Subject: [PATCH 423/465] Move JavaToolchain location expansion test to Starlark. PiperOrigin-RevId: 877941010 Change-Id: I0709e76b1eeea9d572256b921ab27c98019e49eb --- .../testutil/java_toolchain_info_subject.bzl | 14 +++++++ test/java/toolchains/java_toolchain_tests.bzl | 40 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/test/java/testutil/java_toolchain_info_subject.bzl b/test/java/testutil/java_toolchain_info_subject.bzl index a3304f42..2757bfce 100644 --- a/test/java/testutil/java_toolchain_info_subject.bzl +++ b/test/java/testutil/java_toolchain_info_subject.bzl @@ -3,12 +3,26 @@ load("@rules_testing//lib:truth.bzl", "subjects") load("//java/common:java_common.bzl", "java_common") +def _new_java_builder_subject(tool_info, meta): + return subjects.struct( + struct( + data = [f.path for f in tool_info.data.to_list()], + jvm_opts = tool_info.jvm_opts.to_list(), + ), + meta = meta, + attrs = { + "data": lambda values, *, meta: subjects.collection(values, meta = meta, format = True), + "jvm_opts": lambda values, *, meta: subjects.collection(values, meta = meta, format = True), + }, + ) + def _new_java_toolchain_info_subject(info, meta): public = struct( jacocorunner = lambda: subjects.file(info.jacocorunner.executable, meta.derive("jacocorunner.executable")), timezone_data = lambda: subjects.file(info._timezone_data, meta.derive("_timezone_data")), header_compiler_builtin_processors = lambda: subjects.collection(info._header_compiler_builtin_processors.to_list(), meta.derive("_header_compiler_builtin_processors")), reduced_classpath_incompatible_processors = lambda: subjects.collection(info._reduced_classpath_incompatible_processors.to_list(), meta.derive("_reduced_classpath_incompatible_processors")), + javabuilder = lambda: _new_java_builder_subject(info._javabuilder, meta.derive("_javabuilder")), ) return public diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index f685fddd..9ca28577 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -527,6 +527,45 @@ def _test_java_compile_action_uses_tool_specific_jvm_opts_impl(env, target): header_action = env.expect.that_target(target).action_generating("{package}/lib{name}-hjar.jar") header_action.argv().contains("-DturbineFlag=1") +def _test_javabuilder_location_expansion_with_multiple_artifacts(name): + util.helper_target( + native.filegroup, + name = name + "/fg1", + srcs = ["a", "b"], + ) + util.helper_target( + native.filegroup, + name = name + "/fg2", + srcs = ["c", "d"], + ) + _declare_java_toolchain( + name = name, + javabuilder_data = [name + "/fg1", name + "/fg2"], + javabuilder_jvm_opts = [ + "$(locations " + name + "/fg1)", + "$(locations " + name + "/fg2)", + ], + ) + + analysis_test( + name = name, + impl = _test_javabuilder_location_expansion_with_multiple_artifacts_impl, + target = name + "/java_toolchain", + ) + +def _test_javabuilder_location_expansion_with_multiple_artifacts_impl(env, target): + assert_javabuilder = java_toolchain_info_subject.from_target(env, target).javabuilder() + assert_javabuilder.data().contains_exactly([ + "{package}/a", + "{package}/b", + "{package}/c", + "{package}/d", + ]).in_order() + assert_javabuilder.jvm_opts().contains_exactly([ + "{package}/a {package}/b", + "{package}/c {package}/d", + ]).in_order() + def java_toolchain_tests(name): test_suite( name = name, @@ -549,5 +588,6 @@ def java_toolchain_tests(name): _test_java_compile_action_target_gets_javacopts_from_toolchain, _test_java_compile_action_exec_gets_javacopts_from_toolchain, _test_java_compile_action_uses_tool_specific_jvm_opts, + _test_javabuilder_location_expansion_with_multiple_artifacts, ], ) From f64dab7c5a4e424ff86d33ef83973618966b84bc Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 3 Mar 2026 10:17:29 -0800 Subject: [PATCH 424/465] Add a test for deploy jars with custom singlejar PiperOrigin-RevId: 878010346 Change-Id: I44216adca0c605f3bcadb5030f3524f144ca7d23 --- test/java/common/rules/BUILD | 3 + .../rules/deploy_archive_builder_tests.bzl | 92 +++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 test/java/common/rules/deploy_archive_builder_tests.bzl diff --git a/test/java/common/rules/BUILD b/test/java/common/rules/BUILD index 2311a3f2..cc2cd337 100644 --- a/test/java/common/rules/BUILD +++ b/test/java/common/rules/BUILD @@ -1,3 +1,4 @@ +load(":deploy_archive_builder_tests.bzl", "deploy_archive_builder_test_suite") load(":java_binary_tests.bzl", "java_binary_tests") load(":java_import_tests.bzl", "java_import_tests") load(":java_library_tests.bzl", "java_library_tests") @@ -7,6 +8,8 @@ load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") package(default_applicable_licenses = ["@rules_java//:license"]) +deploy_archive_builder_test_suite(name = "deploy_archive_builder_tests") + merge_attrs_test_suite(name = "merge_attrs_tests") java_binary_tests(name = "java_binary_tests") diff --git a/test/java/common/rules/deploy_archive_builder_tests.bzl b/test/java/common/rules/deploy_archive_builder_tests.bzl new file mode 100644 index 00000000..32e75e91 --- /dev/null +++ b/test/java/common/rules/deploy_archive_builder_tests.bzl @@ -0,0 +1,92 @@ +"""Tests for DeployArchiveBuilder.""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_binary.bzl", "java_binary") +load("//java/common:java_semantics.bzl", "semantics") +load("//java/toolchains:java_runtime.bzl", "java_runtime") +load("//java/toolchains:java_toolchain.bzl", "java_toolchain") + +def _declare_java_toolchain(*, name, **kwargs): + java_runtime_name = name + "/runtime" + util.helper_target( + java_runtime, + name = java_runtime_name, + ) + toolchain_attrs = { + "source_version": "6", + "target_version": "6", + "bootclasspath": ["rt.jar"], + "xlint": ["toto"], + "javacopts": ["-Xmaxerrs 500"], + "compatible_javacopts": { + "android": ["-XDandroidCompatible"], + "testonly": ["-XDtestOnly"], + "public_visibility": ["-XDpublicVisibility"], + }, + "tools": [":javac_canary.jar"], + "javabuilder": ":JavaBuilder_deploy.jar", + "header_compiler": ":turbine_canary_deploy.jar", + "header_compiler_direct": ":turbine_direct", + "singlejar": "singlejar", + "ijar": "ijar", + "genclass": "GenClass_deploy.jar", + "timezone_data": "tzdata.jar", + "header_compiler_builtin_processors": ["BuiltinProc1", "BuiltinProc2"], + "reduced_classpath_incompatible_processors": [ + "IncompatibleProc1", + "IncompatibleProc2", + ], + "java_runtime": java_runtime_name, + } + toolchain_attrs.update(kwargs) + util.helper_target( + java_toolchain, + name = name + "/java_toolchain", + **toolchain_attrs + ) + util.helper_target( + native.toolchain, + name = name + "/toolchain", + toolchain = name + "/java_toolchain", + toolchain_type = semantics.JAVA_TOOLCHAIN_TYPE, + ) + +def _test_custom_singlejar(name): + _declare_java_toolchain(name = name) + + util.helper_target( + java_binary, + name = name + "/binary", + srcs = [name + "/main.java"], + main_class = "com.google.test.main", + ) + + analysis_test( + name = name, + impl = _test_custom_singlejar_impl, + target = name + "/binary", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + # Starlark rules are only used with Bazel 8 onwards. + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _test_custom_singlejar_impl(env, target): + action = env.expect.that_target(target).action_named("JavaDeployJar") + action.inputs().contains_at_least_predicates( + [ + matching.file_path_matches("*/test_custom_singlejar/binary.jar"), + ], + ) + +def deploy_archive_builder_test_suite(name): + """Test suite for java_binary deploy archive.""" + test_suite( + name = name, + tests = [ + _test_custom_singlejar, + ], + ) From 21e567b1543ce5af9b1654a167a69d7aabb3d0a9 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 3 Mar 2026 12:00:43 -0800 Subject: [PATCH 425/465] Remove JavaToolchainTest and add a Starlark test for java_common toolchain type enforcement. PiperOrigin-RevId: 878061671 Change-Id: Ie25a277183df5801c9f4909bbdc3f9ef3d20eb62 --- test/java/toolchains/java_toolchain_tests.bzl | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index 9ca28577..7c95d0e3 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -6,6 +6,7 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") +load("//java/common:java_common.bzl", "java_common") load("//java/common:java_semantics.bzl", "semantics") load("//java/toolchains:java_runtime.bzl", "java_runtime") load("//java/toolchains:java_toolchain.bzl", "java_toolchain") @@ -566,6 +567,34 @@ def _test_javabuilder_location_expansion_with_multiple_artifacts_impl(env, targe "{package}/c {package}/d", ]).in_order() +def _no_toolchain_rule_impl(ctx): + java_common.pack_sources( + ctx.actions, + output_source_jar = "output_source_jar", + java_toolchain = "java_toolchain", + ) + +_no_toolchain_rule = rule( + implementation = _no_toolchain_rule_impl, +) + +def _test_java_common_without_toolchain_type_fails(name): + util.helper_target( + _no_toolchain_rule, + name = name + "/no_toolchain", + ) + analysis_test( + name = name, + impl = _test_java_common_without_toolchain_type_fails_impl, + target = name + "/no_toolchain", + expect_failure = True, + ) + +def _test_java_common_without_toolchain_type_fails_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("must declare *tools/jdk:toolchain_type' toolchain in order to use java_common"), + ) + def java_toolchain_tests(name): test_suite( name = name, @@ -589,5 +618,6 @@ def java_toolchain_tests(name): _test_java_compile_action_exec_gets_javacopts_from_toolchain, _test_java_compile_action_uses_tool_specific_jvm_opts, _test_javabuilder_location_expansion_with_multiple_artifacts, + _test_java_common_without_toolchain_type_fails, ], ) From 27163ac1f0380ced234e0378456b89bf21418c2d Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 4 Mar 2026 09:42:56 -0800 Subject: [PATCH 426/465] Starlarkify coverage, annotation processing tests. PiperOrigin-RevId: 878534391 Change-Id: I72afb6f8e85dc85cdbede772efccc52d11669815 --- test/java/common/java_common_tests.bzl | 92 +++++++++++++++++++++ test/java/testutil/javac_action_subject.bzl | 1 + test/java/testutil/rules/custom_library.bzl | 2 + 3 files changed, 95 insertions(+) diff --git a/test/java/common/java_common_tests.bzl b/test/java/common/java_common_tests.bzl index 2eaf00de..c35f8388 100644 --- a/test/java/common/java_common_tests.bzl +++ b/test/java/common/java_common_tests.bzl @@ -1,5 +1,6 @@ """Tests for java_common APIs""" +load("@rules_cc//cc:cc_binary.bzl", "cc_binary") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") @@ -11,6 +12,7 @@ load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") load("//test/java/testutil:artifact_closure.bzl", "artifact_closure") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") load("//test/java/testutil:rules/custom_library.bzl", "custom_library") load("//test/java/testutil:rules/custom_library_extended_compile_jdeps.bzl", "CompileJdepsInfo", "custom_library_extended_jdeps") load("//test/java/testutil:rules/custom_library_with_additional_inputs.bzl", "custom_library_with_additional_inputs") @@ -788,6 +790,94 @@ def _test_compile_strict_deps_enum_impl(env, target): matching.str_matches("invalid value for strict_deps: FOO"), ) +def _test_java_library_collects_coverage_dependencies_from_resources(name): + util.helper_target( + cc_binary, + name = name + "/lib/jni.so", + srcs = [name + "/lib/jni.cc"], + linkshared = 1, + features = ["-supports_pic"], + ) + util.helper_target( + java_library, + name = name + "/lib", + resources = [name + "/lib/jni.so"], + ) + + analysis_test( + name = name, + impl = _test_java_library_collects_coverage_dependencies_from_resources_impl, + target = name + "/lib", + config_settings = { + "//command_line_option:collect_code_coverage": "true", + "//command_line_option:instrumentation_filter": "//test/...", + }, + ) + +def _test_java_library_collects_coverage_dependencies_from_resources_impl(env, target): + env.expect.that_target(target).provider( + InstrumentedFilesInfo, + ).instrumented_files().contains_exactly(["{package}/{name}/jni.cc"]) + + env.expect.that_target(target).provider( + InstrumentedFilesInfo, + ).metadata_files().contains_exactly(["{package}/_objs/{name}/jni.so/jni.gcno"]) + +def _test_skip_annotation_processing(name): + util.helper_target( + java_plugin, + name = name + "/processor", + srcs = [name + "/processor.java"], + data = [name + "/processor_data.txt"], + generates_api = True, # so Turbine would normally run it + processor_class = "Foo", + ) + util.helper_target( + java_library, + name = name + "/exports_processor", + exported_plugins = [":" + name + "/processor"], + ) + util.helper_target( + custom_library, + name = name + "/custom", + srcs = [name + "/custom.java"], + plugins = [":" + name + "/processor"], + deps = [":" + name + "/exports_processor"], + enable_annotation_processing = False, + ) + util.helper_target( + java_library, + name = name + "/custom_noproc", + srcs = [name + "/custom.java"], + ) + + analysis_test( + name = name, + impl = _test_skip_annotation_processing_impl, + targets = { + "custom": ":" + name + "/custom", + "custom_noproc": ":" + name + "/custom_noproc", + }, + ) + +def _test_skip_annotation_processing_impl(env, targets): + javac_action = javac_action_subject.of(env, targets.custom, "{package}/lib{name}.jar") + + javac_action.mnemonic().equals("Javac") + javac_action.argv().not_contains("--processors") + javac_action.argv().contains("--processorpath") + javac_action.inputs().contains_at_least_predicates([ + matching.file_basename_equals("processor_data.txt"), + ]) + + turbine_action = javac_action_subject.of(env, targets.custom, "{package}/lib{name}-hjar.jar") + turbine_action.mnemonic().equals("JavacTurbine") + turbine_action.argv().not_contains("--processors") + + turbine_action_noproc = javac_action_subject.of(env, targets.custom_noproc, "{package}/lib{name}-hjar.jar") + turbine_action_noproc.mnemonic().equals("Turbine") + turbine_action_noproc.argv().not_contains("--processors") + def java_common_tests(name): test_suite( name = name, @@ -817,5 +907,7 @@ def java_common_tests(name): _test_compile_neverlink, _test_compile_strict_deps_case_sensitivity, _test_compile_strict_deps_enum, + _test_java_library_collects_coverage_dependencies_from_resources, + _test_skip_annotation_processing, ], ) diff --git a/test/java/testutil/javac_action_subject.bzl b/test/java/testutil/javac_action_subject.bzl index ed6e9fa2..3a105b70 100644 --- a/test/java/testutil/javac_action_subject.bzl +++ b/test/java/testutil/javac_action_subject.bzl @@ -26,6 +26,7 @@ def _new_javac_action_subject(env, target, output): executable_file_name = lambda: subjects.str(action_subject.actual.argv[0], self.meta), inputs = action_subject.inputs, argv = action_subject.argv, + mnemonic = action_subject.mnemonic, ) return public diff --git a/test/java/testutil/rules/custom_library.bzl b/test/java/testutil/rules/custom_library.bzl index 024c05d9..ec3699ce 100644 --- a/test/java/testutil/rules/custom_library.bzl +++ b/test/java/testutil/rules/custom_library.bzl @@ -21,6 +21,7 @@ def _custom_library_impl(ctx): plugins = [p[JavaPluginInfo] for p in ctx.attr.plugins], javac_opts = ctx.attr.javac_opts, java_toolchain = semantics.find_java_toolchain(ctx), + enable_annotation_processing = ctx.attr.enable_annotation_processing, ) return [DefaultInfo(files = depset([output_jar])), compilation_provider] @@ -35,6 +36,7 @@ custom_library = rule( "plugins": attr.label_list(), "javac_opts": attr.string_list(), "neverlink": attr.bool(), + "enable_annotation_processing": attr.bool(default = True), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], fragments = ["java"], From abda3d1472251220b30c070bc82054bd18526231 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 4 Mar 2026 11:56:56 -0800 Subject: [PATCH 427/465] Test that --experimental_strict_java_deps is passed down to the javac action PiperOrigin-RevId: 878599080 Change-Id: I0046d89faf8edecdacdddcbc2648aafc8179f71b --- test/java/common/rules/java_library_tests.bzl | 58 ++++++++++++++++--- test/java/testutil/javac_action_subject.bzl | 6 +- 2 files changed, 54 insertions(+), 10 deletions(-) diff --git a/test/java/common/rules/java_library_tests.bzl b/test/java/common/rules/java_library_tests.bzl index c6bb282a..64e17435 100644 --- a/test/java/common/rules/java_library_tests.bzl +++ b/test/java/common/rules/java_library_tests.bzl @@ -1,5 +1,6 @@ """Tests for the java_library rule""" +load("@bazel_features//:features.bzl", "bazel_features") load("@rules_cc//cc:cc_binary.bzl", "cc_binary") load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") @@ -9,6 +10,7 @@ load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") load("//test/java/testutil:rules/wrap_java_info.bzl", "JavaInfoWrappingInfo", "java_info_wrapping_rule") @@ -309,15 +311,55 @@ def _test_exposes_native_library_info_impl(env, target): assert_lib.dynamic_library().basename().contains("mynativedep") +def _test_strict_java_deps(name, strict_java_deps): + util.helper_target( + java_library, + name = name + "/jl", + srcs = ["A.java"], + ) + + analysis_test( + name = name, + impl = _test_strict_java_deps_impl, + target = name + "/jl", + config_settings = {"//command_line_option:experimental_strict_java_deps": strict_java_deps}, + attrs = {"expected_strict_java_deps": attr.string()}, + attr_values = {"expected_strict_java_deps": strict_java_deps}, + ) + +def _test_strict_java_deps_impl(env, target): + # Note that if --experimental_strict_java_deps=OFF, we may not set --strict_java_deps in the + # javac action's argv at all; the "OFF" value (which is equivalent to an unset flag) in that + # case is injected by javac_action_subject for convenience and canonicalization. + expect_that_javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + expect_that_javac_action.strict_java_deps().contains_exactly([env.ctx.attr.expected_strict_java_deps]) + +def _test_strict_java_deps_off(name): + _test_strict_java_deps(name, "OFF") + +def _test_strict_java_deps_warn(name): + _test_strict_java_deps(name, "WARN") + +def _test_strict_java_deps_error(name): + _test_strict_java_deps(name, "ERROR") + def java_library_tests(name): + tests = [ + _test_exposes_plugins, + _test_exposes_java_info, + _test_java_info_propagation, + _test_java_library_attributes, + _test_propagates_direct_native_libraries, + _test_exposes_native_library_info, + ] + if bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + tests += [ + _test_strict_java_deps_off, + _test_strict_java_deps_warn, + _test_strict_java_deps_error, + ] + test_suite( name = name, - tests = [ - _test_exposes_plugins, - _test_exposes_java_info, - _test_java_info_propagation, - _test_java_library_attributes, - _test_propagates_direct_native_libraries, - _test_exposes_native_library_info, - ], + tests = tests, ) diff --git a/test/java/testutil/javac_action_subject.bzl b/test/java/testutil/javac_action_subject.bzl index 3a105b70..beb0ecbc 100644 --- a/test/java/testutil/javac_action_subject.bzl +++ b/test/java/testutil/javac_action_subject.bzl @@ -22,6 +22,8 @@ def _new_javac_action_subject(env, target, output): direct_dependencies = lambda: _create_subject_for_flag("--direct_dependencies", self.parsed_flags, self.meta), javacopts = lambda: _create_subject_for_flag("--javacopts", self.parsed_flags, self.meta), jar = lambda: _create_subject_for_flag("-jar", self.parsed_flags, self.meta), + # An unset --strict_java_deps is equivalent to "OFF". + strict_java_deps = lambda: _create_subject_for_flag("--strict_java_deps", self.parsed_flags, self.meta, default = ["OFF"]), sources = lambda: _create_subject_for_flag("--sources", self.parsed_flags, self.meta), executable_file_name = lambda: subjects.str(action_subject.actual.argv[0], self.meta), inputs = action_subject.inputs, @@ -56,9 +58,9 @@ def _parse_flags(argv): return flag_values -def _create_subject_for_flag(flag_name, parsed_flags, meta): +def _create_subject_for_flag(flag_name, parsed_flags, meta, default = None): """Helper to create a collection subject for a given flag.""" - return subjects.collection(parsed_flags[flag_name], meta.derive(flag_name), format = True) + return subjects.collection(parsed_flags.get(flag_name, default), meta.derive(flag_name), format = True) javac_action_subject = struct( of = _new_javac_action_subject, From e898c0fcc80f12f9fbe0e3e9e66f1d3e78ca378d Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 5 Mar 2026 05:40:16 -0800 Subject: [PATCH 428/465] Prepare for Starlarkifying more `java_library` and `java_binary` tests (ignore-relnotes) PiperOrigin-RevId: 879015156 Change-Id: I3f1d0bcf272e21de4861096fa570d98ce461f7fa --- .../common_launcher_java_binary_tests.bzl | 28 +++++++++++++ .../common_launcher_java_library_tests.bzl | 27 +++++++++++++ test/java/common/rules/java_binary_tests.bzl | 17 +++++++- test/java/common/rules/java_library_tests.bzl | 39 +++++++++++++------ 4 files changed, 98 insertions(+), 13 deletions(-) create mode 100644 test/java/common/rules/common_launcher_java_binary_tests.bzl create mode 100644 test/java/common/rules/common_launcher_java_library_tests.bzl diff --git a/test/java/common/rules/common_launcher_java_binary_tests.bzl b/test/java/common/rules/common_launcher_java_binary_tests.bzl new file mode 100644 index 00000000..34c6e3f5 --- /dev/null +++ b/test/java/common/rules/common_launcher_java_binary_tests.bzl @@ -0,0 +1,28 @@ +"""Parameterized tests for java_binary with --java_launcher""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_binary.bzl", "java_binary") + +def _test_java_binary_non_executable_rule_outputs(name): + util.helper_target( + java_binary, + name = name + "/test_app_noexec", + srcs = ["InputFile.java"], + create_executable = 0, + ) + + analysis_test( + name = name, + impl = _test_java_binary_non_executable_rule_outputs_impl, + target = name + "/test_app_noexec", + ) + +def _test_java_binary_non_executable_rule_outputs_impl(env, target): + env.expect.that_target(target).default_outputs().contains_exactly([ + "{package}/{name}.jar", + ]) + +JAVA_BINARY_LAUNCHER_TESTS = [ + _test_java_binary_non_executable_rule_outputs, +] diff --git a/test/java/common/rules/common_launcher_java_library_tests.bzl b/test/java/common/rules/common_launcher_java_library_tests.bzl new file mode 100644 index 00000000..8f0ed228 --- /dev/null +++ b/test/java/common/rules/common_launcher_java_library_tests.bzl @@ -0,0 +1,27 @@ +"""Parameterized tests for java_library with --java_launcher""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_library.bzl", "java_library") + +def _test_java_library_rule_outputs(name): + util.helper_target( + java_library, + name = name + "/test_lib", + srcs = ["A.java"], + ) + + analysis_test( + name = name, + impl = _test_java_library_rule_outputs_impl, + target = name + "/test_lib", + ) + +def _test_java_library_rule_outputs_impl(env, target): + env.expect.that_target(target).default_outputs().contains_exactly([ + "{package}/lib{name}.jar", + ]) + +JAVA_LIBRARY_LAUNCHER_TESTS = [ + _test_java_library_rule_outputs, +] diff --git a/test/java/common/rules/java_binary_tests.bzl b/test/java/common/rules/java_binary_tests.bzl index 10728fb3..7ee9eb1d 100644 --- a/test/java/common/rules/java_binary_tests.bzl +++ b/test/java/common/rules/java_binary_tests.bzl @@ -8,6 +8,7 @@ load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") +load("//test/java/common/rules:common_launcher_java_binary_tests.bzl", "JAVA_BINARY_LAUNCHER_TESTS") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") @@ -251,7 +252,7 @@ def _test_java_binary_can_set_transitive_validation_impl(env, targets): def java_binary_tests(name): test_suite( - name = name, + name = "_basic_" + name, tests = [ _test_java_binary_provides_binary_java_info, _test_stamp_conversion_does_not_override_int, @@ -261,3 +262,17 @@ def java_binary_tests(name): _test_java_binary_can_set_transitive_validation, ], ) + + # TODO: unset --java_launcher explicitly + test_suite( + name = "_jdk_launcher_" + name, + tests = JAVA_BINARY_LAUNCHER_TESTS, + ) + + native.test_suite( + name = name, + tests = [ + "_basic_" + name, + "_jdk_launcher_" + name, + ], + ) diff --git a/test/java/common/rules/java_library_tests.bzl b/test/java/common/rules/java_library_tests.bzl index 64e17435..77980f2f 100644 --- a/test/java/common/rules/java_library_tests.bzl +++ b/test/java/common/rules/java_library_tests.bzl @@ -9,6 +9,8 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") +load("//test/java/common/rules:common_launcher_java_library_tests.bzl", "JAVA_LIBRARY_LAUNCHER_TESTS") +load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") @@ -312,6 +314,10 @@ def _test_exposes_native_library_info_impl(env, target): assert_lib.dynamic_library().basename().contains("mynativedep") def _test_strict_java_deps(name, strict_java_deps): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + always_passes(name) + return + util.helper_target( java_library, name = name + "/jl", @@ -344,22 +350,31 @@ def _test_strict_java_deps_error(name): _test_strict_java_deps(name, "ERROR") def java_library_tests(name): - tests = [ - _test_exposes_plugins, - _test_exposes_java_info, - _test_java_info_propagation, - _test_java_library_attributes, - _test_propagates_direct_native_libraries, - _test_exposes_native_library_info, - ] - if bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: - tests += [ + test_suite( + name = "_basic_" + name, + tests = [ + _test_exposes_plugins, + _test_exposes_java_info, + _test_java_info_propagation, + _test_java_library_attributes, + _test_propagates_direct_native_libraries, + _test_exposes_native_library_info, _test_strict_java_deps_off, _test_strict_java_deps_warn, _test_strict_java_deps_error, - ] + ], + ) + # TODO: unset --java_launcher explicitly test_suite( + name = "_jdk_launcher_" + name, + tests = JAVA_LIBRARY_LAUNCHER_TESTS, + ) + + native.test_suite( name = name, - tests = tests, + tests = [ + "_basic_" + name, + "_jdk_launcher_" + name, + ], ) From 927f2914f8d01cc4f7376e8ffc6adaf76cec1f02 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 5 Mar 2026 11:45:37 -0800 Subject: [PATCH 429/465] Migrate DeployArchiveBuilderTest.testGPlatformK8 PiperOrigin-RevId: 879173676 Change-Id: I7ef4839623ea1d441ddd46fb9863bba1ebee353a --- MODULE.bazel | 1 + 1 file changed, 1 insertion(+) diff --git a/MODULE.bazel b/MODULE.bazel index 204b8e88..442e7451 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -138,3 +138,4 @@ archive_override( test_repositories = use_extension("//test:repositories.bzl", "test_repositories_ext", dev_dependency = True) use_repo(test_repositories, "guava", "truth") + From 80a3bd663ada3931baf0492fb148ea102936c876 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 5 Mar 2026 12:06:34 -0800 Subject: [PATCH 430/465] Fix rules_java CI broken by https://github.com/rules_java/bazel/commit/927f2914f8d01cc4f7376e8ffc6adaf76cec1f02 PiperOrigin-RevId: 879183729 Change-Id: I38a08618024abfb7678704075286a607775fb65d --- MODULE.bazel | 1 - 1 file changed, 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 442e7451..204b8e88 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -138,4 +138,3 @@ archive_override( test_repositories = use_extension("//test:repositories.bzl", "test_repositories_ext", dev_dependency = True) use_repo(test_repositories, "guava", "truth") - From dbefcf35b19047afc5bf08db38298f60142e7867 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 5 Mar 2026 12:46:26 -0800 Subject: [PATCH 431/465] Starlarkify many `JavaStarlarkApiTest` tests. PiperOrigin-RevId: 879201973 Change-Id: I783eee85fb6f1beeb47781f7c163745c3c0b1984 --- test/java/common/java_common_tests.bzl | 201 ++++++++++++++++++ test/java/common/java_info_tests.bzl | 29 +++ test/java/testutil/java_info_subject.bzl | 1 + .../testutil/java_toolchain_info_subject.bzl | 5 + test/java/testutil/rules/custom_library.bzl | 4 + ...library_with_strict_java_deps_provider.bzl | 15 ++ ...library_with_wrong_java_toolchain_type.bzl | 24 +++ test/java/toolchains/BUILD | 2 + test/java/toolchains/java_toolchain_tests.bzl | 85 ++++++++ 9 files changed, 366 insertions(+) create mode 100644 test/java/testutil/rules/custom_library_with_strict_java_deps_provider.bzl create mode 100644 test/java/testutil/rules/custom_library_with_wrong_java_toolchain_type.bzl diff --git a/test/java/common/java_common_tests.bzl b/test/java/common/java_common_tests.bzl index c35f8388..d75d4a56 100644 --- a/test/java/common/java_common_tests.bzl +++ b/test/java/common/java_common_tests.bzl @@ -1,6 +1,8 @@ """Tests for java_common APIs""" +load("@bazel_features//:features.bzl", "bazel_features") load("@rules_cc//cc:cc_binary.bzl", "cc_binary") +load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") @@ -10,6 +12,7 @@ load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") +load("//java/toolchains:java_runtime.bzl", "java_runtime") load("//test/java/testutil:artifact_closure.bzl", "artifact_closure") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") @@ -22,6 +25,8 @@ load("//test/java/testutil:rules/custom_library_with_exports.bzl", "custom_libra load("//test/java/testutil:rules/custom_library_with_named_outputs.bzl", "custom_library_with_named_outputs") load("//test/java/testutil:rules/custom_library_with_sourcepaths.bzl", "custom_library_with_sourcepaths") load("//test/java/testutil:rules/custom_library_with_strict_deps.bzl", "custom_library_with_strict_deps") +load("//test/java/testutil:rules/custom_library_with_strict_java_deps_provider.bzl", "StrictJavaDepsInfo", "custom_library_with_strict_java_deps_provider") +load("//test/java/testutil:rules/custom_library_with_wrong_java_toolchain_type.bzl", "custom_library_with_wrong_java_toolchain_type") load("//test/java/testutil:rules/custom_library_with_wrong_plugins_type.bzl", "custom_library_with_wrong_plugins_type") def _test_compile_default_values(name): @@ -878,6 +883,194 @@ def _test_skip_annotation_processing_impl(env, targets): turbine_action_noproc.mnemonic().equals("Turbine") turbine_action_noproc.argv().not_contains("--processors") +def _test_compile_direct_native_libraries(name): + target_name = name + "/custom" + util.helper_target( + cc_library, + name = target_name + "/native.so", + srcs = ["a.cc"], + ) + util.helper_target( + custom_library, + name = target_name, + srcs = ["A.java"], + ccdeps = [target_name + "/native.so"], + ) + + analysis_test( + name = name, + impl = _test_compile_direct_native_libraries_impl, + target = target_name, + ) + +def _test_compile_direct_native_libraries_impl(env, target): + assert_native_libs = java_info_subject.from_target(env, target).transitive_native_libraries() + assert_native_libs.static_libraries().contains_exactly_predicates([ + matching.any( + matching.str_matches("libnative.so.a"), # linux / mac + matching.str_matches("native.so.lib"), # windows + ), + ]) + +def _test_strict_java_deps_default(name): + util.helper_target( + custom_library, + name = name + "/unused", + ) + analysis_test( + name = name, + target = name + "/unused", # analysis_test requires setting a target. + impl = _test_strict_java_deps_default_impl, + fragments = ["java"], + ) + +def _test_strict_java_deps_default_impl(env, _unused): + env.expect.that_str(env.ctx.fragments.java.strict_java_deps).equals("default") + +def _test_strict_java_deps_error(name): + util.helper_target( + custom_library_with_strict_java_deps_provider, + name = name + "_strict_java_deps_provider", + ) + + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + analysis_test( + name = name, + impl = lambda env, target: env.expect.that_bool(True).equals(True), + target = name + "_strict_java_deps_provider", + ) + else: + analysis_test( + name = name, + target = name + "_strict_java_deps_provider", + impl = _test_strict_java_deps_error_impl, + fragments = ["java"], + config_settings = {"//command_line_option:experimental_strict_java_deps": "error"}, + ) + +def _test_strict_java_deps_error_impl(env, target): + env.expect.that_str(target[StrictJavaDepsInfo].strict_java_deps).equals("error") + +def _test_compile_output_jar_has_manifest_proto(name): + util.helper_target( + custom_library, + name = name + "/custom", + srcs = ["Main.java"], + ) + + analysis_test( + name = name, + impl = _test_compile_output_jar_has_manifest_proto_impl, + target = name + "/custom", + ) + +def _test_compile_output_jar_has_manifest_proto_impl(env, target): + java_info_subject.from_target(env, target).java_outputs().singleton().manifest_proto().short_path_equals( + "{package}/lib{name}.jar_manifest_proto", + ) + +def _test_compile_with_neverlink_deps(name): + target_name = name + "/custom" + util.helper_target( + java_library, + name = target_name + "/neverlink_dep", + srcs = ["B.java"], + neverlink = True, + ) + util.helper_target( + custom_library, + name = target_name, + srcs = ["A.java"], + deps = [target_name + "/neverlink_dep"], + ) + + analysis_test( + name = name, + impl = _test_compile_with_neverlink_deps_impl, + target = target_name, + ) + +def _test_compile_with_neverlink_deps_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + assert_java_info.compilation_args().transitive_runtime_jars().contains_exactly([ + "{package}/lib{name}.jar", + ]) + assert_java_info.transitive_source_jars().contains_exactly([ + "{package}/lib{name}-src.jar", + "{package}/lib{name}/neverlink_dep-src.jar", + ]) + assert_java_info.compilation_args().transitive_compile_time_jars().contains_exactly([ + "{package}/lib{name}-hjar.jar", + "{package}/lib{name}/neverlink_dep-hjar.jar", + ]) + +def _test_compile_output_jar_not_in_runtime_path_without_sources_defined(name): + target_name = name + "/custom" + util.helper_target( + java_library, + name = target_name + "/export_dep", + srcs = ["B.java"], + ) + util.helper_target( + custom_library, + name = target_name, + srcs = [], + exports = [target_name + "/export_dep"], + ) + + analysis_test( + name = name, + impl = _test_compile_output_jar_not_in_runtime_path_without_sources_defined_impl, + target = target_name, + ) + +def _test_compile_output_jar_not_in_runtime_path_without_sources_defined_impl(env, target): + assert_java_info = java_info_subject.from_target(env, target) + assert_java_info.compilation_args().transitive_runtime_jars().contains_exactly([ + "{package}/lib{name}/export_dep.jar", + ]) + assert_java_info.compilation_args().transitive_compile_time_jars().contains_exactly([ + "{package}/lib{name}/export_dep-hjar.jar", + ]) + assert_java_info.java_outputs().singleton().class_jar().short_path_equals("{package}/lib{name}.jar") + assert_java_info.java_outputs().singleton().compile_jar().equals(None) + +def _test_java_runtime_provider_files(name): + # Create a rule that extracts JavaRuntimeInfo.files + util.helper_target( + java_runtime, + name = name + "/jvm", + srcs = ["a.txt"], + java_home = "foo/bar", + ) + + analysis_test( + name = name, + impl = _test_java_runtime_provider_files_impl, + target = name + "/jvm", + ) + +def _test_java_runtime_provider_files_impl(env, target): + env.expect.that_target(target).default_outputs().contains_exactly(["{package}/a.txt"]) + +def _test_custom_library_with_wrong_java_toolchain_type(name): + util.helper_target( + custom_library_with_wrong_java_toolchain_type, + name = name + "/custom", + srcs = ["a.java"], + ) + analysis_test( + name = name, + impl = _test_custom_library_with_wrong_java_toolchain_type_impl, + target = name + "/custom", + expect_failure = True, + ) + +def _test_custom_library_with_wrong_java_toolchain_type_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("got element of type ToolchainInfo, want JavaToolchainInfo"), + ) + def java_common_tests(name): test_suite( name = name, @@ -909,5 +1102,13 @@ def java_common_tests(name): _test_compile_strict_deps_enum, _test_java_library_collects_coverage_dependencies_from_resources, _test_skip_annotation_processing, + _test_compile_direct_native_libraries, + _test_strict_java_deps_default, + _test_strict_java_deps_error, + _test_compile_output_jar_has_manifest_proto, + _test_compile_with_neverlink_deps, + _test_compile_output_jar_not_in_runtime_path_without_sources_defined, + _test_java_runtime_provider_files, + _test_custom_library_with_wrong_java_toolchain_type, ], ) diff --git a/test/java/common/java_info_tests.bzl b/test/java/common/java_info_tests.bzl index 4f82d3eb..daea0485 100644 --- a/test/java/common/java_info_tests.bzl +++ b/test/java/common/java_info_tests.bzl @@ -1390,6 +1390,34 @@ def _java_common_compile_native_libraries_propagate_test_impl(env, target): matching.str_matches("*native_dep*"), ]) +def _test_merge_runtime_output_jars(name): + util.helper_target( + java_library, + name = name + "/a", + srcs = ["A.java"], + ) + util.helper_target( + java_library, + name = name + "/b", + srcs = ["B.java"], + ) + util.helper_target( + java_info_merge_rule, + name = name + "/merged", + deps = [name + "/a", name + "/b"], + ) + analysis_test( + name = name, + impl = _test_merge_runtime_output_jars_impl, + target = name + "/merged", + ) + +def _test_merge_runtime_output_jars_impl(env, target): + java_info_subject.from_target(env, target).runtime_output_jars().contains_exactly([ + "{package}/lib{test_name}/a.jar", + "{package}/lib{test_name}/b.jar", + ]) + def java_info_tests(name): test_suite( name = name, @@ -1438,5 +1466,6 @@ def java_info_tests(name): _java_common_merge_with_neverlink_test, _java_common_compile_with_neverlink_test, _java_common_compile_native_libraries_propagate_test, + _test_merge_runtime_output_jars, ], ) diff --git a/test/java/testutil/java_info_subject.bzl b/test/java/testutil/java_info_subject.bzl index 8471706f..f5ad9e9c 100644 --- a/test/java/testutil/java_info_subject.bzl +++ b/test/java/testutil/java_info_subject.bzl @@ -98,6 +98,7 @@ def _new_java_outputs_subject(java_output, meta): source_jars = lambda: subjects.depset_file(java_output.source_jars if hasattr(java_output.source_jars, "to_list") else depset(java_output.source_jars), meta.derive("source_jars")), jdeps = lambda: subjects.file(java_output.jdeps, meta.derive("jdeps")), compile_jdeps = lambda: subjects.file(java_output.compile_jdeps, meta.derive("compile_jdeps")), + manifest_proto = lambda: subjects.file(java_output.manifest_proto, meta.derive("manifest_proto")), native_headers_jar = lambda: subjects.file(java_output.native_headers_jar, meta.derive("native_headers_jar")), ) return public diff --git a/test/java/testutil/java_toolchain_info_subject.bzl b/test/java/testutil/java_toolchain_info_subject.bzl index 2757bfce..31afe59d 100644 --- a/test/java/testutil/java_toolchain_info_subject.bzl +++ b/test/java/testutil/java_toolchain_info_subject.bzl @@ -23,6 +23,11 @@ def _new_java_toolchain_info_subject(info, meta): header_compiler_builtin_processors = lambda: subjects.collection(info._header_compiler_builtin_processors.to_list(), meta.derive("_header_compiler_builtin_processors")), reduced_classpath_incompatible_processors = lambda: subjects.collection(info._reduced_classpath_incompatible_processors.to_list(), meta.derive("_reduced_classpath_incompatible_processors")), javabuilder = lambda: _new_java_builder_subject(info._javabuilder, meta.derive("_javabuilder")), + label = lambda: subjects.label(info.label, meta.derive("label")), + # TODO: hvd - Give label_subject predicate matching support so we don't need this str_subject variant. + label_str = lambda: subjects.str(str(info.label), meta.derive("label_str")), + default_javacopts = lambda: subjects.collection(info._javacopts_list, meta.derive("default_javacopts")), + default_javacopts_depset = lambda: subjects.collection(info._javacopts.to_list(), meta.derive("default_javacopts_depset")), ) return public diff --git a/test/java/testutil/rules/custom_library.bzl b/test/java/testutil/rules/custom_library.bzl index ec3699ce..5ef3ca03 100644 --- a/test/java/testutil/rules/custom_library.bzl +++ b/test/java/testutil/rules/custom_library.bzl @@ -1,5 +1,6 @@ """Helper rule for testing compilation with default parameter values""" +load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") @@ -9,6 +10,7 @@ def _custom_library_impl(ctx): output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") deps = [dep[JavaInfo] for dep in ctx.attr.deps] runtime_deps = [dep[JavaInfo] for dep in ctx.attr.runtime_deps] + native_libraries = [dep[CcInfo] for dep in ctx.attr.ccdeps] compilation_provider = java_common.compile( ctx, source_files = ctx.files.srcs, @@ -22,6 +24,7 @@ def _custom_library_impl(ctx): javac_opts = ctx.attr.javac_opts, java_toolchain = semantics.find_java_toolchain(ctx), enable_annotation_processing = ctx.attr.enable_annotation_processing, + native_libraries = native_libraries, ) return [DefaultInfo(files = depset([output_jar])), compilation_provider] @@ -32,6 +35,7 @@ custom_library = rule( "source_jars": attr.label_list(allow_files = [".jar"]), "deps": attr.label_list(), "runtime_deps": attr.label_list(), + "ccdeps": attr.label_list(providers = [CcInfo]), "exports": attr.label_list(), "plugins": attr.label_list(), "javac_opts": attr.string_list(), diff --git a/test/java/testutil/rules/custom_library_with_strict_java_deps_provider.bzl b/test/java/testutil/rules/custom_library_with_strict_java_deps_provider.bzl new file mode 100644 index 00000000..3a0f66a7 --- /dev/null +++ b/test/java/testutil/rules/custom_library_with_strict_java_deps_provider.bzl @@ -0,0 +1,15 @@ +"""Custom libraty that reads --strict_java_deps and returns it from a provider.""" + +StrictJavaDepsInfo = provider( + doc = "Provides args.strict_java_deps for testing", + fields = ["strict_java_deps"], +) + +def _impl(ctx): + return [StrictJavaDepsInfo(strict_java_deps = ctx.fragments.java.strict_java_deps)] + +custom_library_with_strict_java_deps_provider = rule( + implementation = _impl, + attrs = {}, + fragments = ["java"], +) diff --git a/test/java/testutil/rules/custom_library_with_wrong_java_toolchain_type.bzl b/test/java/testutil/rules/custom_library_with_wrong_java_toolchain_type.bzl new file mode 100644 index 00000000..73b4a7f9 --- /dev/null +++ b/test/java/testutil/rules/custom_library_with_wrong_java_toolchain_type.bzl @@ -0,0 +1,24 @@ +"""Custom rule to test java_common.compile(java_toolchain = ...) expects JavaToolchainInfo""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_semantics.bzl", "semantics") + +def _impl(ctx): + output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") + return java_common.compile( + ctx, + source_files = ctx.files.srcs, + output = output_jar, + java_toolchain = ctx.attr._java_toolchain[platform_common.ToolchainInfo], + ) + +custom_library_with_wrong_java_toolchain_type = rule( + implementation = _impl, + attrs = { + "srcs": attr.label_list(allow_files = [".java"]), + "deps": attr.label_list(), + "_java_toolchain": attr.label(default = semantics.JAVA_TOOLCHAIN_LABEL), + }, + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], + fragments = ["java"], +) diff --git a/test/java/toolchains/BUILD b/test/java/toolchains/BUILD index 4ebe1f2d..1d7af21f 100644 --- a/test/java/toolchains/BUILD +++ b/test/java/toolchains/BUILD @@ -6,3 +6,5 @@ package(default_applicable_licenses = ["@rules_java//:license"]) java_runtime_tests(name = "java_runtime_tests") java_toolchain_tests(name = "java_toolchain_tests") + +exports_files(["java_runtime.src"]) diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index 7c95d0e3..372b9995 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -13,6 +13,7 @@ load("//java/toolchains:java_toolchain.bzl", "java_toolchain") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:java_toolchain_info_subject.bzl", "java_toolchain_info_subject") load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") +load("//toolchains:java_toolchain_alias.bzl", "java_toolchain_alias") def _declare_java_toolchain(*, name, **kwargs): java_runtime_name = name + "/runtime" @@ -595,6 +596,86 @@ def _test_java_common_without_toolchain_type_fails_impl(env, target): matching.str_matches("must declare *tools/jdk:toolchain_type' toolchain in order to use java_common"), ) +def _test_java_toolchain_flag_default(name): + util.helper_target( + java_toolchain_alias, + name = name + "/toolchain_alias", + ) + + analysis_test( + name = name, + impl = _test_java_toolchain_flag_default_impl, + target = name + "/toolchain_alias", + ) + +def _test_java_toolchain_flag_default_impl(env, target): + assert_toolchain = java_toolchain_info_subject.from_target(env, target) + assert_toolchain.label_str().matches( + matching.any( + matching.str_endswith("jdk:remote_toolchain"), + matching.str_endswith("jdk:toolchain"), + matching.str_endswith("jdk:toolchain_host"), + # buildifier: disable=canonical-repository + matching.str_startswith("@@//toolchains:toolchain_java"), + ), + ) + +def _test_java_toolchain_flag_set(name): + _declare_java_toolchain(name = name) + util.helper_target( + java_toolchain_alias, + name = name + "/toolchain_alias", + ) + + analysis_test( + name = name, + impl = _test_java_toolchain_flag_set_impl, + targets = { + "alias": name + "/toolchain_alias", + "toolchain": name + "/java_toolchain", + }, + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + ) + +def _test_java_toolchain_flag_set_impl(env, targets): + assert_toolchain = java_toolchain_info_subject.from_target(env, targets.alias) + assert_toolchain.label().equals(targets.toolchain.label) + +def _test_default_javac_opts_depset(name): + _declare_java_toolchain(name = name) + + analysis_test( + name = name, + impl = _test_default_javac_opts_depset_impl, + target = name + "/java_toolchain", + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _test_default_javac_opts_depset_impl(env, target): + java_toolchain_info_subject.from_target(env, target).default_javacopts_depset().contains_exactly( + ["-source 6 -target 6 -Xlint:toto -Xmaxerrs 500"], + ) + +def _test_default_javac_opts(name): + _declare_java_toolchain(name = name) + + analysis_test( + name = name, + impl = _test_default_javac_opts_impl, + target = name + "/java_toolchain", + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _test_default_javac_opts_impl(env, target): + java_toolchain_info_subject.from_target(env, target).default_javacopts().contains_at_least([ + "-source", + "6", + "-target", + "6", + ]).in_order() + def java_toolchain_tests(name): test_suite( name = name, @@ -619,5 +700,9 @@ def java_toolchain_tests(name): _test_java_compile_action_uses_tool_specific_jvm_opts, _test_javabuilder_location_expansion_with_multiple_artifacts, _test_java_common_without_toolchain_type_fails, + _test_java_toolchain_flag_default, + _test_java_toolchain_flag_set, + _test_default_javac_opts_depset, + _test_default_javac_opts, ], ) From 878ddc1d5246addd4231f105532c2ee2fe6e8977 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 5 Mar 2026 13:39:30 -0800 Subject: [PATCH 432/465] Starlarkify `*IsPrivateApi` tests in `JavaStarlarkApiTest`. PiperOrigin-RevId: 879224869 Change-Id: I6aacd6716aea4758ce6bb5de6a258c3800ba5808 --- test/java/common/java_common_tests.bzl | 56 ++++++++++++++++++ .../java/testutil/rules/private_api_usage.bzl | 57 +++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 test/java/testutil/rules/private_api_usage.bzl diff --git a/test/java/common/java_common_tests.bzl b/test/java/common/java_common_tests.bzl index d75d4a56..756e3a42 100644 --- a/test/java/common/java_common_tests.bzl +++ b/test/java/common/java_common_tests.bzl @@ -28,6 +28,7 @@ load("//test/java/testutil:rules/custom_library_with_strict_deps.bzl", "custom_l load("//test/java/testutil:rules/custom_library_with_strict_java_deps_provider.bzl", "StrictJavaDepsInfo", "custom_library_with_strict_java_deps_provider") load("//test/java/testutil:rules/custom_library_with_wrong_java_toolchain_type.bzl", "custom_library_with_wrong_java_toolchain_type") load("//test/java/testutil:rules/custom_library_with_wrong_plugins_type.bzl", "custom_library_with_wrong_plugins_type") +load("//test/java/testutil:rules/private_api_usage.bzl", "private_compile_api_usage", "private_merge_api_usage", "private_run_ijar_api_usage") def _test_compile_default_values(name): util.helper_target(custom_library, name = name + "/custom", srcs = ["Main.java"]) @@ -1071,6 +1072,52 @@ def _test_custom_library_with_wrong_java_toolchain_type_impl(env, target): matching.str_matches("got element of type ToolchainInfo, want JavaToolchainInfo"), ) +def _test_private_api(name, helper_rule, private_attr_name): + util.helper_target( + helper_rule, + name = name + "/custom", + private_attr_name = private_attr_name, + ) + + analysis_test( + name = name, + impl = lambda env, target: _test_private_api_impl(env, target, private_attr_name), + target = name + "/custom", + expect_failure = True, + ) + +def _test_private_api_impl(env, target, private_attr_name): + env.expect.that_target(target).failures().contains_predicate( + matching.contains("got unexpected keyword argument: " + private_attr_name), + ) + +def _test_compile_disabling_compile_jar_is_private_api(name): + _test_private_api(name, private_compile_api_usage, "enable_compile_jar_action") + +def _test_compile_classpath_resources_is_private_api(name): + _test_private_api(name, private_compile_api_usage, "classpath_resources") + +def _test_compile_injecting_rule_kind_is_private_api(name): + _test_private_api(name, private_compile_api_usage, "injecting_rule_kind") + +def _test_compile_enable_jspecify_is_private_api(name): + _test_private_api(name, private_compile_api_usage, "enable_jspecify") + +def _test_merge_java_outputs_is_private_api(name): + _test_private_api(name, private_merge_api_usage, "merge_java_outputs") + +def _test_merge_source_jars_is_private_api(name): + _test_private_api(name, private_merge_api_usage, "merge_source_jars") + +def _test_compile_include_compilation_info_is_private_api(name): + _test_private_api(name, private_compile_api_usage, "include_compilation_info") + +def _test_compile_resource_jars_is_private_api(name): + _test_private_api(name, private_compile_api_usage, "resource_jars") + +def _test_run_ijar_output_is_private_api(name): + _test_private_api(name, private_run_ijar_api_usage, "output") + def java_common_tests(name): test_suite( name = name, @@ -1110,5 +1157,14 @@ def java_common_tests(name): _test_compile_output_jar_not_in_runtime_path_without_sources_defined, _test_java_runtime_provider_files, _test_custom_library_with_wrong_java_toolchain_type, + _test_compile_disabling_compile_jar_is_private_api, + _test_compile_classpath_resources_is_private_api, + _test_compile_injecting_rule_kind_is_private_api, + _test_compile_enable_jspecify_is_private_api, + _test_merge_java_outputs_is_private_api, + _test_merge_source_jars_is_private_api, + _test_compile_include_compilation_info_is_private_api, + _test_compile_resource_jars_is_private_api, + _test_run_ijar_output_is_private_api, ], ) diff --git a/test/java/testutil/rules/private_api_usage.bzl b/test/java/testutil/rules/private_api_usage.bzl new file mode 100644 index 00000000..9ceaf826 --- /dev/null +++ b/test/java/testutil/rules/private_api_usage.bzl @@ -0,0 +1,57 @@ +"""Helper rules to test private API usage""" + +load("//java/common:java_common.bzl", "java_common") +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_semantics.bzl", "semantics") + +_PRIVATE_ATTR_ATTRS = { + "private_attr_name": attr.string(mandatory = True), +} + +def _private_compile_api_impl(ctx): + out = ctx.actions.declare_file(ctx.label.name + ".jar") + java_common.compile( + ctx = ctx, + output = out, + java_toolchain = semantics.find_java_toolchain(ctx), + **{ctx.attr.private_attr_name: "does_not_matter"} + ) + return [] + +private_compile_api_usage = rule( + _private_compile_api_impl, + attrs = _PRIVATE_ATTR_ATTRS, + fragments = ["java"], + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], +) + +def _private_merge_api_impl(ctx): + out = ctx.actions.declare_file(ctx.label.name + ".jar") + info = JavaInfo(output_jar = out, compile_jar = out) + java_common.merge( + providers = [info], + **{ctx.attr.private_attr_name: "does_not_matter"} + ) + return [] + +private_merge_api_usage = rule( + _private_merge_api_impl, + attrs = _PRIVATE_ATTR_ATTRS, + fragments = ["java"], +) + +def _private_run_ijar_api_impl(ctx): + java_common.run_ijar( + ctx.actions, + java_toolchain = semantics.find_java_toolchain(ctx), + jar = ctx.actions.declare_file(ctx.label.name + "_ijar.jar"), + **{ctx.attr.private_attr_name: "does_not_matter"} + ) + return [] + +private_run_ijar_api_usage = rule( + _private_run_ijar_api_impl, + attrs = _PRIVATE_ATTR_ATTRS, + fragments = ["java"], + toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], +) From 22bc9a886c1dcc5a44ef7d4e1ffe1afb1c816f3f Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 9 Mar 2026 01:40:24 -0700 Subject: [PATCH 433/465] Automatic code cleanup. PiperOrigin-RevId: 880722722 Change-Id: I55bf0687325a1ef5dac760adbe169d82fa000e9a --- java/common/rules/impl/BUILD | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/common/rules/impl/BUILD b/java/common/rules/impl/BUILD index 70adeccd..6ab41376 100644 --- a/java/common/rules/impl/BUILD +++ b/java/common/rules/impl/BUILD @@ -29,7 +29,7 @@ bzl_library( bzl_library( name = "java_helper_bzl", srcs = ["java_helper.bzl"], - visibility = ["//java:__subpackages__"], + visibility = ["//visibility:private"], deps = [ "//java/common:semantics_bzl", "//java/common/rules:java_helper_bzl", From 421776c58cd4ca3f75e852c63e570bf6a442c891 Mon Sep 17 00:00:00 2001 From: James Judd Date: Mon, 9 Mar 2026 07:41:17 -0700 Subject: [PATCH 434/465] Attempt to fix missing class error by not using tree artifacts for bootclasspath (#340) A few times a year across many thousands of builds we encounter a rare error about the `DumpPlatformClassPath` class being missing. Our Bazel setup uses dynamic execution, builds without the bytes, remote execution + remote caching, and path mapping. The error we encounter is as follows: ``` Error: Could not find or load main class DumpPlatformClassPath Caused by: java.lang.ClassNotFoundException: DumpPlatformClassPath ``` I'm guessing that this is happening due to some kind of Bazel bug that happens with our Bazel setup and tree artifacts, i.e., declare_directory. Best I can tell this is happening because the `DumpPlatformClassPath.class` file is somehow not materializing correctly. I'm not 100% confident about that, but it's my leading hypothesis at this point in time. This commit changes the actions in `bootclasspath.bzl` to not rely on tree artifacts. Instead, they rely JDK 11+'s ability to launch single-file programs (introduced in JEP 330). This avoids the `javac` action and `declare_directory` previously required to compile `DumpPlatformClassPath`. Problem is this makes rules_java not compatible with JDK's older than 11. I'm very open to alternative solutions to this, but I haven't yet come up with a robust, cross platform solution that avoids tree artifacts while also maintaining compatibility with JDKs older than 11. I wanted to open this PR to get some discussion going. Closes #340 COPYBARA_INTEGRATE_REVIEW=https://github.com/bazelbuild/rules_java/pull/340 from lucidsoftware:bootclasspath-avoid-tree-artifact 34809e22c0022d4bb72088c0b1cfc864ea0cfb31 PiperOrigin-RevId: 880851895 Change-Id: I04c7142981a22b9f4995f25e2789ac6aa2aaf097 --- test/check_remote_java_tools_configs.sh | 6 ++- test/toolchains/bootclasspath_tests.bzl | 49 +++++++++++++++++++ toolchains/bootclasspath.bzl | 64 +++++++++++++++---------- 3 files changed, 92 insertions(+), 27 deletions(-) diff --git a/test/check_remote_java_tools_configs.sh b/test/check_remote_java_tools_configs.sh index 7e69dc00..957aa788 100755 --- a/test/check_remote_java_tools_configs.sh +++ b/test/check_remote_java_tools_configs.sh @@ -22,7 +22,11 @@ function download_and_check_hash() { TMP_FILE=$(mktemp -q /tmp/remotejavatools.XXXXXX) echo "fetching $name from $url to ${TMP_FILE}" curl --silent -o ${TMP_FILE} -L "$url" - actual_hash=`sha256sum ${TMP_FILE} | cut -d' ' -f1` + if command -v sha256sum &> /dev/null; then + actual_hash=`sha256sum ${TMP_FILE} | cut -d' ' -f1` + else + actual_hash=`shasum -a 256 ${TMP_FILE} | cut -d' ' -f1` + fi if [ "${hash}" != "${actual_hash}" ]; then echo "ERROR: wrong hash for ${name}! wanted: ${hash}, got: ${actual_hash}" exit 1 diff --git a/test/toolchains/bootclasspath_tests.bzl b/test/toolchains/bootclasspath_tests.bzl index e7ad1cac..15ccd4ff 100644 --- a/test/toolchains/bootclasspath_tests.bzl +++ b/test/toolchains/bootclasspath_tests.bzl @@ -68,6 +68,53 @@ def _test_incompatible_language_version_bootclasspath_enabled_unversioned_impl(e system_path = target[java_common.BootClassPathInfo]._system_path env.expect.that_str(system_path).contains("local_jdk") +def _test_jdk8_uses_tree_artifact(name): + analysis_test( + name = name, + impl = _test_jdk8_uses_tree_artifact_impl, + target = Label("//toolchains:platformclasspath"), + config_settings = { + "//command_line_option:tool_java_runtime_version": "remotejdk_8", + }, + ) + +def _test_jdk8_uses_tree_artifact_impl(env, target): + env.expect.that_target(target).action_named( + "JavaToolchainCompileClasses", + ).argv().contains_at_least([ + "-d", + "{bindir}/{package}/{name}_classes", + "toolchains/DumpPlatformClassPath.java", + ]).in_order() + env.expect.that_target(target).action_named( + "JavaToolchainCompileBootClasspath", + ).argv().contains_at_least([ + "--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED", + "-cp", + "{bindir}/{package}/{name}_classes", + "DumpPlatformClassPath", + "{bindir}/{package}/{name}_unstripped.jar", + ]).in_order() + +def _test_jdk11_uses_source_launcher(name): + analysis_test( + name = name, + impl = _test_jdk11_uses_source_launcher_impl, + target = Label("//toolchains:platformclasspath"), + config_settings = { + "//command_line_option:tool_java_runtime_version": "remotejdk_11", + }, + ) + +def _test_jdk11_uses_source_launcher_impl(env, target): + env.expect.that_target(target).action_named( + "JavaToolchainCompileBootClasspath", + ).argv().contains_at_least([ + "--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED", + "toolchains/DumpPlatformClassPath.java", + "{bindir}/{package}/{name}_unstripped.jar", + ]).in_order() + def bootclasspath_tests(name): test_suite( name = name, @@ -76,5 +123,7 @@ def bootclasspath_tests(name): _test_incompatible_language_version_bootclasspath_disabled, _test_incompatible_language_version_bootclasspath_enabled_versioned, _test_incompatible_language_version_bootclasspath_enabled_unversioned, + _test_jdk8_uses_tree_artifact, + _test_jdk11_uses_source_launcher, ], ) diff --git a/toolchains/bootclasspath.bzl b/toolchains/bootclasspath.bzl index 93da5de8..256c032f 100644 --- a/toolchains/bootclasspath.bzl +++ b/toolchains/bootclasspath.bzl @@ -129,29 +129,35 @@ def _bootclasspath_impl(ctx): exec_javabase = ctx.attr.java_runtime_alias[java_common.JavaRuntimeInfo] env = ctx.attr._utf8_environment[Utf8EnvironmentInfo].environment - class_dir = ctx.actions.declare_directory("%s_classes" % ctx.label.name) - - args = ctx.actions.args() - args.add("-source") - args.add("8") - args.add("-target") - args.add("8") - args.add("-Xlint:-options") - args.add("-J-XX:-UsePerfData") - args.add("-d") - args.add_all([class_dir], expand_directories = False) - args.add(ctx.file.src) - - ctx.actions.run( - executable = "%s/bin/javac" % exec_javabase.java_home, - mnemonic = "JavaToolchainCompileClasses", - inputs = [ctx.file.src] + ctx.files.java_runtime_alias, - outputs = [class_dir], - arguments = [args], - env = env, - execution_requirements = _SUPPORTS_PATH_MAPPING, - use_default_shell_env = True, - ) + # If possible, use JDK 11+'s ability to run a single Java file to avoid a + # separate action to compile DumpPlatformClassPath. + use_source_launcher = exec_javabase.version >= 11 + + class_dir = None + if not use_source_launcher: + class_dir = ctx.actions.declare_directory("%s_classes" % ctx.label.name) + + args = ctx.actions.args() + args.add("-source") + args.add("8") + args.add("-target") + args.add("8") + args.add("-Xlint:-options") + args.add("-J-XX:-UsePerfData") + args.add("-d") + args.add_all([class_dir], expand_directories = False) + args.add(ctx.file.src) + + ctx.actions.run( + executable = "%s/bin/javac" % exec_javabase.java_home, + mnemonic = "JavaToolchainCompileClasses", + inputs = [ctx.file.src] + ctx.files.java_runtime_alias, + outputs = [class_dir], + arguments = [args], + env = env, + execution_requirements = _SUPPORTS_PATH_MAPPING, + use_default_shell_env = True, + ) unstripped_bootclasspath = ctx.actions.declare_file("%s_unstripped.jar" % ctx.label.name) @@ -161,8 +167,13 @@ def _bootclasspath_impl(ctx): args.add("--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED") args.add("--add-exports=jdk.compiler/com.sun.tools.javac.platform=ALL-UNNAMED") args.add("--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED") - args.add_all("-cp", [class_dir], expand_directories = False) - args.add("DumpPlatformClassPath") + + if use_source_launcher: + args.add(ctx.file.src) + else: + args.add_all("-cp", [class_dir], expand_directories = False) + args.add("DumpPlatformClassPath") + args.add(unstripped_bootclasspath) if ctx.attr.language_version_bootstrap_runtime: @@ -211,7 +222,8 @@ Rerun with --toolchain_resolution_debug='@bazel_tools//tools/jdk:bootstrap_runti if len(system) != len(system_files): system = None - inputs = depset([class_dir] + ctx.files.java_runtime_alias, transitive = [any_javabase.files]) + classpath_input = ctx.file.src if use_source_launcher else class_dir + inputs = depset([classpath_input] + ctx.files.java_runtime_alias, transitive = [any_javabase.files]) ctx.actions.run( executable = str(exec_javabase.java_executable_exec_path), mnemonic = "JavaToolchainCompileBootClasspath", From cde9c8b5e0c9dfab364ff515d45e5871e5cda5fc Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 9 Mar 2026 08:59:28 -0700 Subject: [PATCH 435/465] Starlarkify some java runtime tests and one common test. PiperOrigin-RevId: 880883085 Change-Id: I6b2013aa8fba49136967563c349292f1ab098f91 --- test/java/common/rules/BUILD | 3 + test/java/common/rules/add_exports_tests.bzl | 39 +++++++++++ test/java/common/rules/merge_attrs_tests.bzl | 2 +- test/java/testutil/cc_info_subject.bzl | 13 ++++ .../testutil/java_runtime_info_subject.bzl | 14 ++++ test/java/toolchains/java_runtime_tests.bzl | 69 +++++++++++++++++++ 6 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 test/java/common/rules/add_exports_tests.bzl diff --git a/test/java/common/rules/BUILD b/test/java/common/rules/BUILD index cc2cd337..32870da7 100644 --- a/test/java/common/rules/BUILD +++ b/test/java/common/rules/BUILD @@ -1,3 +1,4 @@ +load(":add_exports_tests.bzl", "add_exports_tests") load(":deploy_archive_builder_tests.bzl", "deploy_archive_builder_test_suite") load(":java_binary_tests.bzl", "java_binary_tests") load(":java_import_tests.bzl", "java_import_tests") @@ -21,3 +22,5 @@ java_library_tests(name = "java_library_tests") java_import_tests(name = "java_import_tests") java_test_tests(name = "java_test_tests") + +add_exports_tests(name = "add_exports_tests") diff --git a/test/java/common/rules/add_exports_tests.bzl b/test/java/common/rules/add_exports_tests.bzl new file mode 100644 index 00000000..482e7311 --- /dev/null +++ b/test/java/common/rules/add_exports_tests.bzl @@ -0,0 +1,39 @@ +"""Tests for the add_exports attribute""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java:defs.bzl", "java_library") +load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:rules/java_info_merge.bzl", "java_info_merge_rule") + +def _test_merge_add_exports(name): + util.helper_target( + java_info_merge_rule, + name = name + "/merge", + deps = [name + "/a"], + ) + util.helper_target( + java_library, + name = name + "/a", + srcs = ["A.java"], + add_exports = ["java.base/java.lang"], + ) + + analysis_test( + name = name, + impl = _test_merge_add_exports_impl, + target = name + "/merge", + ) + +def _test_merge_add_exports_impl(env, target): + java_info_subject.from_target(env, target).module_flags().add_exports().contains_exactly( + ["java.base/java.lang"], + ) + +def add_exports_tests(name): + test_suite( + name = name, + tests = [ + _test_merge_add_exports, + ], + ) diff --git a/test/java/common/rules/merge_attrs_tests.bzl b/test/java/common/rules/merge_attrs_tests.bzl index 84b340e3..bea71adc 100644 --- a/test/java/common/rules/merge_attrs_tests.bzl +++ b/test/java/common/rules/merge_attrs_tests.bzl @@ -1,4 +1,4 @@ -"""Tests for merge_attrsfunction""" +"""Tests for merge_attrs function""" load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") load( diff --git a/test/java/testutil/cc_info_subject.bzl b/test/java/testutil/cc_info_subject.bzl index 2d7dca12..b50ff2e6 100644 --- a/test/java/testutil/cc_info_subject.bzl +++ b/test/java/testutil/cc_info_subject.bzl @@ -22,6 +22,7 @@ def _new_cc_info_linking_context_subject(cc_info, meta): public = struct( equals = lambda other: _cc_info_linking_context_equals(self.actual, other, self.meta), library_files = lambda: _new_library_files_subject(self.actual, self.meta), + static_library_files = lambda: _new_static_library_files_subject(self.actual, self.meta), ) return public @@ -43,6 +44,17 @@ def _new_library_files_subject(linking_context, meta): meta = meta.derive("library_files"), ) +def _new_static_library_files_subject(linking_context, meta): + static_libraries = [] + for input in linking_context.linker_inputs.to_list(): + for lib in input.libraries: + if lib.static_library: + static_libraries.append(lib.static_library) + return subjects.depset_file( + depset(static_libraries), + meta = meta.derive("static_library_files"), + ) + def _cc_info_linking_context_equals(actual, expected, meta): if actual == expected: return @@ -87,6 +99,7 @@ def _get_singleton(seq): return seq[0] cc_info_subject = struct( + new_from_cc_info = _new_cc_info_subject, new_from_java_info = lambda java_info, meta: _new_cc_info_subject(java_info.cc_link_params_info, meta.derive("cc_link_params_info")), libraries_to_link = _new_cc_info_libraries_to_link_subject, ) diff --git a/test/java/testutil/java_runtime_info_subject.bzl b/test/java/testutil/java_runtime_info_subject.bzl index ad68fead..bb6ae52c 100644 --- a/test/java/testutil/java_runtime_info_subject.bzl +++ b/test/java/testutil/java_runtime_info_subject.bzl @@ -3,6 +3,7 @@ load("@rules_testing//lib:truth.bzl", "subjects", "truth") load("@rules_testing//lib:util.bzl", "TestingAspectInfo") load("//java/common:java_common.bzl", "java_common") +load(":cc_info_subject.bzl", "cc_info_subject") def _new_java_runtime_info_subject(java_runtime_info, meta): self = struct( @@ -10,11 +11,19 @@ def _new_java_runtime_info_subject(java_runtime_info, meta): meta = meta.derive("JavaRuntimeInfo"), ) public = struct( + hermetic_static_libs = lambda: _new_hermetic_static_libs_subject(self.actual.hermetic_static_libs, self.meta.derive("hermetic_static_libs")), java_home = lambda: _new_path_string_subject(self.actual.java_home, self.meta.derive("java_home")), java_home_runfiles_path = lambda: _new_path_string_subject(self.actual.java_home_runfiles_path, self.meta.derive("java_home_runfiles_path")), java_executable_exec_path = lambda: _new_path_string_subject(self.actual.java_executable_exec_path, self.meta.derive("java_executable_exec_path")), java_executable_runfiles_path = lambda: _new_path_string_subject(self.actual.java_executable_runfiles_path, self.meta.derive("java_executable_runfiles_path")), files = lambda: subjects.depset_file(self.actual.files, self.meta.derive("files")), + lib_ct_sym = lambda: subjects.file(self.actual.lib_ct_sym, self.meta.derive("lib_ct_sym")), + ) + return public + +def _new_hermetic_static_libs_subject(hermetic_static_libs, meta): + public = struct( + singleton = lambda: cc_info_subject.new_from_cc_info(_get_singleton(hermetic_static_libs), meta.derive("cc_info")), ) return public @@ -46,6 +55,11 @@ def _from_target(env, target): ), ) +def _get_singleton(seq): + if len(seq) != 1: + fail("expected singleton, got:", seq) + return seq[0] + java_runtime_info_subject = struct( new = _new_java_runtime_info_subject, from_target = _from_target, diff --git a/test/java/toolchains/java_runtime_tests.bzl b/test/java/toolchains/java_runtime_tests.bzl index 5ec2a061..0112b172 100644 --- a/test/java/toolchains/java_runtime_tests.bzl +++ b/test/java/toolchains/java_runtime_tests.bzl @@ -1,5 +1,6 @@ """Tests for the java_runtime rule""" +load("@rules_cc//cc:defs.bzl", "cc_import") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") @@ -353,6 +354,71 @@ def _test_java_home_generated_impl(env, target): "{gendir}/{package}/generated_java_home", ) +def _test_hermetic_static_libs(name): + util.helper_target( + cc_import, + name = name + "/libs", + static_library = "libStatic.a", + ) + util.helper_target( + java_runtime, + name = name + "/jvm", + lib_modules = name + "/gen_lib_modules", + hermetic_srcs = [name + "/hermetic.properties"], + hermetic_static_libs = [name + "/libs"], + ) + + analysis_test( + name = name, + impl = _test_hermetic_static_libs_impl, + target = name + "/jvm", + ) + +def _test_hermetic_static_libs_impl(env, target): + cc_info = java_runtime_info_subject.from_target(env, target).hermetic_static_libs().singleton() + cc_info.linking_context().static_library_files().contains_exactly(["{package}/libStatic.a"]) + +def _test_implicit_lib_ct_sym(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + srcs = [ + name + "/java", + name + "/jvm/implicit/lib/ct.sym", + ], + ) + analysis_test( + name = name, + impl = _test_implicit_lib_ct_sym_impl, + target = name + "/jvm", + ) + +def _test_implicit_lib_ct_sym_impl(env, target): + java_runtime_info_subject.from_target(env, target).lib_ct_sym().short_path_equals( + "{package}/{name}/implicit/lib/ct.sym", + ) + +def _test_explicit_lib_ct_sym(name): + util.helper_target( + java_runtime, + name = name + "/jvm", + srcs = [ + name + "/java", + name + "/jvm/implicit/lib/ct.sym", + ], + lib_ct_sym = name + "/jvm/explicit/lib/ct.sym", + ) + analysis_test( + name = name, + impl = _test_explicit_lib_ct_sym_impl, + target = name + "/jvm", + ) + +def _test_explicit_lib_ct_sym_impl(env, target): + java_runtime_info_subject.from_target(env, target).lib_ct_sym().short_path_equals( + "{package}/{name}/explicit/lib/ct.sym", + ) + def java_runtime_tests(name): test_suite( name = name, @@ -371,5 +437,8 @@ def java_runtime_tests(name): _test_make_variables, _test_no_srcs, _test_java_home_generated, + _test_hermetic_static_libs, + _test_implicit_lib_ct_sym, + _test_explicit_lib_ct_sym, ], ) From b4301859e168f15a58d36fda9009f1f1efca81a4 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 9 Mar 2026 09:29:32 -0700 Subject: [PATCH 436/465] Remove deleted pipeline from `README.md` (ignore-relnotes) PiperOrigin-RevId: 880896423 Change-Id: I82f17552123b20d17a3cfc8f9ec23d4443c96197 --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 52be4f9d..c9d62dc2 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,6 @@ # rules_java -* Postsubmit [![Build status](https://badge.buildkite.com/d4f950ef5f481b8ca066624ba06c238fa1446d84a057ddbf89.svg?branch=master)](https://buildkite.com/bazel/rules-java-java) -* Postsubmit + Current Bazel Incompatible Flags [![Build status](https://badge.buildkite.com/ef265d270238c02aff65106a0b861abb9265efacdf4af399c3.svg?branch=master)](https://buildkite.com/bazel/rules-java-plus-bazelisk-migrate) +[![Build status](https://badge.buildkite.com/d4f950ef5f481b8ca066624ba06c238fa1446d84a057ddbf89.svg?branch=master)](https://buildkite.com/bazel/rules-java-java) Java Rules for Bazel https://bazel.build. @@ -22,6 +21,6 @@ Add a load like: ```build load("@rules_java//java:java_library.bzl", "java_library") ``` -to your `BUILD` / `BUILD.bazel` / bzl` files +to your `BUILD` / `BUILD.bazel` / `*.bzl` files For detailed docs on the core rules, see https://bazel.build/reference/be/java From cfa04565277c6a1d0f13979621efaf412455ef08 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Mar 2026 06:33:32 -0700 Subject: [PATCH 437/465] Implement the easy java_test unit tests in Starlark. PiperOrigin-RevId: 881395705 Change-Id: I63ec4d6489a15fd854b75176a3a216e715bded6a --- test/java/bazel/rules/BUILD.bazel | 3 + test/java/bazel/rules/java_test_tests.bzl | 44 ++++++ test/java/common/rules/java_test_tests.bzl | 159 +++++++++++++++++++++ 3 files changed, 206 insertions(+) create mode 100644 test/java/bazel/rules/java_test_tests.bzl diff --git a/test/java/bazel/rules/BUILD.bazel b/test/java/bazel/rules/BUILD.bazel index 01655c20..6f97d15a 100644 --- a/test/java/bazel/rules/BUILD.bazel +++ b/test/java/bazel/rules/BUILD.bazel @@ -1,9 +1,12 @@ load(":java_binary_tests.bzl", "java_binary_tests") load(":java_library_tests.bzl", "java_library_tests") load(":java_plugin_tests.bzl", "java_plugin_tests") +load(":java_test_tests.bzl", "java_test_tests") java_binary_tests(name = "java_binary_tests") java_library_tests(name = "java_library_tests") java_plugin_tests(name = "java_plugin_tests") + +java_test_tests(name = "java_test_tests") diff --git a/test/java/bazel/rules/java_test_tests.bzl b/test/java/bazel/rules/java_test_tests.bzl new file mode 100644 index 00000000..9ee618d8 --- /dev/null +++ b/test/java/bazel/rules/java_test_tests.bzl @@ -0,0 +1,44 @@ +"""Tests for the Bazel java_test rule""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching", "subjects") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_test.bzl", "java_test") + +def _test_deduced_test_class(name): + util.helper_target( + java_test, + name = name + "/foo", + srcs = [name + "/Foo.java"], + ) + + analysis_test( + name = name, + impl = _test_deduced_test_class_impl, + target = name + "/foo", + ) + +def _test_deduced_test_class_impl(env, target): + executable = target[DefaultInfo].files_to_run.executable.short_path + assert_action = env.expect.that_target(target).action_generating(executable) + + if assert_action.actual.substitutions: + # TemplateExpansion action on linux/mac + assert_jvm_flags = assert_action.substitutions().get( + "%jvm_flags%", + factory = lambda v, meta: subjects.collection([v], meta), + ) + else: + # Windows + assert_jvm_flags = assert_action.argv() + assert_jvm_flags.contains_predicate( + matching.str_matches("-Dbazel.test_suite=bazel.rules.test_deduced_test_class.foo"), + ) + +def java_test_tests(name): + test_suite( + name = name, + tests = [ + _test_deduced_test_class, + ], + ) diff --git a/test/java/common/rules/java_test_tests.bzl b/test/java/common/rules/java_test_tests.bzl index f4db104b..13362dc3 100644 --- a/test/java/common/rules/java_test_tests.bzl +++ b/test/java/common/rules/java_test_tests.bzl @@ -1,5 +1,6 @@ """Tests for the java_test rule""" +load("@bazel_features//:features.bzl", "bazel_features") load("@rules_cc//cc:cc_binary.bzl", "cc_binary") load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") @@ -7,8 +8,86 @@ load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_test.bzl", "java_test") +load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") +def _test_java_test_is_test_only(name): + util.helper_target( + java_test, + name = name + "/test", + srcs = [name + "/Test.java"], + ) + + util.helper_target( + java_library, + name = name + "/lib", + srcs = [name + "/Lib.java"], + deps = [name + "/test"], + ) + + analysis_test( + name = name, + impl = _test_java_test_is_test_only_impl, + target = name + "/lib", + expect_failure = True, + ) + +def _test_java_test_is_test_only_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("non-test target '*/lib' depends on testonly target '*/test'"), + ) + +def _test_deps_without_srcs_fails(name): + util.helper_target( + rule = java_library, + name = name + "/lib", + srcs = [name + "/Lib.java"], + ) + + util.helper_target( + rule = java_test, + name = name + "/test", + deps = [name + "/lib"], + ) + + analysis_test( + name = name, + target = name + "/test", + impl = _test_deps_without_srcs_fails_impl, + expect_failure = True, + ) + +def _test_deps_without_srcs_fails_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.contains("deps not allowed without srcs"), + ) + +def _test_fix_deps_tool(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + always_passes(name) + return + util.helper_target( + rule = java_test, + name = name + "/test", + srcs = [name + "/Test.java"], + ) + + analysis_test( + name = name, + target = name + "/test", + impl = _test_fix_deps_tool_impl, + config_settings = { + "//command_line_option:experimental_fix_deps_tool": "customfixer", + }, + ) + +def _test_fix_deps_tool_impl(env, target): + assert_compile_action = env.expect.that_target(target).action_named("Javac") + assert_compile_action.argv().contains_at_least([ + "--experimental_fix_deps_tool", + "customfixer", + ]).in_order() + def _test_java_test_propagates_direct_native_libraries(name): util.helper_target( cc_library, @@ -74,10 +153,90 @@ def _test_java_test_propagates_direct_native_libraries_impl(env, target): matching.str_matches("-Djava.library.path=${JAVA_RUNFILES}/*/test_java_test_propagates_direct_native_libraries"), ) +def _test_coverage_uses_coverage_runner_for_main(name): + util.helper_target( + rule = java_test, + name = name + "/test", + srcs = [name + "/Test.java"], + ) + + analysis_test( + name = name, + impl = _test_coverage_uses_coverage_runner_for_main_impl, + target = name + "/test", + config_settings = { + "//command_line_option:collect_code_coverage": True, + }, + ) + +def _test_coverage_uses_coverage_runner_for_main_impl(env, target): + executable = target[DefaultInfo].files_to_run.executable.short_path + assert_action = env.expect.that_target(target).action_generating(executable) + if assert_action.actual.substitutions: + assert_java_start_class = assert_action.substitutions().get( + "%java_start_class%", + factory = lambda v, meta: subjects.str(v, meta.derive("java_start_class")), + ) + assert_java_start_class.contains("com.google.testing.coverage.JacocoCoverageRunner") + else: + # Windows + assert_java_start_class = assert_action.argv() + assert_java_start_class.contains("java_start_class=com.google.testing.coverage.JacocoCoverageRunner") + +def _test_stamp_values(name): + util.helper_target( + rule = java_test, + name = name + "/stamp_true", + srcs = [name + "/Test.java"], + stamp = True, + ) + + util.helper_target( + rule = java_test, + name = name + "/stamp_false", + srcs = [name + "/Test.java"], + stamp = False, + ) + + util.helper_target( + rule = java_test, + name = name + "/stamp_auto", + srcs = [name + "/Test.java"], + stamp = -1, + ) + + util.helper_target( + rule = java_test, + name = name + "/stamp_default", + srcs = [name + "/Test.java"], + ) + + analysis_test( + name = name, + targets = { + "stamp": name + "/stamp_true", + "nostamp": name + "/stamp_false", + "autostamp": name + "/stamp_auto", + "defaultstamp": name + "/stamp_default", + }, + impl = _test_stamp_values_impl, + ) + +def _test_stamp_values_impl(env, targets): + env.expect.that_target(targets.stamp).attr("stamp", factory = subjects.int).equals(1) + env.expect.that_target(targets.nostamp).attr("stamp", factory = subjects.int).equals(0) + env.expect.that_target(targets.defaultstamp).attr("stamp", factory = subjects.int).equals(0) + env.expect.that_target(targets.autostamp).attr("stamp", factory = subjects.int).equals(-1) + def java_test_tests(name): test_suite( name = name, tests = [ + _test_java_test_is_test_only, + _test_deps_without_srcs_fails, + _test_fix_deps_tool, _test_java_test_propagates_direct_native_libraries, + _test_coverage_uses_coverage_runner_for_main, + _test_stamp_values, ], ) From 0508ac3d647638dbd8b59d4d54f43dfb89f65f00 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 10 Mar 2026 07:16:51 -0700 Subject: [PATCH 438/465] Support embedding stamping info from bazel in `java_single_jar` A new attribute `stamp` controls the Bazel build info included in the output: - `stamp = 1`: Always embed Bazel build information, even in `--nostamp` builds. - `stamp = 0`: Embed Bazel build information with constant values even in `--stamp` builds. - `stamp = -1`: Embedding of Bazel build information is controlled by the `--[no]stamp` flag. The above only takes effect when `exclude_build_data = False` (default is `True`). It is an error to specify `stamp = 1` without `exclude_build_data = False`. Fixes https://github.com/bazelbuild/rules_java/issues/352 PiperOrigin-RevId: 881412734 Change-Id: I876b3a3b328eb363ad112dfc0fdfe599de03b164 --- MODULE.bazel | 9 +- java/common/BUILD | 4 +- java/common/rules/BUILD | 6 +- java/common/rules/impl/BUILD | 2 +- .../rules/impl/java_binary_deploy_jar.bzl | 11 +- java/common/rules/impl/java_helper.bzl | 10 ++ java/common/rules/java_single_jar.bzl | 25 ++- test/java/common/rules/BUILD | 3 + .../common/rules/java_single_jar_tests.bzl | 164 ++++++++++++++++++ 9 files changed, 210 insertions(+), 24 deletions(-) create mode 100644 test/java/common/rules/java_single_jar_tests.bzl diff --git a/MODULE.bazel b/MODULE.bazel index 204b8e88..e98ca3d1 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -6,14 +6,7 @@ module( ) bazel_dep(name = "platforms", version = "0.0.11") -bazel_dep(name = "rules_cc", version = "0.2.13") -archive_override( - module_name = "rules_cc", - integrity = "sha256-y3RA9zEyB7HqBXVTgrlFmvfJARcEDzILe2ugNGC4ZrE=", - strip_prefix = "rules_cc-b5a65591334f74371f4d75003768957a740cd868", - urls = ["https://github.com/bazelbuild/rules_cc/archive/b5a65591334f74371f4d75003768957a740cd868.tar.gz"], -) - +bazel_dep(name = "rules_cc", version = "0.2.17") bazel_dep(name = "bazel_features", version = "1.30.0") bazel_dep(name = "bazel_skylib", version = "1.6.1") bazel_dep(name = "protobuf", version = "32.1", repo_name = "com_google_protobuf") diff --git a/java/common/BUILD b/java/common/BUILD index 9958a883..9881236a 100644 --- a/java/common/BUILD +++ b/java/common/BUILD @@ -36,9 +36,7 @@ bzl_library( name = "semantics_bzl", srcs = ["java_semantics.bzl"], visibility = ["//visibility:public"], - deps = [ - "@rules_cc//cc/common", - ], + deps = ["@rules_cc//cc/common:cc_helper_bzl"], ) bzl_library( diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD index f6fde9d4..4c24d073 100644 --- a/java/common/rules/BUILD +++ b/java/common/rules/BUILD @@ -35,7 +35,11 @@ bzl_library( name = "java_single_jar_bzl", srcs = ["java_single_jar.bzl"], visibility = ["//java:__subpackages__"], - deps = ["//java/common"], + deps = [ + "//java/common", + "//java/common:semantics_bzl", + "//java/common/rules/impl:java_helper_bzl", + ], ) bzl_library( diff --git a/java/common/rules/impl/BUILD b/java/common/rules/impl/BUILD index 6ab41376..70adeccd 100644 --- a/java/common/rules/impl/BUILD +++ b/java/common/rules/impl/BUILD @@ -29,7 +29,7 @@ bzl_library( bzl_library( name = "java_helper_bzl", srcs = ["java_helper.bzl"], - visibility = ["//visibility:private"], + visibility = ["//java:__subpackages__"], deps = [ "//java/common:semantics_bzl", "//java/common/rules:java_helper_bzl", diff --git a/java/common/rules/impl/java_binary_deploy_jar.bzl b/java/common/rules/impl/java_binary_deploy_jar.bzl index 7b7d69d1..d6add141 100644 --- a/java/common/rules/impl/java_binary_deploy_jar.bzl +++ b/java/common/rules/impl/java_binary_deploy_jar.bzl @@ -19,15 +19,6 @@ load(":java_helper.bzl", "helper") # copybara: default visibility -def _get_build_info(ctx, stamp): - if helper.is_stamping_enabled(ctx, stamp): - # Makes the target depend on BUILD_INFO_KEY, which helps to discover stamped targets - # See b/326620485 for more details. - ctx.version_file # buildifier: disable=no-effect - return ctx.attr._build_info_translator[OutputGroupInfo].non_redacted_build_info_files.to_list() - else: - return ctx.attr._build_info_translator[OutputGroupInfo].redacted_build_info_files.to_list() - def create_deploy_archives( ctx, java_attrs, @@ -70,7 +61,7 @@ def create_deploy_archives( order = "preorder", ) multi_release = ctx.fragments.java.multi_release_deploy_jars - build_info_files = _get_build_info(ctx, ctx.attr.stamp) + build_info_files = helper.get_build_info(ctx, ctx.attr.stamp) build_target = str(ctx.label) manifest_lines = ctx.attr.deploy_manifest_lines + extra_manifest_lines create_deploy_archive( diff --git a/java/common/rules/impl/java_helper.bzl b/java/common/rules/impl/java_helper.bzl index e45fac9d..638878ba 100644 --- a/java/common/rules/impl/java_helper.bzl +++ b/java/common/rules/impl/java_helper.bzl @@ -241,6 +241,15 @@ def _is_stamping_enabled(ctx, stamp): # stamp == -1 / auto return int(ctx.configuration.stamp_binaries()) +def _get_build_info(ctx, stamp): + if helper.is_stamping_enabled(ctx, stamp): + # Makes the target depend on BUILD_INFO_KEY, which helps to discover stamped targets + # See b/326620485 for more details. + ctx.version_file # buildifier: disable=no-effect + return ctx.attr._build_info_translator[OutputGroupInfo].non_redacted_build_info_files.to_list() + else: + return ctx.attr._build_info_translator[OutputGroupInfo].redacted_build_info_files.to_list() + helper = struct( collect_all_targets_as_deps = _collect_all_targets_as_deps, filter_launcher_for_target = _filter_launcher_for_target, @@ -265,6 +274,7 @@ helper = struct( detokenize_javacopts = _loading_phase_helper.detokenize_javacopts, tokenize_javacopts = _loading_phase_helper.tokenize_javacopts, is_stamping_enabled = _is_stamping_enabled, + get_build_info = _get_build_info, get_relative = _loading_phase_helper.get_relative, has_target_constraints = _loading_phase_helper.has_target_constraints, ) diff --git a/java/common/rules/java_single_jar.bzl b/java/common/rules/java_single_jar.bzl index 95b7ca2e..c9552755 100644 --- a/java/common/rules/java_single_jar.bzl +++ b/java/common/rules/java_single_jar.bzl @@ -15,6 +15,8 @@ load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules/impl:java_helper.bzl", "helper") # copybara: default visibility @@ -69,8 +71,15 @@ def _bazel_java_single_jar_impl(ctx): else: fail("\"compress\" attribute (%s) must be: yes, no, preserve." % ctx.attr.compress) + if ctx.attr.exclude_build_data and ctx.attr.stamp == 1: + fail("Enabling stamping has not effect with exclude_build_data enabled") + + build_info_files = [] if ctx.attr.exclude_build_data: args.add("--exclude_build_data") + else: + build_info_files = helper.get_build_info(ctx, ctx.attr.stamp) + args.add_all(build_info_files, before_each = "--build_info_file") if ctx.attr.multi_release: args.add("--multi_release") @@ -78,7 +87,7 @@ def _bazel_java_single_jar_impl(ctx): args.add("--exclude_pattern", ctx.attr.exclude_pattern) ctx.actions.run( - inputs = inputs, + inputs = depset(build_info_files, transitive = [inputs]), outputs = [ctx.outputs.output], arguments = [args], progress_message = "Merging into %s" % ctx.outputs.output.short_path, @@ -138,6 +147,20 @@ bazel_java_single_jar = rule( executable = True, ), "output": attr.output(), + "stamp": attr.int( + doc = """ + Whether to embed extra Bazel build information into the build_data.properties file: + * `stamp = 1`: Always embed Bazel build information, even in `--nostamp` builds. + * `stamp = 0`: Embed Bazel build information with constant values, even in `--stamp` builds. + * `stamp = -1`: Embedding of Bazel build information is controlled by the `--[no]stamp` flag. + + Note: whether the output contains the build_data.properties file is controlled + by the `exclude_build_data` attribute. + """, + default = 0, + values = [-1, 0, 1], + ), + "_build_info_translator": attr.label(default = semantics.BUILD_INFO_TRANSLATOR_LABEL), }, implementation = _bazel_java_single_jar_impl, doc = """ diff --git a/test/java/common/rules/BUILD b/test/java/common/rules/BUILD index 32870da7..8e74a2a0 100644 --- a/test/java/common/rules/BUILD +++ b/test/java/common/rules/BUILD @@ -4,6 +4,7 @@ load(":java_binary_tests.bzl", "java_binary_tests") load(":java_import_tests.bzl", "java_import_tests") load(":java_library_tests.bzl", "java_library_tests") load(":java_plugin_tests.bzl", "java_plugin_tests") +load(":java_single_jar_tests.bzl", "java_single_jar_tests") load(":java_test_tests.bzl", "java_test_tests") load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") @@ -21,6 +22,8 @@ java_library_tests(name = "java_library_tests") java_import_tests(name = "java_import_tests") +java_single_jar_tests(name = "java_single_jar_tests") + java_test_tests(name = "java_test_tests") add_exports_tests(name = "add_exports_tests") diff --git a/test/java/common/rules/java_single_jar_tests.bzl b/test/java/common/rules/java_single_jar_tests.bzl new file mode 100644 index 00000000..8ea43da8 --- /dev/null +++ b/test/java/common/rules/java_single_jar_tests.bzl @@ -0,0 +1,164 @@ +"""Tests for the java_single_jar rule""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_single_jar.bzl", "java_single_jar") +load("//java/common:java_semantics.bzl", "semantics") + +def _label_to_bin_path(label): + segments = ["{bindir}"] + if label.repo_name: + segments.extend(["external", label.repo_name]) + segments.append(label.package) + return "/".join(segments) + +_BUILD_INFO_PATH = _label_to_bin_path(Label(semantics.BUILD_INFO_TRANSLATOR_LABEL)) + +def _test_java_single_jar_basic(name): + util.helper_target( + java_single_jar, + name = name + "/jar", + deps = ["1.jar", "2.jar"], + ) + + analysis_test( + name = name, + impl = _test_java_single_jar_basic_impl, + target = name + "/jar", + ) + +def _test_java_single_jar_basic_impl(env, target): + assert_that_action = env.expect.that_target(target).action_named("JavaSingleJar") + assert_that_action.argv().contains_at_least([ + "--sources", + "{package}/1.jar", + "{package}/2.jar", + "--output", + "{bindir}/{package}/{name}.jar", + "--normalize", + "--dont_change_compression", + "--exclude_build_data", + "--multi_release", + ]).in_order() + +def _test_java_single_jar_force_enable_stamping(name): + util.helper_target( + java_single_jar, + name = name + "/jar", + stamp = 1, + exclude_build_data = False, + ) + + analysis_test( + name = name, + impl = _test_java_single_jar_force_enable_stamping_impl, + target = name + "/jar", + ) + +def _test_java_single_jar_force_enable_stamping_impl(env, target): + assert_that_action = env.expect.that_target(target).action_named("JavaSingleJar") + assert_that_action.contains_flag_values([ + ("--build_info_file", _BUILD_INFO_PATH + "/non_volatile_file.properties"), + ("--build_info_file", _BUILD_INFO_PATH + "/volatile_file.properties"), + ]) + +def _test_java_single_jar_force_disable_stamping(name): + util.helper_target( + java_single_jar, + name = name + "/jar", + stamp = 0, + exclude_build_data = False, + ) + + analysis_test( + name = name, + impl = _test_java_single_jar_force_disable_stamping_impl, + target = name + "/jar", + ) + +def _test_java_single_jar_force_disable_stamping_impl(env, target): + assert_that_action = env.expect.that_target(target).action_named("JavaSingleJar") + assert_that_action.contains_flag_values([ + ("--build_info_file", _BUILD_INFO_PATH + "/redacted_file.properties"), + ]) + +def _test_java_single_jar_stamping_enabled_build_data_excluded_fails(name): + util.helper_target( + java_single_jar, + name = name + "/jar", + stamp = 1, + exclude_build_data = True, + ) + + analysis_test( + name = name, + impl = _test_java_single_jar_stamping_enabled_build_data_excluded_fails_impl, + target = name + "/jar", + expect_failure = True, + ) + +def _test_java_single_jar_stamping_enabled_build_data_excluded_fails_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("Enabling stamping has not effect with exclude_build_data enabled"), + ) + +def _test_java_single_jar_stamp_attr_auto_stamp_flag_enabled(name): + util.helper_target( + java_single_jar, + name = name + "/jar", + stamp = -1, + exclude_build_data = False, + ) + + analysis_test( + name = name, + impl = _test_java_single_jar_stamp_attr_auto_stamp_flag_enabled_impl, + target = name + "/jar", + config_settings = { + "//command_line_option:stamp": True, + }, + ) + +def _test_java_single_jar_stamp_attr_auto_stamp_flag_enabled_impl(env, target): + assert_that_action = env.expect.that_target(target).action_named("JavaSingleJar") + assert_that_action.contains_flag_values([ + ("--build_info_file", _BUILD_INFO_PATH + "/non_volatile_file.properties"), + ("--build_info_file", _BUILD_INFO_PATH + "/volatile_file.properties"), + ]) + +def _test_java_single_jar_stamp_attr_auto_stamp_flag_disabled(name): + util.helper_target( + java_single_jar, + name = name + "/jar", + stamp = -1, + exclude_build_data = False, + ) + + analysis_test( + name = name, + impl = _test_java_single_jar_stamp_attr_auto_stamp_flag_disabled_impl, + target = name + "/jar", + config_settings = { + "//command_line_option:stamp": False, + }, + ) + +def _test_java_single_jar_stamp_attr_auto_stamp_flag_disabled_impl(env, target): + assert_that_action = env.expect.that_target(target).action_named("JavaSingleJar") + assert_that_action.contains_flag_values([ + ("--build_info_file", _BUILD_INFO_PATH + "/redacted_file.properties"), + ]) + +def java_single_jar_tests(name): + test_suite( + name = name, + tests = [ + _test_java_single_jar_basic, + _test_java_single_jar_force_enable_stamping, + _test_java_single_jar_force_disable_stamping, + _test_java_single_jar_stamping_enabled_build_data_excluded_fails, + _test_java_single_jar_stamp_attr_auto_stamp_flag_enabled, + _test_java_single_jar_stamp_attr_auto_stamp_flag_disabled, + ], + ) From 123b37028abe4ae6913c7a10a079f84d6c70e517 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 11 Mar 2026 05:33:31 -0700 Subject: [PATCH 439/465] Improve tests added in https://github.com/bazelbuild/rules_java/commit/0508ac3d647638dbd8b59d4d54f43dfb89f65f00 Replace the bespoke label -> file paths conversion with actual artifacts from the build info rule. (ignore-relnotes) PiperOrigin-RevId: 881959996 Change-Id: I67dbb7e9eab00bfef6b3db5ae414f81078f965bc --- .../common/rules/java_single_jar_tests.bzl | 59 ++++++++++--------- 1 file changed, 32 insertions(+), 27 deletions(-) diff --git a/test/java/common/rules/java_single_jar_tests.bzl b/test/java/common/rules/java_single_jar_tests.bzl index 8ea43da8..488aab3f 100644 --- a/test/java/common/rules/java_single_jar_tests.bzl +++ b/test/java/common/rules/java_single_jar_tests.bzl @@ -6,15 +6,6 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_single_jar.bzl", "java_single_jar") load("//java/common:java_semantics.bzl", "semantics") -def _label_to_bin_path(label): - segments = ["{bindir}"] - if label.repo_name: - segments.extend(["external", label.repo_name]) - segments.append(label.package) - return "/".join(segments) - -_BUILD_INFO_PATH = _label_to_bin_path(Label(semantics.BUILD_INFO_TRANSLATOR_LABEL)) - def _test_java_single_jar_basic(name): util.helper_target( java_single_jar, @@ -53,14 +44,17 @@ def _test_java_single_jar_force_enable_stamping(name): analysis_test( name = name, impl = _test_java_single_jar_force_enable_stamping_impl, - target = name + "/jar", + targets = { + "jar": name + "/jar", + "build_info": semantics.BUILD_INFO_TRANSLATOR_LABEL, + }, ) -def _test_java_single_jar_force_enable_stamping_impl(env, target): - assert_that_action = env.expect.that_target(target).action_named("JavaSingleJar") +def _test_java_single_jar_force_enable_stamping_impl(env, targets): + assert_that_action = env.expect.that_target(targets.jar).action_named("JavaSingleJar") assert_that_action.contains_flag_values([ - ("--build_info_file", _BUILD_INFO_PATH + "/non_volatile_file.properties"), - ("--build_info_file", _BUILD_INFO_PATH + "/volatile_file.properties"), + ("--build_info_file", f.path) + for f in targets.build_info[OutputGroupInfo].non_redacted_build_info_files.to_list() ]) def _test_java_single_jar_force_disable_stamping(name): @@ -74,13 +68,17 @@ def _test_java_single_jar_force_disable_stamping(name): analysis_test( name = name, impl = _test_java_single_jar_force_disable_stamping_impl, - target = name + "/jar", + targets = { + "jar": name + "/jar", + "build_info": semantics.BUILD_INFO_TRANSLATOR_LABEL, + }, ) -def _test_java_single_jar_force_disable_stamping_impl(env, target): - assert_that_action = env.expect.that_target(target).action_named("JavaSingleJar") +def _test_java_single_jar_force_disable_stamping_impl(env, targets): + assert_that_action = env.expect.that_target(targets.jar).action_named("JavaSingleJar") assert_that_action.contains_flag_values([ - ("--build_info_file", _BUILD_INFO_PATH + "/redacted_file.properties"), + ("--build_info_file", f.path) + for f in targets.build_info[OutputGroupInfo].redacted_build_info_files.to_list() ]) def _test_java_single_jar_stamping_enabled_build_data_excluded_fails(name): @@ -114,17 +112,20 @@ def _test_java_single_jar_stamp_attr_auto_stamp_flag_enabled(name): analysis_test( name = name, impl = _test_java_single_jar_stamp_attr_auto_stamp_flag_enabled_impl, - target = name + "/jar", + targets = { + "jar": name + "/jar", + "build_info": semantics.BUILD_INFO_TRANSLATOR_LABEL, + }, config_settings = { "//command_line_option:stamp": True, }, ) -def _test_java_single_jar_stamp_attr_auto_stamp_flag_enabled_impl(env, target): - assert_that_action = env.expect.that_target(target).action_named("JavaSingleJar") +def _test_java_single_jar_stamp_attr_auto_stamp_flag_enabled_impl(env, targets): + assert_that_action = env.expect.that_target(targets.jar).action_named("JavaSingleJar") assert_that_action.contains_flag_values([ - ("--build_info_file", _BUILD_INFO_PATH + "/non_volatile_file.properties"), - ("--build_info_file", _BUILD_INFO_PATH + "/volatile_file.properties"), + ("--build_info_file", f.path) + for f in targets.build_info[OutputGroupInfo].non_redacted_build_info_files.to_list() ]) def _test_java_single_jar_stamp_attr_auto_stamp_flag_disabled(name): @@ -138,16 +139,20 @@ def _test_java_single_jar_stamp_attr_auto_stamp_flag_disabled(name): analysis_test( name = name, impl = _test_java_single_jar_stamp_attr_auto_stamp_flag_disabled_impl, - target = name + "/jar", + targets = { + "jar": name + "/jar", + "build_info": semantics.BUILD_INFO_TRANSLATOR_LABEL, + }, config_settings = { "//command_line_option:stamp": False, }, ) -def _test_java_single_jar_stamp_attr_auto_stamp_flag_disabled_impl(env, target): - assert_that_action = env.expect.that_target(target).action_named("JavaSingleJar") +def _test_java_single_jar_stamp_attr_auto_stamp_flag_disabled_impl(env, targets): + assert_that_action = env.expect.that_target(targets.jar).action_named("JavaSingleJar") assert_that_action.contains_flag_values([ - ("--build_info_file", _BUILD_INFO_PATH + "/redacted_file.properties"), + ("--build_info_file", f.path) + for f in targets.build_info[OutputGroupInfo].redacted_build_info_files.to_list() ]) def java_single_jar_tests(name): From cc7a75a0d94972bf7c3cf659c13f3e3f43d8a942 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 11 Mar 2026 07:55:38 -0700 Subject: [PATCH 440/465] Implement java_test tests checking for compile time deps on the test runner. Updates rules_testing to include https://github.com/bazelbuild/rules_testing/commit/04a1219 PiperOrigin-RevId: 882013418 Change-Id: I077f6e957968e1b343765364866f24cae0cd3ad6 --- MODULE.bazel | 6 ++-- test/java/common/rules/java_test_tests.bzl | 40 ++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index e98ca3d1..769902b4 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -124,9 +124,9 @@ bazel_dep(name = "rules_shell", version = "0.2.0", dev_dependency = True) bazel_dep(name = "rules_testing", dev_dependency = True) archive_override( module_name = "rules_testing", - integrity = "sha256-d/94Ix5IoGXk9rP1HjYKxPMH8ccwX5b1Qxs8BKg4WRg=", - strip_prefix = "rules_testing-ac97ba507116056cd489161b5e99dd8014685adc", - urls = ["https://github.com/bazelbuild/rules_testing/archive/ac97ba507116056cd489161b5e99dd8014685adc.tar.gz"], + integrity = "sha256-WYc72jM8jNK3m45vjWlmN6NB+95f6HAHnTkRaSaNisE=", + strip_prefix = "rules_testing-04a1219ee516ccdf3ffadfe3b28e5c634c9b90e1", + urls = ["https://github.com/bazelbuild/rules_testing/archive/04a1219ee516ccdf3ffadfe3b28e5c634c9b90e1.tar.gz"], ) test_repositories = use_extension("//test:repositories.bzl", "test_repositories_ext", dev_dependency = True) diff --git a/test/java/common/rules/java_test_tests.bzl b/test/java/common/rules/java_test_tests.bzl index 13362dc3..5c2001ca 100644 --- a/test/java/common/rules/java_test_tests.bzl +++ b/test/java/common/rules/java_test_tests.bzl @@ -8,6 +8,8 @@ load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_test.bzl", "java_test") +load("//java/common:java_info.bzl", "JavaInfo") +load("//java/common:java_semantics.bzl", "semantics") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") @@ -228,6 +230,43 @@ def _test_stamp_values_impl(env, targets): env.expect.that_target(targets.defaultstamp).attr("stamp", factory = subjects.int).equals(0) env.expect.that_target(targets.autostamp).attr("stamp", factory = subjects.int).equals(-1) +def _test_add_test_support_to_compile_time_deps_flag(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + always_passes(name) + return + util.helper_target( + rule = java_test, + name = name + "/test", + srcs = [name + "/Test.java"], + ) + + analysis_test( + name = name, + targets = { + "add_support": name + "/test", + "no_add_support": name + "/test", + }, + attrs = { + "test_runner": attr.label(default = semantics.JAVA_TEST_RUNNER_LABEL), + "add_support": { + "@config_settings": { + "//command_line_option:experimental_add_test_support_to_compile_time_deps": True, + }, + }, + "no_add_support": { + "@config_settings": { + "//command_line_option:experimental_add_test_support_to_compile_time_deps": False, + }, + }, + }, + impl = _test_add_test_support_to_compile_time_deps_flag_impl, + ) + +def _test_add_test_support_to_compile_time_deps_flag_impl(env, targets): + compile_jars = env.ctx.attr.test_runner[JavaInfo].compile_jars + env.expect.that_target(targets.add_support).action_named("Javac").inputs().contains_at_least(compile_jars.to_list()) + env.expect.that_target(targets.no_add_support).action_named("Javac").inputs().contains_none_of(compile_jars.to_list()) + def java_test_tests(name): test_suite( name = name, @@ -238,5 +277,6 @@ def java_test_tests(name): _test_java_test_propagates_direct_native_libraries, _test_coverage_uses_coverage_runner_for_main, _test_stamp_values, + _test_add_test_support_to_compile_time_deps_flag, ], ) From 635d5aba4f5a5beb9f7a86712ad12968229de88a Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 12 Mar 2026 08:01:48 -0700 Subject: [PATCH 441/465] Implement darwin test in java_test. PiperOrigin-RevId: 882593123 Change-Id: I4285d4304e748935c6198d1e9cc98199eb3d200f --- java/common/java_semantics.bzl | 2 + test/java/common/rules/java_test_tests.bzl | 49 ++++++++++++++++ test/java/common/testutil/BUILD | 1 + .../common/testutil/mock_cc_toolchain.bzl | 56 +++++++++++++++++++ .../common/testutil/mock_test_toolchain.bzl | 29 ++++++++++ 5 files changed, 137 insertions(+) create mode 100644 test/java/common/testutil/BUILD create mode 100644 test/java/common/testutil/mock_cc_toolchain.bzl create mode 100644 test/java/common/testutil/mock_test_toolchain.bzl diff --git a/java/common/java_semantics.bzl b/java/common/java_semantics.bzl index 31c0a006..58f957ef 100644 --- a/java/common/java_semantics.bzl +++ b/java/common/java_semantics.bzl @@ -105,6 +105,8 @@ semantics = struct( compatible_javac_options = _compatible_javac_options, LAUNCHER_FLAG_LABEL = Label("@bazel_tools//tools/jdk:launcher_flag_alias"), PROGUARD_ALLOWLISTER_LABEL = "@bazel_tools//tools/jdk:proguard_whitelister", + TOOLS_TEST_DEFAULT_TEST_TOOLCHAIN_TYPE = "@bazel_tools//tools/test:default_test_toolchain_type", + TOOLS_TEST_EMPTY_TOOLCHAIN = "@bazel_tools//tools/test:empty_toolchain", check_java_info_opens_exports = _check_java_info_opens_exports, DOCS = struct( for_attribute = lambda name: _DOCS.ATTRS.get(name, ""), diff --git a/test/java/common/rules/java_test_tests.bzl b/test/java/common/rules/java_test_tests.bzl index 5c2001ca..bd8e6850 100644 --- a/test/java/common/rules/java_test_tests.bzl +++ b/test/java/common/rules/java_test_tests.bzl @@ -10,6 +10,8 @@ load("//java:java_library.bzl", "java_library") load("//java:java_test.bzl", "java_test") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") +load("//test/java/common/testutil:mock_cc_toolchain.bzl", "mock_cc_toolchain") +load("//test/java/common/testutil:mock_test_toolchain.bzl", "mock_test_toolchains") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") @@ -267,6 +269,52 @@ def _test_add_test_support_to_compile_time_deps_flag_impl(env, targets): env.expect.that_target(targets.add_support).action_named("Javac").inputs().contains_at_least(compile_jars.to_list()) env.expect.that_target(targets.no_add_support).action_named("Javac").inputs().contains_none_of(compile_jars.to_list()) +def _test_mac_requires_darwin_for_execution(name): + util.helper_target( + rule = native.platform, + name = name + "/darwin_x86_64", + constraint_values = [ + "@platforms//os:macos", + "@platforms//cpu:x86_64", + ], + ) + + util.helper_target( + rule = java_test, + name = name + "/test", + srcs = [name + "/Test.java"], + use_launcher = False, + use_testrunner = 0, + ) + + util.helper_target( + rule = mock_cc_toolchain, + name = name + "/cc_toolchain", + cpu = "x86_64", + os = "macos", + ) + + toolchains = [Label(name + "/cc_toolchain")] + mock_test_toolchains( + name = name + "/test_toolchain", + cpu = "x86_64", + os = "macos", + ) + + analysis_test( + name = name, + target = name + "/test", + config_settings = { + "//command_line_option:platforms": [Label(name + "/darwin_x86_64")], + "//command_line_option:extra_toolchains": toolchains, + }, + impl = _test_mac_requires_darwin_for_execution_impl, + ) + +def _test_mac_requires_darwin_for_execution_impl(env, target): + env.expect.that_target(target).provider(testing.ExecutionInfo).requirements().contains_at_least( + {"requires-darwin": ""}, + ) + def java_test_tests(name): test_suite( name = name, @@ -278,5 +326,6 @@ def java_test_tests(name): _test_coverage_uses_coverage_runner_for_main, _test_stamp_values, _test_add_test_support_to_compile_time_deps_flag, + _test_mac_requires_darwin_for_execution, ], ) diff --git a/test/java/common/testutil/BUILD b/test/java/common/testutil/BUILD new file mode 100644 index 00000000..c2afbb31 --- /dev/null +++ b/test/java/common/testutil/BUILD @@ -0,0 +1 @@ +package(default_applicable_licenses = ["@rules_java//:license"]) diff --git a/test/java/common/testutil/mock_cc_toolchain.bzl b/test/java/common/testutil/mock_cc_toolchain.bzl new file mode 100644 index 00000000..6680938d --- /dev/null +++ b/test/java/common/testutil/mock_cc_toolchain.bzl @@ -0,0 +1,56 @@ +"""Fake cc_toolchain for testing arbitrary --platforms/--cpu""" + +load("@rules_cc//cc:find_cc_toolchain.bzl", "CC_TOOLCHAIN_TYPE") +load("@rules_cc//cc/common:cc_common.bzl", "cc_common") +load("@rules_cc//cc/toolchains:cc_toolchain.bzl", "cc_toolchain") +load("@rules_cc//cc/toolchains:cc_toolchain_config_info.bzl", "CcToolchainConfigInfo") + +def _mock_config_impl(ctx): + return [ + cc_common.create_cc_toolchain_config_info( + ctx = ctx, + toolchain_identifier = ctx.attr.id, + compiler = "nothing", + # These are deprecated but are mandatory parameters for older Bazel versions. + target_system_name = "deprecated_system_name", + target_cpu = "deprecated_cpu", + target_libc = "deprecated_libc", + ), + ] + +_mock_config = rule( + implementation = _mock_config_impl, + attrs = { + "id": attr.string(mandatory = True), + }, + provides = [CcToolchainConfigInfo], +) + +def mock_cc_toolchain(*, name, cpu, os, **kwargs): + _mock_config( + name = name + "_config", + id = cpu + "-" + os, + **kwargs + ) + cc_toolchain( + name = name + "_impl", + all_files = ":nothing", + as_files = ":nothing", + compiler_files = ":nothing", + dwp_files = ":nothing", + linker_files = ":nothing", + objcopy_files = ":nothing", + strip_files = ":nothing", + toolchain_config = name + "_config", + **kwargs + ) + native.toolchain( + name = name, + toolchain = name + "_impl", + toolchain_type = CC_TOOLCHAIN_TYPE, + target_compatible_with = [ + "@platforms//cpu:" + cpu, + "@platforms//os:" + os, + ], + **kwargs + ) diff --git a/test/java/common/testutil/mock_test_toolchain.bzl b/test/java/common/testutil/mock_test_toolchain.bzl new file mode 100644 index 00000000..cf73145e --- /dev/null +++ b/test/java/common/testutil/mock_test_toolchain.bzl @@ -0,0 +1,29 @@ +"""Fake test toolchain for testing arbitrary --platforms""" + +load("@bazel_features//:features.bzl", "bazel_features") +load("@rules_testing//lib:util.bzl", "util") +load("//java/common:java_semantics.bzl", "semantics") + +def mock_test_toolchains(name, cpu, os): + """Creates and returns a list of mock test toolchains for the given cpu and os if they're required. + + Args: + name: The name of the toolchain. + cpu: The cpu for toolchain should be compatible with. + os: The os the toolchain should be compatible with. + Returns: + A list of toolchain targets. + """ + if not bazel_features.toolchains.has_default_test_toolchain_type: + return [] + util.helper_target( + rule = native.toolchain, + name = name, + toolchain_type = Label(semantics.TOOLS_TEST_DEFAULT_TEST_TOOLCHAIN_TYPE), + toolchain = Label(semantics.TOOLS_TEST_EMPTY_TOOLCHAIN), + target_compatible_with = [ + "@platforms//os:" + os, + "@platforms//cpu:" + cpu, + ], + ) + return [native.package_relative_label(name)] From 983b13c81d346abf8e3cd2d58200bd13b8668a77 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 13 Mar 2026 09:26:09 -0700 Subject: [PATCH 442/465] Implement applicable --java_launcher tests in Starlark and open-source them. PiperOrigin-RevId: 883202557 Change-Id: Ib83a9fa044eded610be4789e7868d351f7205720 --- test/java/common/rules/BUILD | 3 + .../java/common/rules/java_launcher_tests.bzl | 71 +++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 test/java/common/rules/java_launcher_tests.bzl diff --git a/test/java/common/rules/BUILD b/test/java/common/rules/BUILD index 8e74a2a0..28d38349 100644 --- a/test/java/common/rules/BUILD +++ b/test/java/common/rules/BUILD @@ -2,6 +2,7 @@ load(":add_exports_tests.bzl", "add_exports_tests") load(":deploy_archive_builder_tests.bzl", "deploy_archive_builder_test_suite") load(":java_binary_tests.bzl", "java_binary_tests") load(":java_import_tests.bzl", "java_import_tests") +load(":java_launcher_tests.bzl", "java_launcher_tests") load(":java_library_tests.bzl", "java_library_tests") load(":java_plugin_tests.bzl", "java_plugin_tests") load(":java_single_jar_tests.bzl", "java_single_jar_tests") @@ -20,6 +21,8 @@ java_plugin_tests(name = "java_plugin_tests") java_library_tests(name = "java_library_tests") +java_launcher_tests(name = "java_launcher_tests") + java_import_tests(name = "java_import_tests") java_single_jar_tests(name = "java_single_jar_tests") diff --git a/test/java/common/rules/java_launcher_tests.bzl b/test/java/common/rules/java_launcher_tests.bzl new file mode 100644 index 00000000..6faaa93f --- /dev/null +++ b/test/java/common/rules/java_launcher_tests.bzl @@ -0,0 +1,71 @@ +"""Tests for the "launcher" attribute and "--java_launcher" flag.""" + +load("@rules_cc//cc:cc_binary.bzl", "cc_binary") +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:truth.bzl", "matching") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_binary.bzl", "java_binary") + +def _test_overridden_incompatible_launcher(name): + # Check analysis succeeds even though --java_launcher refers to an incompatible target + # when the "use_launcher" attribute is set to False. + util.helper_target( + rule = cc_binary, + name = name + "/launcher", + srcs = select({ + "@platforms//cpu:ppc": [name + "/launcher.cc"], + }), + ) + + util.helper_target( + rule = java_binary, + name = name + "/bin", + srcs = [name + "/Bin.java"], + use_launcher = False, + ) + + analysis_test( + name = name, + impl = lambda env, target: True, + target = name + "/bin", + config_settings = { + "//command_line_option:java_launcher": Label(name + "/launcher"), + "//command_line_option:cpu": "k8", + }, + ) + +def _test_launcher_with_create_executable_false_fails(name): + util.helper_target( + rule = cc_binary, + name = name + "/launcher", + srcs = [name + "/launcher.cc"], + ) + + util.helper_target( + rule = java_binary, + name = name + "/bin", + srcs = [name + "/Bin.java"], + launcher = name + "/launcher", + create_executable = False, + ) + + analysis_test( + name = name, + impl = _test_launcher_with_create_executable_false_fails_impl, + target = name + "/bin", + expect_failure = True, + ) + +def _test_launcher_with_create_executable_false_fails_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("launcher specified but create_executable is false"), + ) + +def java_launcher_tests(name): + test_suite( + name = name, + tests = [ + _test_overridden_incompatible_launcher, + _test_launcher_with_create_executable_false_fails, + ], + ) From 73bd40296fb7c529b79dbdbb2ce20f1cacaccda3 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 17 Mar 2026 05:40:03 -0700 Subject: [PATCH 443/465] Remove extra whitespace (ignore-relnotes) PiperOrigin-RevId: 884968144 Change-Id: I049060711f4c62930b5ff2c5cfa393966f99e92a --- java/common/rules/java_single_jar.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/common/rules/java_single_jar.bzl b/java/common/rules/java_single_jar.bzl index c9552755..ca768873 100644 --- a/java/common/rules/java_single_jar.bzl +++ b/java/common/rules/java_single_jar.bzl @@ -11,7 +11,7 @@ # 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. -"""Definition of the java_single_jar rule.""" +"""Definition of the java_single_jar rule.""" load("//java/common:java_common.bzl", "java_common") load("//java/common:java_info.bzl", "JavaInfo") From f08336996aba472204a47dafb6bddb398f88c274 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 20 Mar 2026 02:41:19 -0700 Subject: [PATCH 444/465] Update `rules_java`'s `CODEOWNERS` (ignore-relnotes) PiperOrigin-RevId: 886664168 Change-Id: I7eb1ab776ae6ceadd619e1e460988943466fe637 --- CODEOWNERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CODEOWNERS b/CODEOWNERS index 1f7a7ed6..9d182e13 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -14,4 +14,4 @@ # Component owners # ---------------- -* @comius @bazelbuild/java-team +* @hvadehra @bazelbuild/java-team From 22b3280dc0f2a2bf80024a280711bdaf8e9719c4 Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 20 Mar 2026 12:14:47 -0700 Subject: [PATCH 445/465] Migrate `JavaStarlarkApiTest.testPackSourcesWithExternalResourceArtifact` to Starlark The test is removed from Bazel and added to `@rules_java` PiperOrigin-RevId: 886915767 Change-Id: Ibaacab7d5241e21a1a0b1870c335e20c88135a85 --- MODULE.bazel | 2 +- test/java/bazel/common/BUILD.bazel | 3 ++ test/java/bazel/common/java_common_tests.bzl | 41 ++++++++++++++++++++ test/repositories.bzl | 5 +++ test/testdata/other_repo/BUILD.bazel | 1 + test/testdata/other_repo/MODULE.bazel | 1 + 6 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 test/java/bazel/common/BUILD.bazel create mode 100644 test/java/bazel/common/java_common_tests.bzl create mode 100644 test/testdata/other_repo/BUILD.bazel create mode 100644 test/testdata/other_repo/MODULE.bazel diff --git a/MODULE.bazel b/MODULE.bazel index 769902b4..38405ca6 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -130,4 +130,4 @@ archive_override( ) test_repositories = use_extension("//test:repositories.bzl", "test_repositories_ext", dev_dependency = True) -use_repo(test_repositories, "guava", "truth") +use_repo(test_repositories, "guava", "other_repo", "truth") diff --git a/test/java/bazel/common/BUILD.bazel b/test/java/bazel/common/BUILD.bazel new file mode 100644 index 00000000..18ab4f84 --- /dev/null +++ b/test/java/bazel/common/BUILD.bazel @@ -0,0 +1,3 @@ +load(":java_common_tests.bzl", "java_common_tests") + +java_common_tests(name = "java_common_tests") diff --git a/test/java/bazel/common/java_common_tests.bzl b/test/java/bazel/common/java_common_tests.bzl new file mode 100644 index 00000000..80fdf442 --- /dev/null +++ b/test/java/bazel/common/java_common_tests.bzl @@ -0,0 +1,41 @@ +"""Bazel tests for java_common APIs""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") + +def _test_java_common_pack_sources_with_external_resource(name): + util.helper_target( + custom_java_info_rule, + name = name + "/custom", + output_jar = name + "/custom.jar", + sources = [ + ":InternalLib.java", + "@other_repo//:ExternalLib.java", + ], + pack_sources = True, + ) + + analysis_test( + name = name, + impl = _test_java_common_pack_sources_with_external_resource_impl, + target = name + "/custom", + # Bazel 7 names external repos differently + attr_values = {"tags": ["min_bazel_8"]}, + ) + +def _test_java_common_pack_sources_with_external_resource_impl(env, target): + assert_that_action = env.expect.that_target(target).action_generating("{package}/{name}-src.jar") + assert_that_action.argv().contains_at_least([ + "--resources", + "{package}/InternalLib.java:bazel/common/InternalLib.java", + "external/+test_repositories_ext+other_repo/ExternalLib.java:ExternalLib.java", + ]).in_order() + +def java_common_tests(name): + test_suite( + name = name, + tests = [ + _test_java_common_pack_sources_with_external_resource, + ], + ) diff --git a/test/repositories.bzl b/test/repositories.bzl index 5d4f568d..0f0afd53 100644 --- a/test/repositories.bzl +++ b/test/repositories.bzl @@ -5,6 +5,7 @@ load("@bazel_skylib//lib:modules.bzl", "modules") # TODO: Use http_jar from //java:http_jar.bzl once it doesn't refert to cache.bzl from @bazel_tools # anymore, which isn't available in Bazel 6. load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") +load("@bazel_tools//tools/build_defs/repo:local.bzl", "local_repository") def test_repositories(): http_file( @@ -19,5 +20,9 @@ def test_repositories(): integrity = "sha256-Ushs3a3DG8hFfB4VaJ/Gt14ul84qg9i1S3ldVW1In4w=", downloaded_file_path = "truth.jar", ) + local_repository( + name = "other_repo", + path = "test/testdata/other_repo", + ) test_repositories_ext = modules.as_extension(test_repositories) diff --git a/test/testdata/other_repo/BUILD.bazel b/test/testdata/other_repo/BUILD.bazel new file mode 100644 index 00000000..fc25d5fb --- /dev/null +++ b/test/testdata/other_repo/BUILD.bazel @@ -0,0 +1 @@ +exports_files(["ExternalLib.java"]) diff --git a/test/testdata/other_repo/MODULE.bazel b/test/testdata/other_repo/MODULE.bazel new file mode 100644 index 00000000..f90d195a --- /dev/null +++ b/test/testdata/other_repo/MODULE.bazel @@ -0,0 +1 @@ +module(name = "other_repo") From 8c82b7f5677a3f2427cbd10b23e3902735b1d03f Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 23 Mar 2026 14:33:05 -0700 Subject: [PATCH 446/465] No public description PiperOrigin-RevId: 888283852 Change-Id: Id71e2bb5fcfab1c6469dbcdc067d0f65f3d2cdec --- java/common/rules/impl/basic_java_library_impl.bzl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/java/common/rules/impl/basic_java_library_impl.bzl b/java/common/rules/impl/basic_java_library_impl.bzl index a0105794..affd222f 100644 --- a/java/common/rules/impl/basic_java_library_impl.bzl +++ b/java/common/rules/impl/basic_java_library_impl.bzl @@ -160,7 +160,8 @@ def basic_java_library( validation_outputs = [] - if ctx.fragments.java.run_android_lint: + # Validation actions don't run in the exec config, so no need to create them. + if ctx.fragments.java.run_android_lint and not ctx.configuration.is_tool_configuration(): generated_source_jars = [ output.generated_source_jar for output in java_info.java_outputs From db20055480ba2c0ac85a923b3e68e18cb872dfa5 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 24 Mar 2026 08:14:39 -0700 Subject: [PATCH 447/465] Move mock toolchain files to `test/java/testutil` PiperOrigin-RevId: 888674071 Change-Id: I99783a86f6e3ffb137d1bcdbba00b2a14ce70294 --- test/java/common/rules/java_test_tests.bzl | 4 ++-- test/java/common/testutil/BUILD | 1 - test/java/{common => }/testutil/mock_cc_toolchain.bzl | 0 test/java/{common => }/testutil/mock_test_toolchain.bzl | 0 4 files changed, 2 insertions(+), 3 deletions(-) delete mode 100644 test/java/common/testutil/BUILD rename test/java/{common => }/testutil/mock_cc_toolchain.bzl (100%) rename test/java/{common => }/testutil/mock_test_toolchain.bzl (100%) diff --git a/test/java/common/rules/java_test_tests.bzl b/test/java/common/rules/java_test_tests.bzl index bd8e6850..f1c44662 100644 --- a/test/java/common/rules/java_test_tests.bzl +++ b/test/java/common/rules/java_test_tests.bzl @@ -10,9 +10,9 @@ load("//java:java_library.bzl", "java_library") load("//java:java_test.bzl", "java_test") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") -load("//test/java/common/testutil:mock_cc_toolchain.bzl", "mock_cc_toolchain") -load("//test/java/common/testutil:mock_test_toolchain.bzl", "mock_test_toolchains") load("//test/java/testutil:helper.bzl", "always_passes") +load("//test/java/testutil:mock_cc_toolchain.bzl", "mock_cc_toolchain") +load("//test/java/testutil:mock_test_toolchain.bzl", "mock_test_toolchains") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") def _test_java_test_is_test_only(name): diff --git a/test/java/common/testutil/BUILD b/test/java/common/testutil/BUILD deleted file mode 100644 index c2afbb31..00000000 --- a/test/java/common/testutil/BUILD +++ /dev/null @@ -1 +0,0 @@ -package(default_applicable_licenses = ["@rules_java//:license"]) diff --git a/test/java/common/testutil/mock_cc_toolchain.bzl b/test/java/testutil/mock_cc_toolchain.bzl similarity index 100% rename from test/java/common/testutil/mock_cc_toolchain.bzl rename to test/java/testutil/mock_cc_toolchain.bzl diff --git a/test/java/common/testutil/mock_test_toolchain.bzl b/test/java/testutil/mock_test_toolchain.bzl similarity index 100% rename from test/java/common/testutil/mock_test_toolchain.bzl rename to test/java/testutil/mock_test_toolchain.bzl From afefe1efcadb8ba65a9772b8b5dadbf5595ebfa1 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 25 Mar 2026 00:57:51 -0700 Subject: [PATCH 448/465] Deduplicate mock `java_toolchain` declarations Additionally: - Minimize the definitions and explicitly set the arguments asserted on in the test cases - Where possible, switch from asserting on the java_toolchain target explicitly and use the resolved toolchain via `java_toolchain_alias` (ignore-relnotes) PiperOrigin-RevId: 889084161 Change-Id: Ia89dac8f5ed9ed81f5366e3df3cb6d75aa4a310b --- .../rules/deploy_archive_builder_tests.bzl | 51 +--- test/java/testutil/mock_java_toolchain.bzl | 62 ++++ test/java/toolchains/java_runtime_tests.bzl | 32 +-- test/java/toolchains/java_toolchain_tests.bzl | 264 +++++++++++------- 4 files changed, 238 insertions(+), 171 deletions(-) create mode 100644 test/java/testutil/mock_java_toolchain.bzl diff --git a/test/java/common/rules/deploy_archive_builder_tests.bzl b/test/java/common/rules/deploy_archive_builder_tests.bzl index 32e75e91..727790f8 100644 --- a/test/java/common/rules/deploy_archive_builder_tests.bzl +++ b/test/java/common/rules/deploy_archive_builder_tests.bzl @@ -4,58 +4,13 @@ load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") -load("//java/common:java_semantics.bzl", "semantics") -load("//java/toolchains:java_runtime.bzl", "java_runtime") -load("//java/toolchains:java_toolchain.bzl", "java_toolchain") +load("//test/java/testutil:mock_java_toolchain.bzl", "mock_java_toolchain") -def _declare_java_toolchain(*, name, **kwargs): - java_runtime_name = name + "/runtime" - util.helper_target( - java_runtime, - name = java_runtime_name, - ) - toolchain_attrs = { - "source_version": "6", - "target_version": "6", - "bootclasspath": ["rt.jar"], - "xlint": ["toto"], - "javacopts": ["-Xmaxerrs 500"], - "compatible_javacopts": { - "android": ["-XDandroidCompatible"], - "testonly": ["-XDtestOnly"], - "public_visibility": ["-XDpublicVisibility"], - }, - "tools": [":javac_canary.jar"], - "javabuilder": ":JavaBuilder_deploy.jar", - "header_compiler": ":turbine_canary_deploy.jar", - "header_compiler_direct": ":turbine_direct", - "singlejar": "singlejar", - "ijar": "ijar", - "genclass": "GenClass_deploy.jar", - "timezone_data": "tzdata.jar", - "header_compiler_builtin_processors": ["BuiltinProc1", "BuiltinProc2"], - "reduced_classpath_incompatible_processors": [ - "IncompatibleProc1", - "IncompatibleProc2", - ], - "java_runtime": java_runtime_name, - } - toolchain_attrs.update(kwargs) - util.helper_target( - java_toolchain, - name = name + "/java_toolchain", - **toolchain_attrs - ) +def _test_custom_singlejar(name): util.helper_target( - native.toolchain, + mock_java_toolchain, name = name + "/toolchain", - toolchain = name + "/java_toolchain", - toolchain_type = semantics.JAVA_TOOLCHAIN_TYPE, ) - -def _test_custom_singlejar(name): - _declare_java_toolchain(name = name) - util.helper_target( java_binary, name = name + "/binary", diff --git a/test/java/testutil/mock_java_toolchain.bzl b/test/java/testutil/mock_java_toolchain.bzl new file mode 100644 index 00000000..c0ca6317 --- /dev/null +++ b/test/java/testutil/mock_java_toolchain.bzl @@ -0,0 +1,62 @@ +"""Fake java toolchains for testing""" + +load("//java/common:java_semantics.bzl", "semantics") +load("//java/toolchains:java_runtime.bzl", _java_runtime_rule = "java_runtime") +load("//java/toolchains:java_toolchain.bzl", "java_toolchain") + +# buildifier: disable=function-docstring +def mock_java_toolchain( + *, + name, + singlejar = "singlejar", + javabuilder = "JavaBuilder_deploy.jar", + header_compiler = "turbine_canary_deploy.jar", + header_compiler_direct = "turbine_direct", + ijar = "ijar", + genclass = "genclass", + java_runtime = None, + tags = None, # for util.helper_target + **kwargs): + if not java_runtime: + java_runtime = name + "_runtime" + _java_runtime_rule(name = java_runtime) + java_toolchain( + name = name + "_java", + javabuilder = javabuilder, + singlejar = singlejar, + header_compiler = header_compiler, + header_compiler_direct = header_compiler_direct, + ijar = ijar, + java_runtime = java_runtime, + genclass = genclass, + tags = tags, + **kwargs + ) + native.toolchain( + name = name, + toolchain = name + "_java", + toolchain_type = semantics.JAVA_TOOLCHAIN_TYPE, + tags = tags, + ) + +# buildifier: disable=function-docstring +def mock_java_runtime_toolchain( + *, + name, + srcs = [], + java_home = None, + java = None, + **kwargs): + _java_runtime_rule( + name = name + "_runtime", + srcs = srcs, + java_home = java_home, + java = java, + **kwargs + ) + native.toolchain( + name = name, + toolchain = name + "_runtime", + toolchain_type = semantics.JAVA_RUNTIME_TOOLCHAIN_TYPE, + **kwargs + ) diff --git a/test/java/toolchains/java_runtime_tests.bzl b/test/java/toolchains/java_runtime_tests.bzl index 0112b172..94d067ea 100644 --- a/test/java/toolchains/java_runtime_tests.bzl +++ b/test/java/toolchains/java_runtime_tests.bzl @@ -4,16 +4,16 @@ load("@rules_cc//cc:defs.bzl", "cc_import") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") -load("//java/common:java_semantics.bzl", "semantics") load("//java/toolchains:java_runtime.bzl", "java_runtime") load("//test/java/testutil:java_runtime_info_subject.bzl", "java_runtime_info_subject") +load("//test/java/testutil:mock_java_toolchain.bzl", "mock_java_runtime_toolchain") load("//test/java/testutil:rules/forward_java_runtime_info.bzl", "java_runtime_info_forwarding_rule") load("//toolchains:java_toolchain_alias.bzl", "java_runtime_alias") def _test_with_absolute_java_home(name): util.helper_target( - java_runtime, - name = name + "/jvm", + mock_java_runtime_toolchain, + name = name + "/java_runtime_toolchain", srcs = [], java_home = "/foo/bar", ) @@ -26,12 +26,6 @@ def _test_with_absolute_java_home(name): name = name + "/r", java_runtime = name + "/alias", ) - util.helper_target( - native.toolchain, - name = name + "/java_runtime_toolchain", - toolchain = name + "/jvm", - toolchain_type = semantics.JAVA_RUNTIME_TOOLCHAIN_TYPE, - ) analysis_test( name = name, @@ -52,8 +46,8 @@ def _test_with_absolute_java_home_impl(env, target): def _test_with_hermetic_java_home(name): util.helper_target( - java_runtime, - name = name + "/jvm", + mock_java_runtime_toolchain, + name = name + "/java_runtime_toolchain", srcs = [], java_home = "foo/bar", ) @@ -66,12 +60,6 @@ def _test_with_hermetic_java_home(name): name = name + "/r", java_runtime = name + "/alias", ) - util.helper_target( - native.toolchain, - name = name + "/java_runtime_toolchain", - toolchain = name + "/jvm", - toolchain_type = semantics.JAVA_RUNTIME_TOOLCHAIN_TYPE, - ) analysis_test( name = name, @@ -99,8 +87,8 @@ def _test_with_generated_java_executable(name): output_to_bindir = True, ) util.helper_target( - java_runtime, - name = name + "/jvm", + mock_java_runtime_toolchain, + name = name + "/java_runtime_toolchain", srcs = [], java = "foo/bar/bin/java", ) @@ -113,12 +101,6 @@ def _test_with_generated_java_executable(name): name = name + "/r", java_runtime = name + "/alias", ) - util.helper_target( - native.toolchain, - name = name + "/java_runtime_toolchain", - toolchain = name + "/jvm", - toolchain_type = semantics.JAVA_RUNTIME_TOOLCHAIN_TYPE, - ) analysis_test( name = name, diff --git a/test/java/toolchains/java_toolchain_tests.bzl b/test/java/toolchains/java_toolchain_tests.bzl index 372b9995..793de8ea 100644 --- a/test/java/toolchains/java_toolchain_tests.bzl +++ b/test/java/toolchains/java_toolchain_tests.bzl @@ -7,58 +7,24 @@ load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_common.bzl", "java_common") -load("//java/common:java_semantics.bzl", "semantics") -load("//java/toolchains:java_runtime.bzl", "java_runtime") -load("//java/toolchains:java_toolchain.bzl", "java_toolchain") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:java_toolchain_info_subject.bzl", "java_toolchain_info_subject") load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") +load("//test/java/testutil:mock_java_toolchain.bzl", "mock_java_toolchain") load("//toolchains:java_toolchain_alias.bzl", "java_toolchain_alias") -def _declare_java_toolchain(*, name, **kwargs): - java_runtime_name = name + "/runtime" - java_runtime(name = java_runtime_name) - toolchain_attrs = { - "source_version": "6", - "target_version": "6", - "bootclasspath": ["rt.jar"], - "xlint": ["toto"], - "javacopts": ["-Xmaxerrs 500"], - "compatible_javacopts": { - "android": ["-XDandroidCompatible"], - "testonly": ["-XDtestOnly"], - "public_visibility": ["-XDpublicVisibility"], - }, - "tools": [":javac_canary.jar"], - "javabuilder": ":JavaBuilder_deploy.jar", - "header_compiler": ":turbine_canary_deploy.jar", - "header_compiler_direct": ":turbine_direct", - "singlejar": "singlejar", - "ijar": "ijar", - "genclass": "GenClass_deploy.jar", - "timezone_data": "tzdata.jar", - "header_compiler_builtin_processors": ["BuiltinProc1", "BuiltinProc2"], - "reduced_classpath_incompatible_processors": [ - "IncompatibleProc1", - "IncompatibleProc2", - ], - "java_runtime": java_runtime_name, - } - toolchain_attrs.update(kwargs) - util.helper_target( - java_toolchain, - name = name + "/java_toolchain", - **toolchain_attrs - ) +def _test_javac_gets_options(name): util.helper_target( - native.toolchain, + mock_java_toolchain, name = name + "/toolchain", - toolchain = name + "/java_toolchain", - toolchain_type = semantics.JAVA_TOOLCHAIN_TYPE, + javabuilder = name + "/JavaBuilder_deploy.jar", + header_compiler_direct = name + "/turbine_direct", + bootclasspath = [name + "/rt.jar"], + source_version = "6", + target_version = "6", + xlint = ["toto"], + javacopts = ["-Xmaxerrs 500"], ) - -def _test_javac_gets_options(name): - _declare_java_toolchain(name = name) util.helper_target( java_library, name = name + "/b", @@ -95,24 +61,31 @@ def _test_javac_gets_options_impl(env, targets): "-Xmaxerrs", "500", ]) - assert_javac_action.jar().contains_exactly(["{package}/JavaBuilder_deploy.jar"]) - assert_javac_action.inputs().contains("{package}/rt.jar") + assert_javac_action.jar().contains_exactly(["{package}/{test_name}/JavaBuilder_deploy.jar"]) + assert_javac_action.inputs().contains("{package}/{test_name}/rt.jar") assert_javac_action.javacopts().not_contains("-g") assert_header_action = javac_action_subject.of(env, targets.b, "{package}/lib{name}-hjar.jar") - assert_header_action.argv().contains("{package}/turbine_direct") + assert_header_action.argv().contains("{package}/{test_name}/turbine_direct") def _test_jacocorunner(name): - _declare_java_toolchain( - name = name, + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", jacocorunner = "myjacocorunner.jar", ) - + util.helper_target( + java_toolchain_alias, + name = name + "/alias", + ) analysis_test( name = name, impl = _test_jacocorunner_impl, - target = name + "/java_toolchain", + target = name + "/alias", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, ) def _test_jacocorunner_impl(env, target): @@ -121,7 +94,10 @@ def _test_jacocorunner_impl(env, target): assert_toolchain.jacocorunner().short_path_equals("{package}/myjacocorunner.jar") def _test_singlejar_get_command_line(name): - _declare_java_toolchain(name = name) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + ) util.helper_target( java_binary, name = name + "/a", @@ -144,7 +120,11 @@ def _test_singlejar_get_command_line_impl(env, target): assert_javac_action.executable_file_name().equals(target.label.package + "/singlejar") def _test_genclass_get_command_line(name): - _declare_java_toolchain(name = name) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + genclass = name + "/GenClass_deploy.jar", + ) util.helper_target( java_library, name = name + "/a", @@ -164,15 +144,26 @@ def _test_genclass_get_command_line(name): def _test_genclass_get_command_line_impl(env, target): assert_javac_action = javac_action_subject.of(env, target, "{package}/lib{name}-gen.jar") - assert_javac_action.jar().contains_exactly(["{package}/GenClass_deploy.jar"]) + assert_javac_action.jar().contains_exactly(["{package}/{test_name}/GenClass_deploy.jar"]) def _test_timezone_data_is_correct(name): - _declare_java_toolchain(name = name) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + timezone_data = "tzdata.jar", + ) + util.helper_target( + java_toolchain_alias, + name = name + "/alias", + ) analysis_test( name = name, impl = _test_timezone_data_is_correct_impl, - target = name + "/java_toolchain", + target = name + "/alias", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, ) def _test_timezone_data_is_correct_impl(env, target): @@ -181,7 +172,11 @@ def _test_timezone_data_is_correct_impl(env, target): ) def _test_java_binary_uses_timezone_data(name): - _declare_java_toolchain(name = name) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + timezone_data = name + "/tzdata.jar", + ) util.helper_target( java_binary, name = name + "/a", @@ -199,11 +194,14 @@ def _test_java_binary_uses_timezone_data(name): def _test_java_binary_uses_timezone_data_impl(env, target): assert_action = javac_action_subject.of(env, target, "{package}/{name}.jar") - assert_action.sources().contains("{package}/tzdata.jar") + assert_action.sources().contains("{package}/{test_name}/tzdata.jar") assert_action.inputs().contains_predicate(matching.file_basename_equals("tzdata.jar")) def _test_ijar_get_command_line(name): - _declare_java_toolchain(name = name) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + ) util.helper_target( java_library, name = name + "/a", @@ -227,8 +225,9 @@ def _test_ijar_get_command_line_impl(env, target): ) def _test_no_header_compiler_header_compilation_enabled_fails(name): - _declare_java_toolchain( - name = name, + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", header_compiler = None, ) util.helper_target( @@ -255,8 +254,9 @@ def _test_no_header_compiler_header_compilation_enabled_fails_impl(env, target): ) def _test_no_header_compiler_direct_header_compilation_enabled_fails(name): - _declare_java_toolchain( - name = name, + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", header_compiler_direct = None, ) util.helper_target( @@ -283,8 +283,9 @@ def _test_no_header_compiler_direct_header_compilation_enabled_fails_impl(env, t ) def _test_no_header_compiler_header_compilation_disabled_analyzes_successfully(name): - _declare_java_toolchain( - name = name, + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", header_compiler = None, ) util.helper_target( @@ -311,41 +312,60 @@ def _test_no_header_compiler_header_compilation_disabled_analyzes_successfully_i def _test_header_compiler_builtin_processors(name): util.helper_target( - java_toolchain, - name = name + "/java_toolchain", + mock_java_toolchain, + name = name + "/toolchain", header_compiler_builtin_processors = ["BuiltinProc1", "BuiltinProc2"], - singlejar = "singlejar", + ) + util.helper_target( + java_toolchain_alias, + name = name + "/alias", ) analysis_test( name = name, impl = _test_header_compiler_builtin_processors_impl, - target = name + "/java_toolchain", + target = name + "/alias", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, ) def _test_header_compiler_builtin_processors_impl(env, target): - java_toolchain_info_subject.from_target(env, target).header_compiler_builtin_processors().contains_exactly(["BuiltinProc1", "BuiltinProc2"]) + java_toolchain_info_subject.from_target(env, target).header_compiler_builtin_processors().contains_exactly([ + "BuiltinProc1", + "BuiltinProc2", + ]) def _test_reduced_classpath_incompatible_processors(name): util.helper_target( - java_toolchain, - name = name + "/java_toolchain", + mock_java_toolchain, + name = name + "/toolchain", reduced_classpath_incompatible_processors = ["IncompatibleProc1", "IncompatibleProc2"], - singlejar = "singlejar", + ) + util.helper_target( + java_toolchain_alias, + name = name + "/alias", ) analysis_test( name = name, impl = _test_reduced_classpath_incompatible_processors_impl, - target = name + "/java_toolchain", + target = name + "/alias", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, ) def _test_reduced_classpath_incompatible_processors_impl(env, target): - java_toolchain_info_subject.from_target(env, target).reduced_classpath_incompatible_processors().contains_exactly(["IncompatibleProc1", "IncompatibleProc2"]) + java_toolchain_info_subject.from_target(env, target).reduced_classpath_incompatible_processors().contains_exactly([ + "IncompatibleProc1", + "IncompatibleProc2", + ]) def _test_location_expansion_in_jvm_opts(name): - _declare_java_toolchain( - name = name, + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", tools = [name + "/jsr305.jar", name + "/javac"], jvm_opts = [ "--patch-module=jdk.compiler=$(location " + name + "/javac)", @@ -381,8 +401,9 @@ def _test_location_expansion_with_multiple_artifacts_fails(name): name = name + "/fg", srcs = ["one", "two"], ) - _declare_java_toolchain( - name = name, + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", tools = [name + "/fg"], javabuilder_jvm_opts = ["$(location " + name + "/fg)"], ) @@ -390,7 +411,7 @@ def _test_location_expansion_with_multiple_artifacts_fails(name): analysis_test( name = name, impl = _test_location_expansion_with_multiple_artifacts_fails_impl, - target = name + "/java_toolchain", + target = name + "/toolchain_java", # the underlying java_toolchain expect_failure = True, ) @@ -405,15 +426,16 @@ def _test_timezone_data_with_multiple_artifacts_fails(name): name = name + "/fg", srcs = ["one", "two"], ) - _declare_java_toolchain( - name = name, + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", timezone_data = name + "/fg", ) analysis_test( name = name, impl = _test_timezone_data_with_multiple_artifacts_fails_impl, - target = name + "/java_toolchain", + target = name + "/toolchain_java", # the underlying java_toolchain expect_failure = True, ) @@ -423,8 +445,12 @@ def _test_timezone_data_with_multiple_artifacts_fails_impl(env, target): ) def _test_java_compile_action_target_gets_javacopts_from_toolchain(name): - _declare_java_toolchain( - name = name, + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + source_version = "6", + target_version = "6", + xlint = ["toto"], javacopts = ["-XDtoolchainJavacFlag"], ) util.helper_target( @@ -456,8 +482,12 @@ def _test_java_compile_action_target_gets_javacopts_from_toolchain_impl(env, tar ]) def _test_java_compile_action_exec_gets_javacopts_from_toolchain(name): - _declare_java_toolchain( - name = name, + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + source_version = "6", + target_version = "6", + xlint = ["toto"], javacopts = ["-XDtoolchainJavacFlag"], ) util.helper_target( @@ -495,8 +525,9 @@ def _test_java_compile_action_exec_gets_javacopts_from_toolchain_impl(env, targe ]) def _test_java_compile_action_uses_tool_specific_jvm_opts(name): - _declare_java_toolchain( - name = name, + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", jvm_opts = ["-Xbase"], javabuilder_jvm_opts = ["-DjavabuilderFlag=1"], turbine_jvm_opts = ["-DturbineFlag=1"], @@ -540,19 +571,27 @@ def _test_javabuilder_location_expansion_with_multiple_artifacts(name): name = name + "/fg2", srcs = ["c", "d"], ) - _declare_java_toolchain( - name = name, + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", javabuilder_data = [name + "/fg1", name + "/fg2"], javabuilder_jvm_opts = [ "$(locations " + name + "/fg1)", "$(locations " + name + "/fg2)", ], ) + util.helper_target( + java_toolchain_alias, + name = name + "/alias", + ) analysis_test( name = name, impl = _test_javabuilder_location_expansion_with_multiple_artifacts_impl, - target = name + "/java_toolchain", + target = name + "/alias", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, ) def _test_javabuilder_location_expansion_with_multiple_artifacts_impl(env, target): @@ -621,7 +660,10 @@ def _test_java_toolchain_flag_default_impl(env, target): ) def _test_java_toolchain_flag_set(name): - _declare_java_toolchain(name = name) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + ) util.helper_target( java_toolchain_alias, name = name + "/toolchain_alias", @@ -632,7 +674,7 @@ def _test_java_toolchain_flag_set(name): impl = _test_java_toolchain_flag_set_impl, targets = { "alias": name + "/toolchain_alias", - "toolchain": name + "/java_toolchain", + "toolchain": name + "/toolchain_java", # the underlying java_toolchain }, config_settings = { "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], @@ -644,13 +686,27 @@ def _test_java_toolchain_flag_set_impl(env, targets): assert_toolchain.label().equals(targets.toolchain.label) def _test_default_javac_opts_depset(name): - _declare_java_toolchain(name = name) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + source_version = "6", + target_version = "6", + xlint = ["toto"], + javacopts = ["-Xmaxerrs 500"], + ) + util.helper_target( + java_toolchain_alias, + name = name + "/alias", + ) analysis_test( name = name, impl = _test_default_javac_opts_depset_impl, - target = name + "/java_toolchain", + target = name + "/alias", attr_values = {"tags": ["min_bazel_8"]}, + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, ) def _test_default_javac_opts_depset_impl(env, target): @@ -659,12 +715,24 @@ def _test_default_javac_opts_depset_impl(env, target): ) def _test_default_javac_opts(name): - _declare_java_toolchain(name = name) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + source_version = "6", + target_version = "6", + ) + util.helper_target( + java_toolchain_alias, + name = name + "/alias", + ) analysis_test( name = name, impl = _test_default_javac_opts_impl, - target = name + "/java_toolchain", + target = name + "/alias", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, attr_values = {"tags": ["min_bazel_8"]}, ) From 5ae9e83b1e3c771a0f79dbe8d157f65a4f20451e Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 26 Mar 2026 03:34:35 -0700 Subject: [PATCH 449/465] Internal change (ignore-relnotes) PiperOrigin-RevId: 889735173 Change-Id: Ia6d4adaf419af786f5ad842948a509ddfb7c9232 --- java/common/rules/java_package_configuration.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/common/rules/java_package_configuration.bzl b/java/common/rules/java_package_configuration.bzl index e6b1885f..a1abcd05 100644 --- a/java/common/rules/java_package_configuration.bzl +++ b/java/common/rules/java_package_configuration.bzl @@ -18,7 +18,7 @@ load("//java/common/rules:java_helper.bzl", "helper") load("//java/private:boot_class_path_info.bzl", "BootClassPathInfo") load("//java/private:native.bzl", "get_internal_java_common") -# copybara: default visibility +# copybara: rules_java visibility JavaPackageConfigurationInfo = provider( "A provider for Java per-package configuration", From 747bddd6091a624c54a42c1ac20308190c1ad849 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 1 Apr 2026 13:34:36 -0700 Subject: [PATCH 450/465] Add `java_library` tests (ignore-relnotes) PiperOrigin-RevId: 893090207 Change-Id: Idc90df60767576cf47d3e9faba36465da7534818 --- .../common_launcher_java_library_tests.bzl | 226 ++++++++++++++++++ test/java/testutil/javac_action_subject.bzl | 1 + 2 files changed, 227 insertions(+) diff --git a/test/java/common/rules/common_launcher_java_library_tests.bzl b/test/java/common/rules/common_launcher_java_library_tests.bzl index 8f0ed228..9690b2ba 100644 --- a/test/java/common/rules/common_launcher_java_library_tests.bzl +++ b/test/java/common/rules/common_launcher_java_library_tests.bzl @@ -1,8 +1,13 @@ """Parameterized tests for java_library with --java_launcher""" +load("@bazel_features//:features.bzl", "bazel_features") load("@rules_testing//lib:analysis_test.bzl", "analysis_test") load("@rules_testing//lib:util.bzl", "util") +load("//java:java_import.bzl", "java_import") load("//java:java_library.bzl", "java_library") +load("//test/java/testutil:helper.bzl", "always_passes") +load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") def _test_java_library_rule_outputs(name): util.helper_target( @@ -22,6 +27,227 @@ def _test_java_library_rule_outputs_impl(env, target): "{package}/lib{name}.jar", ]) +def _test_java_library_action_graph(name): + util.helper_target( + java_library, + name = name + "/test_lib", + srcs = [ + "Util.java", + "Util2.java", + ], + javacopts = [ + "-g", + "-encoding", + "utf8", + ], + ) + + analysis_test( + name = name, + impl = _test_java_library_action_graph_impl, + target = name + "/test_lib", + ) + +def _test_java_library_action_graph_impl(env, target): + javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + javac_action.inputs().contains_at_least([ + "{package}/Util.java", + "{package}/Util2.java", + ]) + javac_action.javacopts().contains_at_least([ + "-g", + "-encoding", + "utf8", + ]) + +def _test_java_library_deps_of_genrule_are_not_on_classpath(name): + util.helper_target( + java_library, + name = name + "/root_dep", + srcs = ["test.java"], + ) + util.helper_target( + native.genrule, + name = name + "/has_java_dep", + outs = ["foo.jar"], + cmd = "echo NOT EXECUTED", + tools = [name + "/root_dep"], + ) + util.helper_target( + java_import, + name = name + "/has_java_dep_import", + jars = [name + "/has_java_dep"], + ) + util.helper_target( + java_library, + name = name + "/library", + srcs = ["dummy.java"], + deps = [name + "/has_java_dep_import"], + ) + + analysis_test( + name = name, + impl = _test_java_library_deps_of_genrule_are_not_on_classpath_impl, + target = name + "/library", + ) + +def _test_java_library_deps_of_genrule_are_not_on_classpath_impl(env, target): + expected_classpath = "{bin_path}/{package}/_ijar/{test_name}/has_java_dep_import/{package}/foo-ijar.jar" + javac_action_subject.of(env, target, "{package}/lib{name}.jar").classpath().contains_exactly([expected_classpath]) + +def _test_java_library_compile_and_run_time_paths(name): + util.helper_target( + java_library, + name = name + "/base", + srcs = ["Base.java"], + ) + util.helper_target( + java_library, + name = name + "/specialization", + srcs = ["Specialization.java"], + deps = [name + "/base"], + ) + + analysis_test( + name = name, + impl = _test_java_library_compile_and_run_time_paths_impl, + targets = { + "base": name + "/base", + "specialization": name + "/specialization", + }, + ) + +def _test_java_library_compile_and_run_time_paths_impl(env, targets): + base_info = java_info_subject.from_target(env, targets.base) + base_info.compilation_args().transitive_runtime_jars().contains_exactly(["{package}/lib{name}.jar"]) + base_info.compilation_args().transitive_compile_time_jars().contains_exactly(["{package}/lib{name}-hjar.jar"]) + base_info.compilation_args().compile_jars().contains_exactly(["{package}/lib{name}-hjar.jar"]) + + base_jar = "{package}/lib{test_name}/base.jar" + base_hjar = "{package}/lib{test_name}/base-hjar.jar" + + specialization_info = java_info_subject.from_target(env, targets.specialization) + specialization_info.compilation_args().transitive_runtime_jars().contains_exactly([ + base_jar, + "{package}/lib{name}.jar", + ]) + specialization_info.compilation_args().transitive_compile_time_jars().contains_exactly([ + base_hjar, + "{package}/lib{name}-hjar.jar", + ]) + specialization_info.compilation_args().compile_jars().contains_exactly(["{package}/lib{name}-hjar.jar"]) + +def _test_java_library_files_to_compile(name): + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["Lib.java"], + ) + + analysis_test( + name = name, + impl = _test_java_library_files_to_compile_impl, + target = name + "/lib", + ) + +def _test_java_library_files_to_compile_impl(env, target): + env.expect.that_target(target).output_group("compilation_outputs").contains_exactly(["{package}/lib{name}.jar"]) + +def _test_java_library_runtime_deps_are_not_on_classpath(name): + util.helper_target( + java_library, + name = name + "/runtime_java_dep", + srcs = ["test.java"], + ) + util.helper_target( + java_library, + name = name + "/compile_dep", + srcs = ["compile.java"], + ) + util.helper_target( + java_library, + name = name + "/depends_on_runtimedep", + srcs = ["dummy.java"], + runtime_deps = [name + "/runtime_java_dep"], + deps = [name + "/compile_dep"], + ) + + analysis_test( + name = name, + impl = _test_java_library_runtime_deps_are_not_on_classpath_impl, + target = name + "/depends_on_runtimedep", + ) + +def _test_java_library_runtime_deps_are_not_on_classpath_impl(env, target): + expected_compile = "{bin_path}/{package}/lib{test_name}/compile_dep-hjar.jar" + javac_action_subject.of(env, target, "{package}/lib{name}.jar").classpath().contains_exactly([expected_compile]) + +def _test_java_library_runtime_deps_are_not_on_classpath_with_header_compilation(name): + util.helper_target( + java_library, + name = name + "/runtime_java_dep", + srcs = ["test.java"], + ) + util.helper_target( + java_library, + name = name + "/compile_dep", + srcs = ["compile.java"], + ) + util.helper_target( + java_library, + name = name + "/depends_on_runtimedep", + srcs = ["dummy.java"], + runtime_deps = [name + "/runtime_java_dep"], + deps = [name + "/compile_dep"], + ) + + analysis_test( + name = name, + impl = _test_java_library_runtime_deps_are_not_on_classpath_with_header_compilation_impl, + config_settings = { + "//command_line_option:java_header_compilation": True, + }, + target = name + "/depends_on_runtimedep", + ) + +def _test_java_library_runtime_deps_are_not_on_classpath_with_header_compilation_impl(env, target): + expected_compile = "{bin_path}/{package}/lib{test_name}/compile_dep-hjar.jar" + javac_action_subject.of(env, target, "{package}/lib{name}.jar").classpath().contains_exactly([expected_compile]) + +def _test_java_library_fix_deps_tool_written_to_params_file(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + # Bazel 7 does not support transition on experimental_* flags. + # Exit early because this test case would be a loading phase error otherwise. + always_passes(name) + return + util.helper_target( + java_library, + name = name + "/base", + srcs = ["Base.java"], + ) + + analysis_test( + name = name, + impl = _test_java_library_fix_deps_tool_written_to_params_file_impl, + config_settings = { + "//command_line_option:experimental_fix_deps_tool": "fixer", + }, + target = name + "/base", + ) + +def _test_java_library_fix_deps_tool_written_to_params_file_impl(env, target): + javac_action_subject.of(env, target, "{package}/lib{name}.jar").argv().contains_at_least([ + "--experimental_fix_deps_tool", + "fixer", + ]).in_order() + JAVA_LIBRARY_LAUNCHER_TESTS = [ _test_java_library_rule_outputs, + _test_java_library_action_graph, + _test_java_library_deps_of_genrule_are_not_on_classpath, + _test_java_library_compile_and_run_time_paths, + _test_java_library_files_to_compile, + _test_java_library_runtime_deps_are_not_on_classpath, + _test_java_library_runtime_deps_are_not_on_classpath_with_header_compilation, + _test_java_library_fix_deps_tool_written_to_params_file, ] diff --git a/test/java/testutil/javac_action_subject.bzl b/test/java/testutil/javac_action_subject.bzl index beb0ecbc..057040b0 100644 --- a/test/java/testutil/javac_action_subject.bzl +++ b/test/java/testutil/javac_action_subject.bzl @@ -25,6 +25,7 @@ def _new_javac_action_subject(env, target, output): # An unset --strict_java_deps is equivalent to "OFF". strict_java_deps = lambda: _create_subject_for_flag("--strict_java_deps", self.parsed_flags, self.meta, default = ["OFF"]), sources = lambda: _create_subject_for_flag("--sources", self.parsed_flags, self.meta), + classpath = lambda: _create_subject_for_flag("--classpath", self.parsed_flags, self.meta), executable_file_name = lambda: subjects.str(action_subject.actual.argv[0], self.meta), inputs = action_subject.inputs, argv = action_subject.argv, From 23998995830e7ac87f2d6d7f3f17a8dade05ea23 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 15 Apr 2026 05:48:09 -0700 Subject: [PATCH 451/465] Internal change PiperOrigin-RevId: 900117275 Change-Id: I258daa1e7ddd4eddd69041b8f1a78eeb78de8f20 --- java/common/java_semantics.bzl | 6 ++++++ java/private/java_info.bzl | 7 +++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/java/common/java_semantics.bzl b/java/common/java_semantics.bzl index 58f957ef..3a7459ca 100644 --- a/java/common/java_semantics.bzl +++ b/java/common/java_semantics.bzl @@ -13,6 +13,7 @@ # limitations under the License. """Bazel Java Semantics""" +load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_helper.bzl", "cc_helper") # copybara: default visibility @@ -41,6 +42,10 @@ def _check_java_info_opens_exports(): def _minimize_cc_info(cc_info): return cc_info +def _merge_cc_infos(*args, **kwargs): + # TODO: b/483025864 - use https://github.com/bazelbuild/rules_cc/commit/011d6d9e7fae71d43df2d4d83c577f2cef2aa52e + return cc_common.merge_cc_infos(*args, **kwargs) + _DOCS = struct( ATTRS = { "resources": """ @@ -112,6 +117,7 @@ semantics = struct( for_attribute = lambda name: _DOCS.ATTRS.get(name, ""), ), minimize_cc_info = _minimize_cc_info, + merge_cc_infos = _merge_cc_infos, tokenize_javacopts = _tokenize_javacopts, PLATFORMS_ROOT = "@platforms//", INCOMPATIBLE_DISABLE_NON_EXECUTABLE_JAVA_BINARY = False, # Flip when java_single_jar is feature complete diff --git a/java/private/java_info.bzl b/java/private/java_info.bzl index 65c6f2a1..19c435a2 100644 --- a/java/private/java_info.bzl +++ b/java/private/java_info.bzl @@ -16,7 +16,6 @@ Definition of JavaInfo and JavaPluginInfo provider. """ -load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_semantics.bzl", "semantics") load(":native.bzl", "get_internal_java_common") @@ -175,7 +174,7 @@ def merge( } if get_internal_java_common().google_legacy_api_enabled(): - cc_info = semantics.minimize_cc_info(cc_common.merge_cc_infos(cc_infos = [p.cc_link_params_info for p in providers])) + cc_info = semantics.minimize_cc_info(semantics.merge_cc_infos(cc_infos = [p.cc_link_params_info for p in providers])) result.update( cc_link_params_info = cc_info, transitive_native_libraries = @@ -677,7 +676,7 @@ def _javainfo_init_base( if get_internal_java_common().google_legacy_api_enabled(): transitive_cc_infos = [dep.cc_link_params_info for dep in concatenated_deps.runtimedeps_exports_deps] transitive_cc_infos.extend(native_libraries) - cc_info = semantics.minimize_cc_info(cc_common.merge_cc_infos(cc_infos = transitive_cc_infos)) + cc_info = semantics.minimize_cc_info(semantics.merge_cc_infos(cc_infos = transitive_cc_infos)) result.update( cc_link_params_info = cc_info, transitive_native_libraries = @@ -686,7 +685,7 @@ def _javainfo_init_base( else: transitive_native_libraries = [] if native_libraries: - merged_cc_info = cc_common.merge_cc_infos(cc_infos = native_libraries) + merged_cc_info = semantics.merge_cc_infos(cc_infos = native_libraries) if hasattr(merged_cc_info, "_legacy_transitive_native_libraries"): transitive_native_libraries = [merged_cc_info._legacy_transitive_native_libraries] else: From 7b13ead48190fc096b61bf1e7aa9df59121212be Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 17 Apr 2026 07:10:56 -0700 Subject: [PATCH 452/465] Support disable_lint_checks in java_library PiperOrigin-RevId: 901279874 Change-Id: Icfebb038e6974b6d9dfc091cfd9e88a27de6aa68 --- java/common/rules/android_lint.bzl | 15 ++++++++++++++- .../common/rules/impl/basic_java_library_impl.bzl | 5 ++++- .../common/rules/impl/bazel_java_library_impl.bzl | 5 ++++- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/java/common/rules/android_lint.bzl b/java/common/rules/android_lint.bzl index 032e06bc..7152990c 100644 --- a/java/common/rules/android_lint.bzl +++ b/java/common/rules/android_lint.bzl @@ -22,7 +22,18 @@ def _tokenize_opts(opts_depset): opts = reversed(opts_depset.to_list()) return semantics.tokenize_javacopts(opts) -def _android_lint_action(ctx, source_files, source_jars, compilation_info, is_library): +def _flags_from_disable_lint_checks(args, disable_lint_checks): + invalid_ids = [check for check in disable_lint_checks if not _check_id_is_valid(check)] + if invalid_ids: + fail("Found not allowed character in disabled check ID(s) %s" % str(invalid_ids)) + args.add_joined("--disable", disable_lint_checks, join_with = ",") + +# Returns whether the passed Android Lint check ID is valid +def _check_id_is_valid(check): + # We want to prevent whitespace so that extra flags can't be 'injected' into Android Lint + return check.replace(".", "").replace("_", "").isalnum() + +def _android_lint_action(ctx, source_files, source_jars, compilation_info, is_library, disable_lint_checks = []): """ Creates an action that runs Android lint against Java source files. @@ -43,6 +54,7 @@ def _android_lint_action(ctx, source_files, source_jars, compilation_info, is_li source files. It should also include generated source jars. compilation_info: (struct) Information about compilation. is_library: (bool) Whether the target is a library. + disable_lint_checks: (list[str]) A list of AndroidLint checks to be skipped. Returns: (None|File) The Android lint output file or None if no source files were @@ -112,6 +124,7 @@ def _android_lint_action(ctx, source_files, source_jars, compilation_info, is_li args.add("--lintopts") args.add_all(linter.lint_opts) + _flags_from_disable_lint_checks(args, disable_lint_checks) for package_config in linter.package_config: if package_config.matches(package_config.package_specs, ctx.label): diff --git a/java/common/rules/impl/basic_java_library_impl.bzl b/java/common/rules/impl/basic_java_library_impl.bzl index affd222f..e2e27442 100644 --- a/java/common/rules/impl/basic_java_library_impl.bzl +++ b/java/common/rules/impl/basic_java_library_impl.bzl @@ -72,7 +72,8 @@ def basic_java_library( add_opens = [], bootclasspath = None, javabuilder_jvm_flags = None, - is_library = True): + is_library = True, + disable_lint_checks = []): """ Creates actions that compile and lint Java sources, sets up coverage and returns JavaInfo, InstrumentedFilesInfo and output groups. @@ -109,6 +110,7 @@ def basic_java_library( bootclasspath: (Target) The JDK APIs to compile this library against. javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. is_library: (bool) Whether the target is a library. Primarily for static analysis purposes. + disable_lint_checks: (list[str]) A list of AndroidLint checks to be skipped. Returns: (dict[str, Provider], {files_to_build: list[File], @@ -172,6 +174,7 @@ def basic_java_library( source_jars + generated_source_jars, compilation_info, is_library, + disable_lint_checks, ) if lint_output: validation_outputs.append(depset([lint_output])) diff --git a/java/common/rules/impl/bazel_java_library_impl.bzl b/java/common/rules/impl/bazel_java_library_impl.bzl index 5c7fc5cb..3ee1deb7 100644 --- a/java/common/rules/impl/bazel_java_library_impl.bzl +++ b/java/common/rules/impl/bazel_java_library_impl.bzl @@ -35,7 +35,8 @@ def bazel_java_library_rule( add_exports = [], add_opens = [], bootclasspath = None, - javabuilder_jvm_flags = None): + javabuilder_jvm_flags = None, + disable_lint_checks = []): """Implements java_library. Use this call when you need to produce a fully fledged java_library from @@ -58,6 +59,7 @@ def bazel_java_library_rule( add_opens: (list[str]) Allow this library to reflectively access the given /. bootclasspath: (Target) The JDK APIs to compile this library against. javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. + disable_lint_checks: (list[str]) A list of AndroidLint checks to be skipped. Returns: (dict[str, provider]) A list containing DefaultInfo, JavaInfo, InstrumentedFilesInfo, OutputGroupsInfo, ProguardSpecProvider providers. @@ -83,6 +85,7 @@ def bazel_java_library_rule( add_opens = add_opens, bootclasspath = bootclasspath, javabuilder_jvm_flags = javabuilder_jvm_flags, + disable_lint_checks = disable_lint_checks, ) target["DefaultInfo"] = construct_defaultinfo( From e1c82d4942c1150e8037a1d75358b51c57e17d70 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 22 Apr 2026 01:26:25 -0700 Subject: [PATCH 453/465] Internal Change PiperOrigin-RevId: 903683605 Change-Id: Ib9c4b7bdce8dd815722e9ca6916ba3a69743d2da --- java/common/java_semantics.bzl | 4 ++++ java/common/rules/impl/import_deps_check.bzl | 1 + 2 files changed, 5 insertions(+) diff --git a/java/common/java_semantics.bzl b/java/common/java_semantics.bzl index 3a7459ca..e847d879 100644 --- a/java/common/java_semantics.bzl +++ b/java/common/java_semantics.bzl @@ -24,6 +24,9 @@ def _find_java_toolchain(ctx): def _find_java_runtime_toolchain(ctx): return ctx.toolchains["@bazel_tools//tools/jdk:runtime_toolchain_type"].java_runtime +def _update_args_for_import_deps(*_args): + pass + def _get_default_resource_path(path, segment_extractor): # Look for src/.../resources to match Maven repository structure. segments = path.split("/") @@ -121,5 +124,6 @@ semantics = struct( tokenize_javacopts = _tokenize_javacopts, PLATFORMS_ROOT = "@platforms//", INCOMPATIBLE_DISABLE_NON_EXECUTABLE_JAVA_BINARY = False, # Flip when java_single_jar is feature complete + update_args_for_import_deps = _update_args_for_import_deps, expand_javacopts_make_variables = True, ) diff --git a/java/common/rules/impl/import_deps_check.bzl b/java/common/rules/impl/import_deps_check.bzl index 68d52145..69dec8b6 100644 --- a/java/common/rules/impl/import_deps_check.bzl +++ b/java/common/rules/impl/import_deps_check.bzl @@ -57,6 +57,7 @@ def import_deps_check( args.add("--jdeps_output", jdeps_output) args.add("--rule_label", ctx.label) + semantics.update_args_for_import_deps(ctx, args) inputs = depset( jars_to_check, transitive = [ From 23ef409e3b3ec682ce821911676425ed7c293300 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 22 Apr 2026 02:56:23 -0700 Subject: [PATCH 454/465] Migrate the `javaTestSetsSecurityManagerPropertyOnVersion17` to Starlark The test is added to rules_java and removed from Bazel (ignore-relnotes) PiperOrigin-RevId: 903721335 Change-Id: I8cd6b6c86bb32304f63cc1f21fae16f20319eefd --- test/java/common/rules/java_test_tests.bzl | 38 ++++++++++++++++++++++ test/java/testutil/mock_java_toolchain.bzl | 2 ++ 2 files changed, 40 insertions(+) diff --git a/test/java/common/rules/java_test_tests.bzl b/test/java/common/rules/java_test_tests.bzl index f1c44662..d4bd4b0e 100644 --- a/test/java/common/rules/java_test_tests.bzl +++ b/test/java/common/rules/java_test_tests.bzl @@ -12,6 +12,7 @@ load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:mock_cc_toolchain.bzl", "mock_cc_toolchain") +load("//test/java/testutil:mock_java_toolchain.bzl", "mock_java_runtime_toolchain") load("//test/java/testutil:mock_test_toolchain.bzl", "mock_test_toolchains") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") @@ -315,6 +316,42 @@ def _test_mac_requires_darwin_for_execution_impl(env, target): {"requires-darwin": ""}, ) +def _test_java_test_sets_securiry_manager_property_jdk17(name): + util.helper_target( + java_test, + name = name + "/test", + srcs = ["FooTest.java"], + test_class = "FooTest", + ) + util.helper_target( + mock_java_runtime_toolchain, + name = name + "/toolchain", + version = 17, + ) + + analysis_test( + name = name, + impl = _test_java_test_sets_securiry_manager_property_jdk17_impl, + target = name + "/test", + config_settings = { + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + ) + +def _test_java_test_sets_securiry_manager_property_jdk17_impl(env, target): + executable = env.expect.that_target(target).executable().actual.short_path + assert_action = env.expect.that_target(target).action_generating(executable) + if assert_action.actual.substitutions: + # TemplateExpansion action on linux/mac + assert_action.substitutions().get("%jvm_flags%", factory = subjects.str).contains( + "-Djava.security.manager=allow", + ) + else: + # windows + assert_action.argv().contains_predicate( + matching.str_matches("-Djava.security.manager=allow"), + ) + def java_test_tests(name): test_suite( name = name, @@ -327,5 +364,6 @@ def java_test_tests(name): _test_stamp_values, _test_add_test_support_to_compile_time_deps_flag, _test_mac_requires_darwin_for_execution, + _test_java_test_sets_securiry_manager_property_jdk17, ], ) diff --git a/test/java/testutil/mock_java_toolchain.bzl b/test/java/testutil/mock_java_toolchain.bzl index c0ca6317..de824b16 100644 --- a/test/java/testutil/mock_java_toolchain.bzl +++ b/test/java/testutil/mock_java_toolchain.bzl @@ -46,12 +46,14 @@ def mock_java_runtime_toolchain( srcs = [], java_home = None, java = None, + version = None, **kwargs): _java_runtime_rule( name = name + "_runtime", srcs = srcs, java_home = java_home, java = java, + version = version, **kwargs ) native.toolchain( From d07df79ee172b2ef06af50966b3af052fee2e68f Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 27 Apr 2026 01:27:20 -0700 Subject: [PATCH 455/465] Migrate the `testResourceStripPrefix` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 906200503 Change-Id: I2feea71ecbe4b2741a00a32503d10dc63d181eb9 --- test/java/bazel/rules/java_binary_tests.bzl | 22 +++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/test/java/bazel/rules/java_binary_tests.bzl b/test/java/bazel/rules/java_binary_tests.bzl index 737acea9..8c385046 100644 --- a/test/java/bazel/rules/java_binary_tests.bzl +++ b/test/java/bazel/rules/java_binary_tests.bzl @@ -97,6 +97,27 @@ def _test_java_binary_javacopts_location_expansion_impl(env, target): "-XepOpt:foo={package}/A.java", ) +def _test_java_binary_resource_strip_prefix(name): + util.helper_target( + java_binary, + name = name + "/bin", + srcs = ["Foo.java"], + main_class = "Foo", + resource_strip_prefix = native.package_name() + "/path/to/strip", + resources = ["path/to/strip/bar.props"], + ) + + analysis_test( + name = name, + impl = _test_java_binary_resource_strip_prefix_impl, + target = name + "/bin", + ) + +def _test_java_binary_resource_strip_prefix_impl(env, target): + env.expect.that_target(target).action_generating("{package}/{name}.jar").contains_flag_values([ + ("--resources", "{package}/path/to/strip/bar.props:bar.props"), + ]) + def java_binary_tests(name): test_suite( name = name, @@ -104,5 +125,6 @@ def java_binary_tests(name): _test_java_binary_cross_compilation_to_unix, _test_java_binary_javacopts_make_variable_expansion, _test_java_binary_javacopts_location_expansion, + _test_java_binary_resource_strip_prefix, ], ) From 0b519df0fb588dc06b89dfe4d50d7639c1ce73a6 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 29 Apr 2026 08:04:46 -0700 Subject: [PATCH 456/465] Add java_library tests (ignore-relnotes) PiperOrigin-RevId: 907592868 Change-Id: I95b3560ff3008b56d5d2d63dbbd7eb8f91d2911a --- .../common_launcher_java_library_tests.bzl | 401 ++++++++++++++++++ test/java/testutil/javac_action_subject.bzl | 7 + 2 files changed, 408 insertions(+) diff --git a/test/java/common/rules/common_launcher_java_library_tests.bzl b/test/java/common/rules/common_launcher_java_library_tests.bzl index 9690b2ba..3b2a2282 100644 --- a/test/java/common/rules/common_launcher_java_library_tests.bzl +++ b/test/java/common/rules/common_launcher_java_library_tests.bzl @@ -1,13 +1,19 @@ """Parameterized tests for java_library with --java_launcher""" load("@bazel_features//:features.bzl", "bazel_features") +load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_testing//lib:analysis_test.bzl", "analysis_test") +load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_import.bzl", "java_import") load("//java:java_library.bzl", "java_library") +load("//java:java_plugin.bzl", "java_plugin") +load("//java/toolchains:java_runtime.bzl", "java_runtime") +load("//java/toolchains:java_toolchain.bzl", "java_toolchain") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") +load("//test/java/testutil:rules/custom_library_with_bootclasspath.bzl", "custom_bootclasspath") def _test_java_library_rule_outputs(name): util.helper_target( @@ -214,12 +220,397 @@ def _test_java_library_runtime_deps_are_not_on_classpath_with_header_compilation expected_compile = "{bin_path}/{package}/lib{test_name}/compile_dep-hjar.jar" javac_action_subject.of(env, target, "{package}/lib{name}.jar").classpath().contains_exactly([expected_compile]) +def _test_java_library_annotation_processing_using_javacopt(name): + util.helper_target( + java_library, + name = name + "/to_be_processed", + srcs = ["ToBeProcessed.java"], + javacopts = ["-processor com.google.process.Processor"], + ) + + analysis_test( + name = name, + impl = _test_java_library_annotation_processing_using_javacopt_impl, + target = name + "/to_be_processed", + ) + +def _test_java_library_annotation_processing_using_javacopt_impl(env, target): + javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + javac_action.argv().contains("--generated_sources_output") + javac_action.generated_sources_output().contains("{bin_path}/{package}/lib{name}-gensrc.jar") + javac_action.javacopts().contains("-processor") + javac_action.javacopts().contains("com.google.process.Processor") + + # The compile action should have a gensrc jar output + javac_action.outputs().contains("{package}/lib{name}-gensrc.jar") + + # The gensrc jar should be an input to the source jar action + src_jar_action = env.expect.that_target(target).action_generating("{package}/lib{name}-src.jar") + src_jar_action.inputs().contains("{package}/lib{name}-gensrc.jar") + +def _test_java_library_javacopts_with_location_expansion(name): + util.helper_target( + java_library, + name = name + "/patch", + srcs = ["A.java"], + ) + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["ToBeProcessed.java"], + javacopts = ["--patch $(execpath " + name + "/patch)"], + deps = [name + "/patch"], + ) + + analysis_test( + name = name, + impl = _test_java_library_javacopts_with_location_expansion_impl, + target = name + "/lib", + ) + +def _test_java_library_javacopts_with_location_expansion_impl(env, target): + javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + javac_action.javacopts().contains_at_least([ + "--patch", + "{bin_path}/{package}/lib{test_name}/patch.jar", + ]) + +def _test_java_library_invalid_plugin(name): + util.helper_target( + java_library, + name = name + "/not_a_plugin", + srcs = ["NotAPlugin.java"], + ) + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["Lib.java"], + plugins = [name + "/not_a_plugin"], + ) + + analysis_test( + name = name, + impl = _test_java_library_invalid_plugin_impl, + target = name + "/lib", + expect_failure = True, + ) + +def _test_java_library_invalid_plugin_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.contains("does not have mandatory providers: 'JavaPluginInfo'"), + ) + +def _test_java_library_plugin_with_runtime_deps(name): + util.helper_target( + java_library, + name = name + "/runtime_lib", + srcs = ["Runtime.java"], + ) + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["Lib.java"], + runtime_deps = [name + "/runtime_lib"], + ) + util.helper_target( + java_plugin, + name = name + "/plugin", + srcs = ["Plugin.java"], + processor_class = "com.google.process.stuff", + deps = [name + "/lib"], + ) + util.helper_target( + java_library, + name = name + "/leaf_lib", + srcs = ["LeafLib.java"], + plugins = [name + "/plugin"], + ) + + analysis_test( + name = name, + impl = _test_java_library_plugin_with_runtime_deps_impl, + target = name + "/leaf_lib", + ) + +def _test_java_library_plugin_with_runtime_deps_impl(env, target): + javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + javac_action.processorpath().contains_exactly_predicates([ + matching.str_matches("*/plugin.jar"), + matching.str_matches("*/lib.jar"), + matching.str_matches("*/runtime_lib.jar"), + ]) + +def _test_java_library_source_jar_without_annotation_processing(name): + util.helper_target( + java_library, + name = name + "/foo", + srcs = ["Foo.java"], + ) + + analysis_test( + name = name, + impl = _test_java_library_source_jar_without_annotation_processing_impl, + target = name + "/foo", + ) + +def _test_java_library_source_jar_without_annotation_processing_impl(env, target): + javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + javac_action.argv().not_contains("--generated_sources_output") + javac_action.outputs().contains_exactly([ + "{package}/lib{name}.jar", + "{package}/lib{name}.jdeps", + "{package}/lib{name}-native-header.jar", + "{package}/lib{name}.jar_manifest_proto", + ]) + + src_jar_action = javac_action_subject.of(env, target, "{package}/lib{name}-src.jar") + src_jar_action.outputs().contains_exactly([ + "{package}/lib{name}-src.jar", + ]) + +def _test_java_library_source_jars_with_source_jars(name): + util.helper_target( + java_library, + name = name + "/beatit", + srcs = [ + "Plugin.java", + "Some.srcjar", + ], + ) + + analysis_test( + name = name, + impl = _test_java_library_source_jars_with_source_jars_impl, + target = name + "/beatit", + ) + +def _test_java_library_source_jars_with_source_jars_impl(env, target): + src_jar_action = javac_action_subject.of(env, target, "{package}/lib{name}-src.jar") + src_jar_action.inputs().contains_at_least([ + "{package}/Plugin.java", + "{package}/Some.srcjar", + ]) + src_jar_action.sources().contains_exactly([ + "{package}/Some.srcjar", + ]) + src_jar_action.resources().contains_predicate( + matching.str_matches("*/Plugin.java:*rules/Plugin.java"), + ) + +def _test_java_library_should_set_bootclasspath(name): + boot_jar = util.empty_file(name + "/boot.jar") + util.helper_target( + custom_bootclasspath, + name = name + "/mock_bootclasspath", + bootclasspath = [boot_jar], + ) + + util.helper_target( + java_runtime, + name = name + "/runtime", + ) + + util.helper_target( + java_toolchain, + name = name + "/mock_toolchain_impl", + bootclasspath = [name + "/mock_bootclasspath"], + genclass = name + "/genclass", + header_compiler = name + "/header_compiler", + header_compiler_direct = name + "/header_compiler_direct", + ijar = name + "/ijar", + java_runtime = name + "/runtime", + javabuilder = name + "/javabuilder", + singlejar = name + "/singlejar", + ) + util.helper_target( + native.toolchain, + name = name + "/toolchain", + toolchain = name + "/mock_toolchain_impl", + toolchain_type = "@bazel_tools//tools/jdk:toolchain_type", + ) + util.helper_target( + java_library, + name = name + "/test_lib", + srcs = ["A.java"], + ) + + analysis_test( + name = name, + impl = _test_java_library_should_set_bootclasspath_impl, + config_settings = { + "//command_line_option:extra_toolchains": [ + native.package_relative_label(name + "/toolchain"), + ], + }, + target = name + "/test_lib", + ) + +def _test_java_library_should_set_bootclasspath_impl(env, target): + javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + + javac_action.bootclasspath().contains_exactly([ + "{bin_path}/{package}/test_java_library_should_set_bootclasspath/boot.jar", + ]) + +def _test_java_library_command_line_contains_target_label_and_rule_kind(name): + util.helper_target( + java_library, + name = name + "/test_lib", + srcs = ["A.java"], + ) + + analysis_test( + name = name, + impl = _test_java_library_command_line_contains_target_label_and_rule_kind_impl, + target = name + "/test_lib", + ) + +def _test_java_library_command_line_contains_target_label_and_rule_kind_impl(env, target): + javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + javac_action.target_label().contains_exactly(["//{package}:{name}"]) + +def _test_java_library_propagates_native_libraries(name): + util.helper_target( + cc_library, + name = name + "/native_deps1.so", + srcs = ["a.cc"], + ) + util.helper_target( + java_library, + name = name + "/lib_deps", + srcs = ["B.java"], + deps = [name + "/native_deps1.so"], + ) + util.helper_target( + cc_library, + name = name + "/native_deps2.so", + srcs = ["b.cc"], + ) + util.helper_target( + cc_library, + name = name + "/native_rdeps1.so", + srcs = ["c.cc"], + ) + util.helper_target( + java_library, + name = name + "/lib_runtime_deps", + srcs = ["C.java"], + deps = [name + "/native_rdeps1.so"], + ) + util.helper_target( + cc_library, + name = name + "/native_rdeps2.so", + srcs = ["d.cc"], + ) + util.helper_target( + cc_library, + name = name + "/native_exports1.so", + srcs = ["e.cc"], + ) + util.helper_target( + java_library, + name = name + "/lib_exports", + srcs = ["D.java"], + deps = [name + "/native_exports1.so"], + ) + util.helper_target( + cc_library, + name = name + "/native_exports2.so", + srcs = ["f.cc"], + ) + util.helper_target( + cc_library, + name = name + "/native_data1.so", + srcs = ["g.cc"], + ) + util.helper_target( + java_library, + name = name + "/lib_data", + srcs = ["E.java"], + deps = [name + "/native_data1.so"], + ) + util.helper_target( + cc_library, + name = name + "/native_data2.so", + srcs = ["h.cc"], + ) + util.helper_target( + java_library, + name = name + "/top", + srcs = ["A.java"], + data = [ + name + "/lib_data", + name + "/native_data2.so", + ], + exports = [ + name + "/lib_exports", + name + "/native_exports2.so", + ], + runtime_deps = [ + name + "/lib_runtime_deps", + name + "/native_rdeps2.so", + ], + deps = [ + name + "/lib_deps", + name + "/native_deps2.so", + ], + ) + + analysis_test( + name = name, + impl = _test_java_library_propagates_native_libraries_impl, + target = name + "/top", + ) + +def _test_java_library_propagates_native_libraries_impl(env, target): + java_info_subject.from_target(env, target).transitive_native_libraries().static_libraries().contains_exactly_predicates([ + # Windows platforms use .lib extension for static libraries. + matching.is_in(["libnative_rdeps2.so.a", "native_rdeps2.so.lib"]), + matching.is_in(["libnative_exports2.so.a", "native_exports2.so.lib"]), + matching.is_in(["libnative_deps2.so.a", "native_deps2.so.lib"]), + matching.is_in(["libnative_rdeps1.so.a", "native_rdeps1.so.lib"]), + matching.is_in(["libnative_exports1.so.a", "native_exports1.so.lib"]), + matching.is_in(["libnative_deps1.so.a", "native_deps1.so.lib"]), + ]) + +def _test_java_library_gen_source_no_processor_names(name): + util.helper_target( + java_plugin, + name = name + "/plugin", + srcs = ["AnnotationProcessor.java"], + ) + util.helper_target( + java_library, + name = name + "/to_be_processed", + srcs = ["ToBeProcessed.java"], + plugins = [name + "/plugin"], + ) + + analysis_test( + name = name, + impl = _test_java_library_gen_source_no_processor_names_impl, + target = name + "/to_be_processed", + ) + +def _test_java_library_gen_source_no_processor_names_impl(env, target): + javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + + # The compile action should not have a gensrc jar output even though it has a plugin, + # since the plugin doesn't define a processor. + javac_action.outputs().contains_exactly([ + "{package}/lib{name}.jar", + "{package}/lib{name}.jdeps", + "{package}/lib{name}-native-header.jar", + "{package}/lib{name}.jar_manifest_proto", + ]) + def _test_java_library_fix_deps_tool_written_to_params_file(name): if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: # Bazel 7 does not support transition on experimental_* flags. # Exit early because this test case would be a loading phase error otherwise. always_passes(name) return + util.helper_target( java_library, name = name + "/base", @@ -250,4 +641,14 @@ JAVA_LIBRARY_LAUNCHER_TESTS = [ _test_java_library_runtime_deps_are_not_on_classpath, _test_java_library_runtime_deps_are_not_on_classpath_with_header_compilation, _test_java_library_fix_deps_tool_written_to_params_file, + _test_java_library_propagates_native_libraries, + _test_java_library_gen_source_no_processor_names, + _test_java_library_annotation_processing_using_javacopt, + _test_java_library_javacopts_with_location_expansion, + _test_java_library_invalid_plugin, + _test_java_library_plugin_with_runtime_deps, + _test_java_library_source_jar_without_annotation_processing, + _test_java_library_source_jars_with_source_jars, + _test_java_library_should_set_bootclasspath, + _test_java_library_command_line_contains_target_label_and_rule_kind, ] diff --git a/test/java/testutil/javac_action_subject.bzl b/test/java/testutil/javac_action_subject.bzl index 057040b0..3c405665 100644 --- a/test/java/testutil/javac_action_subject.bzl +++ b/test/java/testutil/javac_action_subject.bzl @@ -25,9 +25,16 @@ def _new_javac_action_subject(env, target, output): # An unset --strict_java_deps is equivalent to "OFF". strict_java_deps = lambda: _create_subject_for_flag("--strict_java_deps", self.parsed_flags, self.meta, default = ["OFF"]), sources = lambda: _create_subject_for_flag("--sources", self.parsed_flags, self.meta), + resources = lambda: _create_subject_for_flag("--resources", self.parsed_flags, self.meta), classpath = lambda: _create_subject_for_flag("--classpath", self.parsed_flags, self.meta), + bootclasspath = lambda: _create_subject_for_flag("--bootclasspath", self.parsed_flags, self.meta), + system = lambda: _create_subject_for_flag("--system", self.parsed_flags, self.meta), + generated_sources_output = lambda: _create_subject_for_flag("--generated_sources_output", self.parsed_flags, self.meta), + processorpath = lambda: _create_subject_for_flag("--processorpath", self.parsed_flags, self.meta), + target_label = lambda: _create_subject_for_flag("--target_label", self.parsed_flags, self.meta), executable_file_name = lambda: subjects.str(action_subject.actual.argv[0], self.meta), inputs = action_subject.inputs, + outputs = lambda: subjects.collection([o.short_path for o in action_subject.actual.outputs.to_list()], self.meta.derive("outputs()"), format = True), argv = action_subject.argv, mnemonic = action_subject.mnemonic, ) From 6d7ddaa95b786b47815ce1ff41d16d1b880e4b99 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 29 Apr 2026 08:39:11 -0700 Subject: [PATCH 457/465] Add java_library tests (ignore-relnotes) PiperOrigin-RevId: 907608297 Change-Id: I972c3eb8e2a85812809adec31e521077c1c5c785 --- test/java/common/rules/BUILD | 21 ++ .../common_launcher_java_library_tests.bzl | 232 ++++++++++++++++++ test/java/testutil/java_info_subject.bzl | 1 + test/java/testutil/javac_action_subject.bzl | 1 + 4 files changed, 255 insertions(+) diff --git a/test/java/common/rules/BUILD b/test/java/common/rules/BUILD index 28d38349..0f1d293c 100644 --- a/test/java/common/rules/BUILD +++ b/test/java/common/rules/BUILD @@ -1,3 +1,5 @@ +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_library.bzl", "java_library") load(":add_exports_tests.bzl", "add_exports_tests") load(":deploy_archive_builder_tests.bzl", "deploy_archive_builder_test_suite") load(":java_binary_tests.bzl", "java_binary_tests") @@ -30,3 +32,22 @@ java_single_jar_tests(name = "java_single_jar_tests") java_test_tests(name = "java_test_tests") add_exports_tests(name = "add_exports_tests") + +# Used for tests. +util.helper_target( + java_library, + name = "module_javacopts_helper", + srcs = [ + "InputFile.java", + "InputFile2.java", + ], + add_exports = [ + "export/one", + "export/two", + ], + add_opens = [ + "open/one", + "open/two", + ], + visibility = ["//test/java:__subpackages__"], +) diff --git a/test/java/common/rules/common_launcher_java_library_tests.bzl b/test/java/common/rules/common_launcher_java_library_tests.bzl index 3b2a2282..f0a19580 100644 --- a/test/java/common/rules/common_launcher_java_library_tests.bzl +++ b/test/java/common/rules/common_launcher_java_library_tests.bzl @@ -13,6 +13,7 @@ load("//java/toolchains:java_toolchain.bzl", "java_toolchain") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") +load("//test/java/testutil:mock_java_toolchain.bzl", "mock_java_toolchain") load("//test/java/testutil:rules/custom_library_with_bootclasspath.bzl", "custom_bootclasspath") def _test_java_library_rule_outputs(name): @@ -632,6 +633,230 @@ def _test_java_library_fix_deps_tool_written_to_params_file_impl(env, target): "fixer", ]).in_order() +def _test_java_library_compilation_info_provider(name): + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + bootclasspath = [name + "/boot.jar"], + ) + + util.helper_target( + java_library, + name = name + "/test_lib", + srcs = ["A.java"], + ) + + analysis_test( + name = name, + impl = _test_java_library_compilation_info_provider_impl, + config_settings = { + "//command_line_option:extra_toolchains": [ + native.package_relative_label(name + "/toolchain"), + ], + }, + target = name + "/test_lib", + ) + +def _test_java_library_compilation_info_provider_impl(env, target): + java_info_subject.from_target(env, target).compilation_info().boot_classpath().contains_exactly([ + "{package}/{test_name}/boot.jar", + ]) + +def _test_java_library_native_header_outputs(name): + util.helper_target( + java_library, + name = name + "/jni", + srcs = [ + "Bar.java", + "Foo.java", + ], + ) + + analysis_test( + name = name, + impl = _test_java_library_native_header_outputs_impl, + target = name + "/jni", + ) + +def _test_java_library_native_header_outputs_impl(env, target): + javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + javac_action.native_header_output().contains_exactly([ + "{bin_path}/{package}/lib{name}-native-header.jar", + ]) + javac_action.outputs().contains("{package}/lib{name}-native-header.jar") + java_info_subject.from_target(env, target).outputs().native_headers().contains_exactly([ + "{package}/lib{name}-native-header.jar", + ]) + +def _test_java_library_module_javacopts(name): + analysis_test( + name = name, + impl = _test_java_library_module_javacopts_impl, + target = "//test/java/common/rules:module_javacopts_helper", + ) + +def _test_java_library_module_javacopts_impl(env, target): + javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + javac_action.javacopts().contains_at_least([ + "--add-exports=export/one=ALL-UNNAMED", + "--add-exports=export/two=ALL-UNNAMED", + ]) + + java_info = java_info_subject.from_target(env, target) + java_info.module_flags().add_exports().contains_exactly([ + "export/one", + "export/two", + ]) + java_info.module_flags().add_opens().contains_exactly([ + "open/one", + "open/two", + ]) + +def _test_java_library_forwarded_deps(name): + util.helper_target( + java_library, + name = name + "/a", + srcs = ["a.java"], + ) + util.helper_target( + java_library, + name = name + "/b1", + exports = [name + "/a"], + ) + util.helper_target( + java_library, + name = name + "/b2", + exports = [name + "/a"], + ) + util.helper_target( + java_library, + name = name + "/c1", + srcs = ["c1.java"], + deps = [name + "/b1"], + ) + util.helper_target( + java_library, + name = name + "/c2", + srcs = ["c2.java"], + deps = [name + "/b2"], + ) + + analysis_test( + name = name, + impl = _test_java_library_forwarded_deps_impl, + targets = { + "a": name + "/a", + "c1": name + "/c1", + "c2": name + "/c2", + }, + ) + +def _test_java_library_forwarded_deps_impl(env, targets): + a_info = java_info_subject.from_target(env, targets.a) + c1_info = java_info_subject.from_target(env, targets.c1) + c2_info = java_info_subject.from_target(env, targets.c2) + + a_jars = a_info.compilation_args().actual.compile_jars.to_list() + c1_info.compilation_info().compilation_classpath().contains_at_least(a_jars) + c2_info.compilation_info().compilation_classpath().contains_at_least(a_jars) + +# Regression test for b/5773894 +def _test_java_library_transitive_strict_deps(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + always_passes(name) + return + + util.helper_target( + java_library, + name = name + "/c", + srcs = ["C.java"], + ) + util.helper_target( + java_library, + name = name + "/b", + srcs = ["B.java"], + deps = [name + "/c"], + ) + util.helper_target( + java_library, + name = name + "/a", + exports = [name + "/b"], + ) + + analysis_test( + name = name, + impl = _test_java_library_transitive_strict_deps_impl, + config_settings = { + "//command_line_option:experimental_strict_java_deps": "ERROR", + }, + target = name + "/a", + ) + +def _test_java_library_transitive_strict_deps_impl(env, target): + a_info = java_info_subject.from_target(env, target) + a_info.compilation_args().compile_jars().contains_exactly([ + "{package}/lib{test_name}/b-hjar.jar", + ]) + +def _test_java_library_emit_output_deps(name): + util.helper_target( + java_library, + name = name + "/b", + srcs = ["B.java"], + ) + util.helper_target( + java_library, + name = name + "/a", + exports = [name + "/b"], + ) + + analysis_test( + name = name, + impl = _test_java_library_emit_output_deps_impl, + config_settings = { + "//command_line_option:java_deps": True, + }, + targets = { + "a": name + "/a", + "b": name + "/b", + }, + ) + +def _test_java_library_emit_output_deps_impl(env, targets): + javac_action_subject.of(env, targets.b, "{package}/lib{name}.jar").outputs().contains( + "{package}/lib{name}.jdeps", + ) + + javac_action_subject.of(env, targets.a, "{package}/lib{name}.jar").outputs().contains_exactly([ + "{package}/lib{name}.jar", + "{package}/lib{name}-native-header.jar", + "{package}/lib{name}.jar_manifest_proto", + ]) + +def _test_java_library_deps_without_srcs(name): + util.helper_target( + java_library, + name = name + "/b", + srcs = ["B.java"], + ) + util.helper_target( + java_library, + name = name + "/a", + deps = [name + "/b"], + ) + + analysis_test( + name = name, + impl = _test_java_library_deps_without_srcs_impl, + target = name + "/a", + expect_failure = True, + ) + +def _test_java_library_deps_without_srcs_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.contains("deps not allowed without srcs"), + ) + JAVA_LIBRARY_LAUNCHER_TESTS = [ _test_java_library_rule_outputs, _test_java_library_action_graph, @@ -651,4 +876,11 @@ JAVA_LIBRARY_LAUNCHER_TESTS = [ _test_java_library_source_jars_with_source_jars, _test_java_library_should_set_bootclasspath, _test_java_library_command_line_contains_target_label_and_rule_kind, + _test_java_library_compilation_info_provider, + _test_java_library_native_header_outputs, + _test_java_library_module_javacopts, + _test_java_library_forwarded_deps, + _test_java_library_transitive_strict_deps, + _test_java_library_emit_output_deps, + _test_java_library_deps_without_srcs, ] diff --git a/test/java/testutil/java_info_subject.bzl b/test/java/testutil/java_info_subject.bzl index f5ad9e9c..9a0fb533 100644 --- a/test/java/testutil/java_info_subject.bzl +++ b/test/java/testutil/java_info_subject.bzl @@ -57,6 +57,7 @@ def _new_java_compilation_info_subject(java_info, meta): ) public = struct( compilation_classpath = lambda: subjects.depset_file(self.actual.compilation_classpath, self.meta.derive("compilation_classpath")), + boot_classpath = lambda: subjects.depset_file(self.actual.boot_classpath, self.meta.derive("boot_classpath")), runtime_classpath = lambda: subjects.depset_file(self.actual.runtime_classpath, self.meta.derive("runtime_classpath")), runtime_classpath_list = lambda: subjects.collection(self.actual.runtime_classpath.to_list(), self.meta.derive("runtime_classpath.to_list()"), format = True), javac_options = lambda: subjects.collection(helper.tokenize_javacopts(opts = self.actual.javac_options), self.meta.derive("javac_options"), format = True), diff --git a/test/java/testutil/javac_action_subject.bzl b/test/java/testutil/javac_action_subject.bzl index 3c405665..ab957abe 100644 --- a/test/java/testutil/javac_action_subject.bzl +++ b/test/java/testutil/javac_action_subject.bzl @@ -37,6 +37,7 @@ def _new_javac_action_subject(env, target, output): outputs = lambda: subjects.collection([o.short_path for o in action_subject.actual.outputs.to_list()], self.meta.derive("outputs()"), format = True), argv = action_subject.argv, mnemonic = action_subject.mnemonic, + native_header_output = lambda: _create_subject_for_flag("--native_header_output", self.parsed_flags, self.meta), ) return public From 2e11dbd09b5c6fdcee276b11053baaf78f1d5647 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 30 Apr 2026 01:34:18 -0700 Subject: [PATCH 458/465] Fix `@rules_java` CI with `Bazel@HEAD`. Broken by https://github.com/bazelbuild/bazel/commit/905d8e09e4b8dc7333ecd7f4621c7d98f55948a2 [^1] (ignore-relnotes) PiperOrigin-RevId: 908023960 Change-Id: I113d44af93935dbee4cc4d5c534799f034d4dfff --- .../common_launcher_java_library_tests.bzl | 29 ------------------- test/java/common/rules/java_test_tests.bzl | 27 ----------------- 2 files changed, 56 deletions(-) diff --git a/test/java/common/rules/common_launcher_java_library_tests.bzl b/test/java/common/rules/common_launcher_java_library_tests.bzl index f0a19580..fe17a7b0 100644 --- a/test/java/common/rules/common_launcher_java_library_tests.bzl +++ b/test/java/common/rules/common_launcher_java_library_tests.bzl @@ -605,34 +605,6 @@ def _test_java_library_gen_source_no_processor_names_impl(env, target): "{package}/lib{name}.jar_manifest_proto", ]) -def _test_java_library_fix_deps_tool_written_to_params_file(name): - if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: - # Bazel 7 does not support transition on experimental_* flags. - # Exit early because this test case would be a loading phase error otherwise. - always_passes(name) - return - - util.helper_target( - java_library, - name = name + "/base", - srcs = ["Base.java"], - ) - - analysis_test( - name = name, - impl = _test_java_library_fix_deps_tool_written_to_params_file_impl, - config_settings = { - "//command_line_option:experimental_fix_deps_tool": "fixer", - }, - target = name + "/base", - ) - -def _test_java_library_fix_deps_tool_written_to_params_file_impl(env, target): - javac_action_subject.of(env, target, "{package}/lib{name}.jar").argv().contains_at_least([ - "--experimental_fix_deps_tool", - "fixer", - ]).in_order() - def _test_java_library_compilation_info_provider(name): util.helper_target( mock_java_toolchain, @@ -865,7 +837,6 @@ JAVA_LIBRARY_LAUNCHER_TESTS = [ _test_java_library_files_to_compile, _test_java_library_runtime_deps_are_not_on_classpath, _test_java_library_runtime_deps_are_not_on_classpath_with_header_compilation, - _test_java_library_fix_deps_tool_written_to_params_file, _test_java_library_propagates_native_libraries, _test_java_library_gen_source_no_processor_names, _test_java_library_annotation_processing_using_javacopt, diff --git a/test/java/common/rules/java_test_tests.bzl b/test/java/common/rules/java_test_tests.bzl index d4bd4b0e..6c71d335 100644 --- a/test/java/common/rules/java_test_tests.bzl +++ b/test/java/common/rules/java_test_tests.bzl @@ -67,32 +67,6 @@ def _test_deps_without_srcs_fails_impl(env, target): matching.contains("deps not allowed without srcs"), ) -def _test_fix_deps_tool(name): - if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: - always_passes(name) - return - util.helper_target( - rule = java_test, - name = name + "/test", - srcs = [name + "/Test.java"], - ) - - analysis_test( - name = name, - target = name + "/test", - impl = _test_fix_deps_tool_impl, - config_settings = { - "//command_line_option:experimental_fix_deps_tool": "customfixer", - }, - ) - -def _test_fix_deps_tool_impl(env, target): - assert_compile_action = env.expect.that_target(target).action_named("Javac") - assert_compile_action.argv().contains_at_least([ - "--experimental_fix_deps_tool", - "customfixer", - ]).in_order() - def _test_java_test_propagates_direct_native_libraries(name): util.helper_target( cc_library, @@ -358,7 +332,6 @@ def java_test_tests(name): tests = [ _test_java_test_is_test_only, _test_deps_without_srcs_fails, - _test_fix_deps_tool, _test_java_test_propagates_direct_native_libraries, _test_coverage_uses_coverage_runner_for_main, _test_stamp_values, From 206ebe3ce99cfebc65d420ccab1e7f50174336a4 Mon Sep 17 00:00:00 2001 From: Googler Date: Mon, 4 May 2026 09:28:30 -0700 Subject: [PATCH 459/465] Add java_library tests (ignore-relnotes) PiperOrigin-RevId: 910074524 Change-Id: If420bab81faef3164e323355e5e1c4a1647891c8 --- .../common_launcher_java_library_tests.bzl | 275 +++++++++++++++++- test/java/testutil/javac_action_subject.bzl | 2 + .../testutil/javac_action_subject_tests.bzl | 8 + 3 files changed, 284 insertions(+), 1 deletion(-) diff --git a/test/java/common/rules/common_launcher_java_library_tests.bzl b/test/java/common/rules/common_launcher_java_library_tests.bzl index fe17a7b0..b1faa10b 100644 --- a/test/java/common/rules/common_launcher_java_library_tests.bzl +++ b/test/java/common/rules/common_launcher_java_library_tests.bzl @@ -317,7 +317,7 @@ def _test_java_library_plugin_with_runtime_deps(name): java_plugin, name = name + "/plugin", srcs = ["Plugin.java"], - processor_class = "com.google.process.stuff", + processor_class = "com.example.process.stuff", deps = [name + "/lib"], ) util.helper_target( @@ -829,6 +829,273 @@ def _test_java_library_deps_without_srcs_impl(env, target): matching.contains("deps not allowed without srcs"), ) +def _test_dependency_artifacts_with_exports(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + always_passes(name) + return + + util.helper_target( + java_library, + name = name + "/e", + srcs = ["E.java"], + ) + util.helper_target( + java_library, + name = name + "/d", + srcs = ["D.java"], + ) + util.helper_target( + java_library, + name = name + "/c", + srcs = ["C.java"], + exports = [name + "/e"], + ) + util.helper_target( + java_library, + name = name + "/b", + exports = [name + "/d"], + ) + util.helper_target( + java_library, + name = name + "/a", + srcs = ["A.java"], + deps = [ + name + "/b", + name + "/c", + name + "/d", + ], + ) + + analysis_test( + name = name, + impl = _test_dependency_artifacts_with_exports_impl, + target = name + "/a", + config_settings = { + "//command_line_option:experimental_java_classpath": "javabuilder", + }, + ) + +def _test_dependency_artifacts_with_exports_impl(env, target): + javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") + javac_action.deps_artifacts().contains_exactly([ + "{bin_path}/{package}/lib{test_name}/c-hjar.jdeps", + "{bin_path}/{package}/lib{test_name}/d-hjar.jdeps", + "{bin_path}/{package}/lib{test_name}/e-hjar.jdeps", + ]) + +def _test_exports_are_indirect_not_direct(name): + util.helper_target( + java_library, + name = name + "/a", + srcs = ["a.java"], + ) + util.helper_target( + java_library, + name = name + "/b", + srcs = ["b.java"], + exports = [name + "/a"], + ) + util.helper_target( + java_library, + name = name + "/c", + srcs = ["c.java"], + deps = [name + "/b"], + ) + + analysis_test( + name = name, + impl = _test_exports_are_indirect_not_direct_impl, + targets = { + "b": name + "/b", + "c": name + "/c", + }, + ) + +def _test_exports_are_indirect_not_direct_impl(env, targets): + b_info = java_info_subject.from_target(env, targets.b) + c_info = java_info_subject.from_target(env, targets.c) + + b_info.compilation_info().compilation_classpath().contains_exactly([]) + + c_info.compilation_info().compilation_classpath().contains_at_least_predicates([ + matching.file_basename_equals("a-hjar.jar"), + matching.file_basename_equals("b-hjar.jar"), + ]) + +def _test_exports_runfiles(name): + util.helper_target( + java_library, + name = name + "/a", + srcs = ["a.java"], + data = ["data.txt"], + ) + util.helper_target( + java_library, + name = name + "/b", + srcs = ["b.java"], + exports = [name + "/a"], + ) + + analysis_test( + name = name, + impl = _test_exports_runfiles_impl, + target = name + "/b", + ) + +def _test_exports_runfiles_impl(env, target): + env.expect.that_target(target).runfiles().contains_exactly([ + "{workspace}/{package}/data.txt", + "{workspace}/{package}/lib{test_name}/a.jar", + "{workspace}/{package}/lib{test_name}/b.jar", + ]) + +def _test_exports_collect_source_jars(name): + util.helper_target( + java_library, + name = name + "/exp", + srcs = ["C.java"], + ) + util.helper_target( + java_library, + name = name + "/lib", + srcs = ["B.java"], + exports = [name + "/exp"], + ) + util.helper_target( + java_library, + name = name + "/a", + srcs = ["A.java"], + deps = [name + "/lib"], + ) + + analysis_test( + name = name, + impl = _test_exports_collect_source_jars_impl, + target = name + "/a", + ) + +def _test_exports_collect_source_jars_impl(env, target): + java_info_subject.from_target(env, target).transitive_source_jars().contains_exactly([ + "{package}/lib{test_name}/a-src.jar", + "{package}/lib{test_name}/lib-src.jar", + "{package}/lib{test_name}/exp-src.jar", + ]) + +def _test_exported_plugins_are_inherited(name): + util.helper_target( + java_plugin, + name = name + "/plugin", + srcs = ["Plugin.java"], + processor_class = "com.example.process.stuff", + ) + util.helper_target( + java_library, + name = name + "/exporting_lib", + srcs = ["ExportingLib.java"], + exported_plugins = [name + "/plugin"], + ) + util.helper_target( + java_library, + name = name + "/consuming_lib", + srcs = ["ConsumingLib.java"], + deps = [name + "/exporting_lib"], + ) + util.helper_target( + java_library, + name = name + "/leaf_lib", + srcs = ["LeafLib.java"], + deps = [name + "/consuming_lib"], + ) + + analysis_test( + name = name, + impl = _test_exported_plugins_are_inherited_impl, + targets = { + "consuming": name + "/consuming_lib", + "leaf": name + "/leaf_lib", + }, + ) + +def _test_exported_plugins_are_inherited_impl(env, targets): + # libconsuming_lib should include the plugin, since it directly depends on exporting_lib + javac_action_subject.of( + env, + targets.consuming, + "{package}/lib{test_name}/consuming_lib.jar", + ).processors().contains_exactly(["com.example.process.stuff"]) + + # but libleaf_lib should not, because its dependency is transitive. + javac_action_subject.of( + env, + targets.leaf, + "{package}/lib{test_name}/leaf_lib.jar", + ).processors().contains_exactly([]) + +def _test_exported_plugins_are_propagated_through_exports(name): + util.helper_target( + java_plugin, + name = name + "/plugin", + srcs = ["Plugin.java"], + processor_class = "com.example.process.stuff", + ) + util.helper_target( + java_library, + name = name + "/exporting_plugins_lib", + srcs = ["ExportingLib.java"], + exported_plugins = [name + "/plugin"], + ) + util.helper_target( + java_library, + name = name + "/exporting_lib", + srcs = ["ExportingLib.java"], + exports = [name + "/exporting_plugins_lib"], + ) + util.helper_target( + java_library, + name = name + "/consuming_lib", + srcs = ["ConsumingLib.java"], + exports = [name + "/exporting_lib"], + deps = [name + "/exporting_lib"], + ) + util.helper_target( + java_library, + name = name + "/leaf_lib", + srcs = ["LeafLib.java"], + deps = [name + "/consuming_lib"], + ) + + analysis_test( + name = name, + impl = _test_exported_plugins_are_propagated_through_exports_impl, + targets = { + "exporting": name + "/exporting_lib", + "consuming": name + "/consuming_lib", + "leaf": name + "/leaf_lib", + }, + ) + +def _test_exported_plugins_are_propagated_through_exports_impl(env, targets): + # libexporting_lib should not include the plugin, only export it further. + javac_action_subject.of( + env, + targets.exporting, + "{package}/lib{test_name}/exporting_lib.jar", + ).processors().contains_exactly([]) + + # libconsuming_lib should pick up the plugin through the export on exporting_lib. + javac_action_subject.of( + env, + targets.consuming, + "{package}/lib{test_name}/consuming_lib.jar", + ).processors().contains_exactly(["com.example.process.stuff"]) + + # libleaf_lib should pick up the plugin through the (transitive) export on exporting_lib. + javac_action_subject.of( + env, + targets.leaf, + "{package}/lib{test_name}/leaf_lib.jar", + ).processors().contains_exactly(["com.example.process.stuff"]) + JAVA_LIBRARY_LAUNCHER_TESTS = [ _test_java_library_rule_outputs, _test_java_library_action_graph, @@ -854,4 +1121,10 @@ JAVA_LIBRARY_LAUNCHER_TESTS = [ _test_java_library_transitive_strict_deps, _test_java_library_emit_output_deps, _test_java_library_deps_without_srcs, + _test_dependency_artifacts_with_exports, + _test_exports_are_indirect_not_direct, + _test_exports_runfiles, + _test_exports_collect_source_jars, + _test_exported_plugins_are_inherited, + _test_exported_plugins_are_propagated_through_exports, ] diff --git a/test/java/testutil/javac_action_subject.bzl b/test/java/testutil/javac_action_subject.bzl index ab957abe..a887d689 100644 --- a/test/java/testutil/javac_action_subject.bzl +++ b/test/java/testutil/javac_action_subject.bzl @@ -20,6 +20,7 @@ def _new_javac_action_subject(env, target, output): public = struct( direct_dependencies = lambda: _create_subject_for_flag("--direct_dependencies", self.parsed_flags, self.meta), + deps_artifacts = lambda: _create_subject_for_flag("--deps_artifacts", self.parsed_flags, self.meta), javacopts = lambda: _create_subject_for_flag("--javacopts", self.parsed_flags, self.meta), jar = lambda: _create_subject_for_flag("-jar", self.parsed_flags, self.meta), # An unset --strict_java_deps is equivalent to "OFF". @@ -31,6 +32,7 @@ def _new_javac_action_subject(env, target, output): system = lambda: _create_subject_for_flag("--system", self.parsed_flags, self.meta), generated_sources_output = lambda: _create_subject_for_flag("--generated_sources_output", self.parsed_flags, self.meta), processorpath = lambda: _create_subject_for_flag("--processorpath", self.parsed_flags, self.meta), + processors = lambda: _create_subject_for_flag("--processors", self.parsed_flags, self.meta, default = []), target_label = lambda: _create_subject_for_flag("--target_label", self.parsed_flags, self.meta), executable_file_name = lambda: subjects.str(action_subject.actual.argv[0], self.meta), inputs = action_subject.inputs, diff --git a/test/java/testutil/javac_action_subject_tests.bzl b/test/java/testutil/javac_action_subject_tests.bzl index c1e577be..dc8f3f47 100644 --- a/test/java/testutil/javac_action_subject_tests.bzl +++ b/test/java/testutil/javac_action_subject_tests.bzl @@ -35,6 +35,12 @@ def _parse_flags_test_impl(ctx): "--classpath", "pkg/bar-hjar.jar", "other/pkg/baz.jar", + "--processors", + "com.example.process.stuff", + "com.example.process.other", + "--deps_artifacts", + "pkg/dep1.jdeps", + "pkg/dep2.jdeps", ]) asserts.equals(env, { "-Xmx1g": [], @@ -64,6 +70,8 @@ def _parse_flags_test_impl(ctx): ], "--strict_java_deps": ["ERROR"], "--classpath": ["pkg/bar-hjar.jar", "other/pkg/baz.jar"], + "--processors": ["com.example.process.stuff", "com.example.process.other"], + "--deps_artifacts": ["pkg/dep1.jdeps", "pkg/dep2.jdeps"], }, flags) return unittest.end(env) From 1f939098d31726416fe22aacb5532ebc3afa3859 Mon Sep 17 00:00:00 2001 From: Googler Date: Tue, 5 May 2026 07:57:06 -0700 Subject: [PATCH 460/465] Open source one version tests (ignore-relnotes) PiperOrigin-RevId: 910688799 Change-Id: Ifa9ae668c58137ff14eb2aa1a2875c8ac5fe0b37 --- java/common/BUILD | 5 +- java/common/java_semantics.bzl | 2 + test/java/common/rules/java_binary_tests.bzl | 159 +++++++++++++++++++ test/java/common/rules/java_test_tests.bzl | 112 ++++++++++++- test/java/testutil/mock_java_toolchain.bzl | 10 +- 5 files changed, 285 insertions(+), 3 deletions(-) diff --git a/java/common/BUILD b/java/common/BUILD index 9881236a..7887b1f0 100644 --- a/java/common/BUILD +++ b/java/common/BUILD @@ -36,7 +36,10 @@ bzl_library( name = "semantics_bzl", srcs = ["java_semantics.bzl"], visibility = ["//visibility:public"], - deps = ["@rules_cc//cc/common:cc_helper_bzl"], + deps = [ + "@bazel_features//:features", + "@rules_cc//cc/common:cc_helper_bzl", + ], ) bzl_library( diff --git a/java/common/java_semantics.bzl b/java/common/java_semantics.bzl index e847d879..919553e9 100644 --- a/java/common/java_semantics.bzl +++ b/java/common/java_semantics.bzl @@ -13,6 +13,7 @@ # limitations under the License. """Bazel Java Semantics""" +load("@bazel_features//private:util.bzl", _bazel_version_ge = "ge") load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("@rules_cc//cc/common:cc_helper.bzl", "cc_helper") @@ -126,4 +127,5 @@ semantics = struct( INCOMPATIBLE_DISABLE_NON_EXECUTABLE_JAVA_BINARY = False, # Flip when java_single_jar is feature complete update_args_for_import_deps = _update_args_for_import_deps, expand_javacopts_make_variables = True, + java_toolchain_supports_one_version = _bazel_version_ge("8.0.0"), # can be dropped once we no longer support Bazel 7 ) diff --git a/test/java/common/rules/java_binary_tests.bzl b/test/java/common/rules/java_binary_tests.bzl index 7ee9eb1d..f2ab5be9 100644 --- a/test/java/common/rules/java_binary_tests.bzl +++ b/test/java/common/rules/java_binary_tests.bzl @@ -1,6 +1,7 @@ """Tests for the java_binary rule""" load("@bazel_features//:features.bzl", "bazel_features") +load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc:cc_binary.bzl", "cc_binary") load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") @@ -8,9 +9,12 @@ load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") +load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_helper.bzl", "helper") load("//test/java/common/rules:common_launcher_java_binary_tests.bzl", "JAVA_BINARY_LAUNCHER_TESTS") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:mock_java_toolchain.bzl", "mock_java_toolchain") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") load("//test/java/testutil:rules/forward_java_info.bzl", "java_info_forwarding_rule") @@ -250,6 +254,158 @@ def _test_java_binary_can_set_transitive_validation_impl(env, targets): # ensure they don't propagate to `bin` because they're a part of the `deploy_env` env.expect.that_target(targets.bin).output_group("_validation").contains_exactly([]) +def _test_one_version_check_action(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + # exit early because this test case would be a loading phase error otherwise + always_passes(name) + return + + util.helper_target( + java_library, + name = name + "/c", + srcs = [name + "/c.java"], + ) + util.helper_target( + java_library, + name = name + "/a", + srcs = [name + "/a.java"], + deps = [name + "/c"], + ) + util.helper_target( + java_binary, + name = name + "/b", + srcs = [name + "/b.java"], + deps = [name + "/a"], + ) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + oneversion = "one_version_tool", + oneversion_allowlist = "one_version_allowlist", + ) + + analysis_test( + name = name, + impl = _test_one_version_check_action_impl, + target = name + "/b", + config_settings = { + "//command_line_option:experimental_one_version_enforcement": "ERROR", + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + attrs = { + "_windows_constraints": attr.label_list( + default = [paths.join(semantics.PLATFORMS_ROOT, "os:windows")], + ), + }, + ) + +def _test_one_version_check_action_impl(env, target): + assert_target = env.expect.that_target(target) + assert_target.default_outputs().contains_exactly([ + "{package}/{test_name}/b.jar", + "{package}/{test_name}/b" + (".exe" if helper.is_target_platform_windows(env.ctx) else ""), + ]) + assert_target.output_group("_validation").contains( + "{package}/{name}-one-version.txt", + ) + assert_action = assert_target.action_generating("{package}/{name}-one-version.txt") + assert_action.mnemonic().equals("JavaOneVersion") + assert_action.inputs().contains_at_least([ + "{package}/{test_name}/b.jar", + "{package}/lib{test_name}/a.jar", + "{package}/lib{test_name}/c.jar", + ]) + tool = [f for f in assert_action.actual.inputs.to_list() if f.short_path.endswith("one_version_tool")][0] + assert_action.argv().contains_exactly([ + tool.path, + "--output", + "{bindir}/{package}/{name}-one-version.txt", + "--allowlist", + "{package}/one_version_allowlist", + "--inputs", + "{bindir}/{package}/{test_name}/b.jar,//{package}:{test_name}/b", + "{bindir}/{package}/lib{test_name}/a.jar,//{package}:{test_name}/a", + "{bindir}/{package}/lib{test_name}/c.jar,//{package}:{test_name}/c", + ]).in_order() + +def _test_one_version_check_violations_allowed(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + # exit early because this test case would be a loading phase error otherwise + always_passes(name) + return + + util.helper_target( + java_binary, + name = name + "/foo", + srcs = [name + "/foo.java"], + ) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + oneversion = "one_version_tool", + oneversion_allowlist = "one_version_allowlist", + ) + + analysis_test( + name = name, + impl = _test_one_version_check_violations_allowed_impl, + target = name + "/foo", + config_settings = { + "//command_line_option:experimental_one_version_enforcement": "WARNING", + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + ) + +def _test_one_version_check_violations_allowed_impl(env, target): + assert_action = env.expect.that_target(target).action_generating( + "{package}/{name}-one-version.txt", + ) + env.expect.that_target(target).output_group("_validation").contains( + "{package}/{name}-one-version.txt", + ) + tool = [f for f in assert_action.actual.inputs.to_list() if f.short_path.endswith("one_version_tool")][0] + assert_action.argv().contains_exactly([ + tool.path, + "--output", + "{bindir}/{package}/{name}-one-version.txt", + "--allowlist", + "{package}/one_version_allowlist", + "--succeed_on_found_violations", + "--inputs", + "{bindir}/{package}/{test_name}/foo.jar,//{package}:{test_name}/foo", + ]).in_order() + +def _test_one_version_check_disabled(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + # exit early because this test case would be a loading phase error otherwise + always_passes(name) + return + + util.helper_target( + java_binary, + name = name + "/foo", + srcs = [name + "/foo.java"], + ) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + oneversion = "one_version_tool", + ) + + analysis_test( + name = name, + impl = _test_one_version_check_disabled_impl, + target = name + "/foo", + config_settings = { + "//command_line_option:experimental_one_version_enforcement": "OFF", + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + ) + +def _test_one_version_check_disabled_impl(env, target): + action_mnemonics = [a.mnemonic for a in env.expect.that_target(target).actual.actions] + env.expect.that_collection(action_mnemonics).not_contains("JavaOneVersion") + def java_binary_tests(name): test_suite( name = "_basic_" + name, @@ -260,6 +416,9 @@ def java_binary_tests(name): _test_java_binary_propagates_direct_native_libraries, _test_java_compile_only, _test_java_binary_can_set_transitive_validation, + _test_one_version_check_action, + _test_one_version_check_violations_allowed, + _test_one_version_check_disabled, ], ) diff --git a/test/java/common/rules/java_test_tests.bzl b/test/java/common/rules/java_test_tests.bzl index 6c71d335..995872f1 100644 --- a/test/java/common/rules/java_test_tests.bzl +++ b/test/java/common/rules/java_test_tests.bzl @@ -1,18 +1,21 @@ """Tests for the java_test rule""" load("@bazel_features//:features.bzl", "bazel_features") +load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc:cc_binary.bzl", "cc_binary") load("@rules_cc//cc:cc_library.bzl", "cc_library") load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching", "subjects") load("@rules_testing//lib:util.bzl", "util") +load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") load("//java:java_test.bzl", "java_test") load("//java/common:java_info.bzl", "JavaInfo") load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_helper.bzl", "helper") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:mock_cc_toolchain.bzl", "mock_cc_toolchain") -load("//test/java/testutil:mock_java_toolchain.bzl", "mock_java_runtime_toolchain") +load("//test/java/testutil:mock_java_toolchain.bzl", "mock_java_runtime_toolchain", "mock_java_toolchain") load("//test/java/testutil:mock_test_toolchain.bzl", "mock_test_toolchains") load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") @@ -326,6 +329,111 @@ def _test_java_test_sets_securiry_manager_property_jdk17_impl(env, target): matching.str_matches("-Djava.security.manager=allow"), ) +def _test_one_version_check_java_test(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + # exit early because this test case would be a loading phase error otherwise + always_passes(name) + return + + util.helper_target( + java_library, + name = name + "/foo", + srcs = [name + "/foo.java"], + ) + util.helper_target( + java_test, + name = name + "/foo_test", + srcs = [name + "/foo_test.java"], + deps = [name + "/foo"], + use_testrunner = False, + ) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + oneversion = "one_version_tool", + oneversion_allowlist = "one_version_allowlist", + oneversion_allowlist_for_tests = "one_version_allowlist_for_tests", + ) + + analysis_test( + name = name, + impl = _test_one_version_check_java_test_impl, + target = name + "/foo_test", + config_settings = { + "//command_line_option:experimental_one_version_enforcement": "ERROR", + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + attrs = { + "_windows_constraints": attr.label_list( + default = [paths.join(semantics.PLATFORMS_ROOT, "os:windows")], + ), + }, + ) + +def _test_one_version_check_java_test_impl(env, target): + assert_target = env.expect.that_target(target) + assert_target.default_outputs().contains_exactly([ + "{package}/{test_name}/foo_test.jar", + "{package}/{test_name}/foo_test" + (".exe" if helper.is_target_platform_windows(env.ctx) else ""), + ]) + assert_action = assert_target.action_generating( + "{package}/{name}-one-version.txt", + ) + tool = [f for f in assert_action.actual.inputs.to_list() if f.short_path.endswith("one_version_tool")][0] + assert_action.argv().contains_exactly([ + tool.path, + "--output", + "{bindir}/{package}/{name}-one-version.txt", + "--allowlist", + "{package}/one_version_allowlist_for_tests", + "--inputs", + "{bindir}/{package}/{test_name}/foo_test.jar,//{package}:{test_name}/foo_test", + "{bindir}/{package}/lib{test_name}/foo.jar,//{package}:{test_name}/foo", + ]).in_order() + +def _test_one_version_check_disabled_for_java_test(name): + if not bazel_features.rules.analysis_tests_can_transition_on_experimental_incompatible_flags: + # exit early because this test case would be a loading phase error otherwise + always_passes(name) + return + + util.helper_target( + java_test, + name = name + "/foo_test", + srcs = [name + "/foo.java"], + use_testrunner = False, + ) + util.helper_target( + java_binary, + name = name + "/foo_binary", + srcs = [name + "/foo.java"], + ) + util.helper_target( + mock_java_toolchain, + name = name + "/toolchain", + oneversion = "one_version_tool", + ) + + analysis_test( + name = name, + impl = _test_one_version_check_disabled_for_java_test_impl, + targets = { + "bin": name + "/foo_binary", + "test": name + "/foo_test", + }, + config_settings = { + "//command_line_option:experimental_one_version_enforcement": "ERROR", + "//command_line_option:one_version_enforcement_on_java_tests": False, + "//command_line_option:extra_toolchains": [Label(name + "/toolchain")], + }, + ) + +def _test_one_version_check_disabled_for_java_test_impl(env, targets): + binary_action_mnemonics = [a.mnemonic for a in env.expect.that_target(targets.bin).actual.actions] + test_action_mnemonics = [a.mnemonic for a in env.expect.that_target(targets.test).actual.actions] + env.expect.that_collection(binary_action_mnemonics).contains("JavaOneVersion") + env.expect.that_collection(test_action_mnemonics).not_contains("JavaOneVersion") + def java_test_tests(name): test_suite( name = name, @@ -338,5 +446,7 @@ def java_test_tests(name): _test_add_test_support_to_compile_time_deps_flag, _test_mac_requires_darwin_for_execution, _test_java_test_sets_securiry_manager_property_jdk17, + _test_one_version_check_java_test, + _test_one_version_check_disabled_for_java_test, ], ) diff --git a/test/java/testutil/mock_java_toolchain.bzl b/test/java/testutil/mock_java_toolchain.bzl index de824b16..aae0afde 100644 --- a/test/java/testutil/mock_java_toolchain.bzl +++ b/test/java/testutil/mock_java_toolchain.bzl @@ -15,11 +15,19 @@ def mock_java_toolchain( ijar = "ijar", genclass = "genclass", java_runtime = None, + oneversion = None, + oneversion_allowlist = None, + oneversion_allowlist_for_tests = None, tags = None, # for util.helper_target **kwargs): if not java_runtime: java_runtime = name + "_runtime" _java_runtime_rule(name = java_runtime) + one_version_args = { + "oneversion": oneversion, + "oneversion_allowlist": oneversion_allowlist, + "oneversion_allowlist_for_tests": oneversion_allowlist_for_tests, + } if semantics.java_toolchain_supports_one_version else {} java_toolchain( name = name + "_java", javabuilder = javabuilder, @@ -30,7 +38,7 @@ def mock_java_toolchain( java_runtime = java_runtime, genclass = genclass, tags = tags, - **kwargs + **(kwargs | one_version_args) ) native.toolchain( name = name, From ffd5c7502ee68292c9c48c8af280710f18122aa1 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 6 May 2026 07:24:59 -0700 Subject: [PATCH 461/465] Migrate the `javaTestInvalidTestClassAtRootPackage` test to Starlark The test is removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 911323913 Change-Id: Ie7cd3da252158916945911ef1cf59099a098e4e0 --- BUILD | 15 +++++++++++++++ test/java/bazel/rules/java_test_tests.bzl | 15 +++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/BUILD b/BUILD index 9f0e2239..2fbbbd62 100644 --- a/BUILD +++ b/BUILD @@ -1,4 +1,5 @@ load("@rules_license//rules:license.bzl", "license") +load("//java:java_test.bzl", "java_test") package(default_applicable_licenses = [":license"]) @@ -27,3 +28,17 @@ license( name = "license", package_name = "rules_java", ) + +# For exercising root-package behavior in tests +java_test( + name = "invalid_test_at_repo_root", + srcs = ["SomeTest.java"], + tags = [ + "manual", + "nobuilder", + "notap", + ], + visibility = [ + "//test/java/bazel/rules:__pkg__", + ], +) diff --git a/test/java/bazel/rules/java_test_tests.bzl b/test/java/bazel/rules/java_test_tests.bzl index 9ee618d8..5c76b0ee 100644 --- a/test/java/bazel/rules/java_test_tests.bzl +++ b/test/java/bazel/rules/java_test_tests.bzl @@ -35,10 +35,25 @@ def _test_deduced_test_class_impl(env, target): matching.str_matches("-Dbazel.test_suite=bazel.rules.test_deduced_test_class.foo"), ) +# regression test for https://github.com/bazelbuild/bazel/issues/20378 +def _test_invalid_test_class_at_repo_root(name): + analysis_test( + name = name, + impl = _test_invalid_test_class_at_repo_root_impl, + target = "//:invalid_test_at_repo_root", + expect_failure = True, + ) + +def _test_invalid_test_class_at_repo_root_impl(env, target): + env.expect.that_target(target).failures().contains_predicate( + matching.str_matches("cannot determine test class."), + ) + def java_test_tests(name): test_suite( name = name, tests = [ _test_deduced_test_class, + _test_invalid_test_class_at_repo_root, ], ) From c54e911d6b351ca25dbba05756ffb98336960346 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 27 May 2026 02:21:48 -0700 Subject: [PATCH 462/465] Create a `java_common.compile_header` API that just does the header compilation part of `java_common.compile` PiperOrigin-RevId: 921992069 Change-Id: I4dfc3671c04175e2a803427dab64a7db2a7d180c --- java/private/java_common.bzl | 28 +++ java/private/java_common_internal.bzl | 305 +++++++++++++++++++------- java/private/java_info.bzl | 2 +- 3 files changed, 253 insertions(+), 82 deletions(-) diff --git a/java/private/java_common.bzl b/java/private/java_common.bzl index 174f4e6a..59ba7dfc 100644 --- a/java/private/java_common.bzl +++ b/java/private/java_common.bzl @@ -22,6 +22,7 @@ load("//java/common/rules:java_toolchain.bzl", "JavaToolchainInfo") load(":boot_class_path_info.bzl", "BootClassPathInfo") load( ":java_common_internal.bzl", + _compile_header_internal = "compile_header", _compile_internal = "compile", _run_ijar_internal = "run_ijar", ) @@ -89,6 +90,32 @@ def _compile( enable_annotation_processing = enable_annotation_processing, ) +def _compile_header( + ctx, + output, + java_toolchain, + source_jars = [], + source_files = [], + javac_opts = [], + deps = [], + plugins = [], + strict_deps = "ERROR", + bootclasspath = None, + enable_annotation_processing = True): + return _compile_header_internal( + ctx, + output = output, + java_toolchain = java_toolchain, + source_jars = source_jars, + source_files = source_files, + javac_opts = javac_opts, + deps = deps, + plugins = plugins, + strict_deps = strict_deps, + bootclasspath = bootclasspath, + enable_annotation_processing = enable_annotation_processing, + ) + def _run_ijar(actions, jar, java_toolchain, target_label = None): get_internal_java_common().check_java_toolchain_is_declared_on_rule(actions) return _run_ijar_internal( @@ -277,6 +304,7 @@ def _make_java_common(): methods = { "provider": JavaInfo, "compile": _compile, + "compile_header": _compile_header, "run_ijar": _run_ijar, "stamp_jar": _stamp_jar, "pack_sources": _pack_sources, diff --git a/java/private/java_common_internal.bzl b/java/private/java_common_internal.bzl index 249b9255..30d9533c 100644 --- a/java/private/java_common_internal.bzl +++ b/java/private/java_common_internal.bzl @@ -37,6 +37,103 @@ _STRICT_DEPS_VALUES = [ "DEFAULT", # When no flag value is specified on the command line. ] +def _construct_javac_opts(ctx, java_toolchain, plugin_info, javac_opts, bootclasspath, add_exports = []): + all_javac_opts = [] # [depset[str]] + all_javac_opts.append(java_toolchain._javacopts) + all_javac_opts.append(ctx.fragments.java.default_javac_flags_depset) + all_javac_opts.append(semantics.compatible_javac_options(ctx, java_toolchain)) + + if ("com.google.devtools.build.runfiles.AutoBazelRepositoryProcessor" in + plugin_info.plugins.processor_classes.to_list()): + all_javac_opts.append(depset( + ["-Abazel.repository=" + ctx.label.repo_name], + order = "preorder", + )) + system_bootclasspath = None + for package_config in java_toolchain._package_configuration: + if package_config.matches(package_config.package_specs, ctx.label): + all_javac_opts.append(package_config.javac_opts) + if package_config.system: + if system_bootclasspath: + fail("Multiple system package configurations found for %s" % ctx.label) + system_bootclasspath = package_config.system + if not bootclasspath: + bootclasspath = system_bootclasspath + + all_javac_opts.append(depset( + ["--add-exports=%s=ALL-UNNAMED" % x for x in add_exports], + order = "preorder", + )) + + if type(javac_opts) == type([]): + # detokenize target's javacopts, it will be tokenized before compilation + all_javac_opts.append(helper.detokenize_javacopts(helper.tokenize_javacopts(ctx, javac_opts))) + elif type(javac_opts) == type(depset()): + all_javac_opts.append(javac_opts) + else: + fail("Expected javac_opts to be a list or depset, got:", type(javac_opts)) + + # we reverse the list of javacopts depsets, so that we keep the right-most set + # in case it's deduped. When this depset is flattened, we will reverse again, + # and then tokenize before passing to javac. This way, right-most javacopts will + # be retained and "win out". + return depset(order = "preorder", transitive = reversed(all_javac_opts)), bootclasspath + +def _construct_classpaths(deps, strict_deps, classpath_mode): + is_strict_mode = strict_deps != "OFF" + + direct_jars = depset() + if is_strict_mode: + direct_jars = depset(order = "preorder", transitive = [dep.compile_jars for dep in deps]) + + header_compilation_direct_deps = depset() + if is_strict_mode: + header_compilation_direct_deps = depset( + order = "preorder", + transitive = [dep.header_compilation_direct_deps for dep in deps], + ) + + compilation_classpath = depset( + order = "preorder", + transitive = [direct_jars] + [dep.transitive_compile_time_jars for dep in deps], + ) + compile_time_java_deps = depset() + if is_strict_mode and classpath_mode != "OFF": + compile_time_java_deps = depset(transitive = [dep._compile_time_java_dependencies for dep in deps]) + + return struct( + direct_jars = direct_jars, + header_compilation_direct_deps = header_compilation_direct_deps, + compilation_classpath = compilation_classpath, + compile_time_java_deps = compile_time_java_deps, + ) + +def _derive_header_compilation_outputs(ctx, base_output, suffix = ""): + if suffix: + compile_jar = _derive_output_file(ctx, base_output, name_suffix = suffix, extension = "jar") + compile_deps_proto = _derive_output_file(ctx, base_output, name_suffix = suffix, extension = "jdeps") + else: + compile_jar = base_output + compile_deps_proto = _derive_output_file(ctx, base_output, extension = "jdeps") + + # TODO: b/417791104 - remove check after a Bazel release + if ctx.fragments.java.use_header_compilation_direct_deps(): + header_compilation_jar = _derive_output_file(ctx, base_output, name_suffix = "-tjar", extension = "jar") + else: + header_compilation_jar = None + + return struct( + compile_jar = compile_jar, + header_compilation_jar = header_compilation_jar, + compile_deps_proto = compile_deps_proto, + ) + +def _validate_strict_deps(strict_deps): + strict_deps = (strict_deps or "default").upper() + if strict_deps not in _STRICT_DEPS_VALUES: + fail("Got an invalid value for strict_deps:", strict_deps, "must be one of:", _STRICT_DEPS_VALUES) + return strict_deps + def compile( ctx, output, @@ -125,54 +222,18 @@ def compile( get_internal_java_common().check_provider_instances([java_toolchain], "java_toolchain", JavaToolchainInfo) get_internal_java_common().check_provider_instances(plugins, "plugins", JavaPluginInfo) - # normalize and validate strict_deps - strict_deps = (strict_deps or "default").upper() - if strict_deps not in _STRICT_DEPS_VALUES: - fail("Got an invalid value for strict_deps:", strict_deps, "must be one of:", _STRICT_DEPS_VALUES) + strict_deps = _validate_strict_deps(strict_deps) plugin_info = merge_plugin_info_without_outputs(plugins + deps) - all_javac_opts = [] # [depset[str]] - all_javac_opts.append(java_toolchain._javacopts) - - all_javac_opts.append(ctx.fragments.java.default_javac_flags_depset) - all_javac_opts.append(semantics.compatible_javac_options(ctx, java_toolchain)) - - if ("com.google.devtools.build.runfiles.AutoBazelRepositoryProcessor" in - plugin_info.plugins.processor_classes.to_list()): - all_javac_opts.append(depset( - ["-Abazel.repository=" + ctx.label.repo_name], - order = "preorder", - )) - system_bootclasspath = None - for package_config in java_toolchain._package_configuration: - if package_config.matches(package_config.package_specs, ctx.label): - all_javac_opts.append(package_config.javac_opts) - if package_config.system: - if system_bootclasspath: - fail("Multiple system package configurations found for %s" % ctx.label) - system_bootclasspath = package_config.system - if not bootclasspath: - bootclasspath = system_bootclasspath - - all_javac_opts.append(depset( - ["--add-exports=%s=ALL-UNNAMED" % x for x in add_exports], - order = "preorder", - )) - - if type(javac_opts) == type([]): - # detokenize target's javacopts, it will be tokenized before compilation - all_javac_opts.append(helper.detokenize_javacopts(helper.tokenize_javacopts(ctx, javac_opts))) - elif type(javac_opts) == type(depset()): - all_javac_opts.append(javac_opts) - else: - fail("Expected javac_opts to be a list or depset, got:", type(javac_opts)) - - # we reverse the list of javacopts depsets, so that we keep the right-most set - # in case it's deduped. When this depset is flattened, we will reverse again, - # and then tokenize before passing to javac. This way, right-most javacopts will - # be retained and "win out". - all_javac_opts = depset(order = "preorder", transitive = reversed(all_javac_opts)) + all_javac_opts, bootclasspath = _construct_javac_opts( + ctx, + java_toolchain, + plugin_info, + javac_opts, + bootclasspath, + add_exports, + ) # Optimization: skip this if there are no annotation processors, to avoid unnecessarily # disabling the direct classpath optimization if `enable_annotation_processor = False` @@ -190,27 +251,8 @@ def compile( has_sources = source_files or source_jars has_resources = resources or resource_jars - is_strict_mode = strict_deps != "OFF" classpath_mode = ctx.fragments.java.reduce_java_classpath() - - direct_jars = depset() - if is_strict_mode: - direct_jars = depset(order = "preorder", transitive = [dep.compile_jars for dep in deps]) - - header_compilation_direct_deps = depset() - if is_strict_mode: - header_compilation_direct_deps = depset( - order = "preorder", - transitive = [dep.header_compilation_direct_deps for dep in deps], - ) - - compilation_classpath = depset( - order = "preorder", - transitive = [direct_jars] + [dep.transitive_compile_time_jars for dep in deps], - ) - compile_time_java_deps = depset() - if is_strict_mode and classpath_mode != "OFF": - compile_time_java_deps = depset(transitive = [dep._compile_time_java_dependencies for dep in deps]) + classpaths = _construct_classpaths(deps, strict_deps, classpath_mode) # create compile time jar action if not has_sources: @@ -222,14 +264,10 @@ def compile( header_compilation_jar = compile_jar compile_deps_proto = None elif _should_use_header_compilation(ctx, java_toolchain): - compile_jar = _derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jar") - - # TODO: b/417791104 - remove check after a Bazel release - if ctx.fragments.java.use_header_compilation_direct_deps(): - header_compilation_jar = _derive_output_file(ctx, output, name_suffix = "-tjar", extension = "jar") - else: - header_compilation_jar = None - compile_deps_proto = _derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jdeps") + hdr_outputs = _derive_header_compilation_outputs(ctx, output, suffix = "-hjar") + compile_jar = hdr_outputs.compile_jar + header_compilation_jar = hdr_outputs.header_compilation_jar + compile_deps_proto = hdr_outputs.compile_deps_proto get_internal_java_common().create_header_compilation_action( ctx, java_toolchain, @@ -238,10 +276,10 @@ def compile( plugin_info, depset(source_files), source_jars, - compilation_classpath, - direct_jars, + classpaths.compilation_classpath, + classpaths.direct_jars, bootclasspath, - compile_time_java_deps, + classpaths.compile_time_java_deps, all_javac_opts, strict_deps, ctx.label, @@ -249,7 +287,7 @@ def compile( enable_direct_classpath, annotation_processor_additional_inputs, header_compilation_jar, - header_compilation_direct_deps, + classpaths.header_compilation_direct_deps, ) elif ctx.fragments.java.use_ijars(): compile_jar = run_ijar( @@ -282,11 +320,11 @@ def compile( output, manifest_proto, plugin_info, - compilation_classpath, - direct_jars, + classpaths.compilation_classpath, + classpaths.direct_jars, bootclasspath, depset(javabuilder_jvm_flags), - compile_time_java_deps, + classpaths.compile_time_java_deps, all_javac_opts, strict_deps, ctx.label, @@ -331,7 +369,7 @@ def compile( # needs to be flattened because the public API is a list boot_classpath = (bootclasspath.bootclasspath if bootclasspath else java_toolchain.bootclasspath).to_list(), # we only add compile time jars from deps, and not exports - compilation_classpath = compilation_classpath, + compilation_classpath = classpaths.compilation_classpath, runtime_classpath = depset( order = "preorder", direct = direct_runtime_jars, @@ -494,3 +532,108 @@ def get_runtime_classpath_for_archive(jars, excluded_jars): jars, excluded_jars, ) + +def compile_header( + ctx, + output, + java_toolchain, + source_jars = [], + source_files = [], + javac_opts = [], + deps = [], + plugins = [], + strict_deps = "ERROR", + bootclasspath = None, + injecting_rule_kind = None, + enable_annotation_processing = True): + """Compiles Java header jars from the implementation of a Starlark rule. + + Args: + ctx: (RuleContext) The rule context + output: (File) The output header jar (hjar) + java_toolchain: (JavaToolchainInfo) Toolchain to be used. Mandatory. + source_jars: ([File]) A list of the jars to be compiled. + source_files: ([File]) A list of the Java source files to be compiled. + javac_opts: ([str]|depset[str]) A list of the desired javac options. Optional. + deps: ([JavaInfo]) A list of dependencies. Optional. + plugins: ([JavaPluginInfo|JavaInfo]) A list of plugins. Optional. + strict_deps: (str) A string that specifies how to handle strict deps. Possible values: + 'OFF', 'ERROR', 'WARN' and 'DEFAULT'. + bootclasspath: (BootClassPathInfo) If present, overrides the bootclasspath associated with + the provided java_toolchain. Optional. + injecting_rule_kind: (str|None) + enable_annotation_processing: (bool) + + Returns: + (JavaInfo) + """ + get_internal_java_common().check_provider_instances([java_toolchain], "java_toolchain", JavaToolchainInfo) + get_internal_java_common().check_provider_instances(plugins, "plugins", JavaPluginInfo) + + strict_deps = _validate_strict_deps(strict_deps) + + plugin_info = merge_plugin_info_without_outputs(plugins + deps) + + all_javac_opts, bootclasspath = _construct_javac_opts( + ctx, + java_toolchain, + plugin_info, + javac_opts, + bootclasspath, + add_exports = [], + ) + + enable_direct_classpath = True + if not enable_annotation_processing and plugin_info.plugins.processor_classes: + plugin_info = disable_plugin_info_annotation_processing(plugin_info) + enable_direct_classpath = False + + classpaths = _construct_classpaths(deps, strict_deps, ctx.fragments.java.reduce_java_classpath()) + + hdr_outputs = _derive_header_compilation_outputs(ctx, output) + + get_internal_java_common().create_header_compilation_action( + ctx, + java_toolchain, + hdr_outputs.compile_jar, + hdr_outputs.compile_deps_proto, + plugin_info, + depset(source_files), + source_jars, + classpaths.compilation_classpath, + classpaths.direct_jars, + bootclasspath, + classpaths.compile_time_java_deps, + all_javac_opts, + strict_deps, + ctx.label, + injecting_rule_kind, + enable_direct_classpath, + [], # additional_inputs + hdr_outputs.header_compilation_jar, + classpaths.header_compilation_direct_deps, + ) + + return java_info_for_compilation( + output_jar = hdr_outputs.compile_jar, + compile_jar = hdr_outputs.compile_jar, + header_compilation_jar = hdr_outputs.header_compilation_jar, + source_jar = None, + generated_class_jar = None, + generated_source_jar = None, + plugin_info = plugin_info, + deps = deps, + runtime_deps = [], + exports = [], + exported_plugins = [], + compile_jdeps = hdr_outputs.compile_deps_proto, + jdeps = None, + native_headers_jar = None, + manifest_proto = None, + native_libraries = [], + neverlink = True, + add_exports = [], + add_opens = [], + direct_runtime_jars = [], + compilation_info = None, + ) diff --git a/java/private/java_info.bzl b/java/private/java_info.bzl index 19c435a2..e873ee1b 100644 --- a/java/private/java_info.bzl +++ b/java/private/java_info.bzl @@ -491,7 +491,7 @@ def java_info_for_compilation( runtime_output_jars = direct_runtime_jars, transitive_runtime_jars = transitive_runtime_jars, transitive_source_jars = depset( - direct = [source_jar], + direct = [source_jar] if source_jar else [], # only differs from the usual java_info.transitive_source_jars in the order of deps transitive = [dep.transitive_source_jars for dep in concatenated_deps.runtimedeps_exports_deps], ), From 7ed01c94b0b811415d1a35a31baab69be13977c4 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 27 May 2026 02:57:00 -0700 Subject: [PATCH 463/465] Migrate the module flag tests to Starlark The tests are removed from Bazel and added to rules_java (ignore-relnotes) PiperOrigin-RevId: 922006563 Change-Id: I7490d5219ed376c98f91e773018bad39a23d2cfc --- .bazelrc | 5 +- test/java/bazel/common/BUILD.bazel | 3 + test/java/bazel/common/java_info_tests.bzl | 67 +++++++++++++++++++ .../testutil/rules/custom_java_info_rule.bzl | 4 ++ 4 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 test/java/bazel/common/java_info_tests.bzl diff --git a/.bazelrc b/.bazelrc index 9db5d775..12d684fc 100644 --- a/.bazelrc +++ b/.bazelrc @@ -16,4 +16,7 @@ build --host_cxxopt=-std=c++17 # Some tests relies on dynamic libs that are not interface libs # the latter are always enabled on Windows: https://github.com/bazelbuild/bazel/blob/1f5414408467171581b6142e93f67fe730d722cf/src/main/java/com/google/devtools/build/lib/rules/cpp/CcModule.java#L2430 # we can't use a transition because toolchain deps exceed the default --analysis_testing_deps_limit. -test --nointerface_shared_objects \ No newline at end of file +test --nointerface_shared_objects + +# For testing add_exports/add_opens module flags behavior. +test --incompatible_java_info_merge_runtime_module_flags diff --git a/test/java/bazel/common/BUILD.bazel b/test/java/bazel/common/BUILD.bazel index 18ab4f84..c9cd0668 100644 --- a/test/java/bazel/common/BUILD.bazel +++ b/test/java/bazel/common/BUILD.bazel @@ -1,3 +1,6 @@ load(":java_common_tests.bzl", "java_common_tests") +load(":java_info_tests.bzl", "java_info_tests") java_common_tests(name = "java_common_tests") + +java_info_tests(name = "java_info_tests") diff --git a/test/java/bazel/common/java_info_tests.bzl b/test/java/bazel/common/java_info_tests.bzl new file mode 100644 index 00000000..cae1a922 --- /dev/null +++ b/test/java/bazel/common/java_info_tests.bzl @@ -0,0 +1,67 @@ +"""Tests for Bazel JavaInfo.""" + +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") +load("@rules_testing//lib:util.bzl", "util") +load("//java:java_library.bzl", "java_library") +load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") +load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") + +# We can't transition on a Starlark-semantics affecting flag, so this relies on +# --incompatible_java_info_merge_runtime_module_flags set in .bazelrc +def _test_create_java_info_with_module_flags_merge_runtime(name): + util.helper_target( + custom_java_info_rule, + name = name + "/my_starlark_rule", + output_jar = name + "/doesnotmatter.jar", + dep = [name + "/dep"], + dep_runtime = [name + "/runtime"], + dep_exports = [name + "/export"], + add_exports = ["java.base/java.lang.invoke"], + ) + util.helper_target( + java_library, + name = name + "/dep", + srcs = ["java/A.java"], + add_exports = ["java.base/java.lang"], + add_opens = ["java.base/java.lang"], + ) + + util.helper_target( + java_library, + name = name + "/runtime", + srcs = ["java/A.java"], + add_opens = ["java.base/java.util"], + ) + + util.helper_target( + java_library, + name = name + "/export", + srcs = ["java/A.java"], + add_opens = ["java.base/java.math"], + ) + + analysis_test( + name = name, + impl = _test_create_java_info_with_module_flags_merge_runtime_impl, + target = name + "/my_starlark_rule", + ) + +def _test_create_java_info_with_module_flags_merge_runtime_impl(env, target): + assert_module_info = java_info_subject.from_target(env, target).module_flags() + assert_module_info.add_exports().contains_exactly([ + "java.base/java.lang", + "java.base/java.lang.invoke", + ]).in_order() + assert_module_info.add_opens().contains_exactly([ + "java.base/java.util", + "java.base/java.math", + "java.base/java.lang", + ]).in_order() + +def java_info_tests(name): + test_suite( + name = name, + tests = [ + _test_create_java_info_with_module_flags_merge_runtime, + ], + ) diff --git a/test/java/testutil/rules/custom_java_info_rule.bzl b/test/java/testutil/rules/custom_java_info_rule.bzl index 3b61473a..e9a47918 100644 --- a/test/java/testutil/rules/custom_java_info_rule.bzl +++ b/test/java/testutil/rules/custom_java_info_rule.bzl @@ -61,6 +61,8 @@ def _impl(ctx): generated_source_jar = ctx.file.generated_source_jar, native_headers_jar = ctx.file.native_headers_jar, manifest_proto = ctx.file.manifest_proto, + add_exports = ctx.attr.add_exports, + add_opens = ctx.attr.add_opens, ), ] @@ -86,6 +88,8 @@ custom_java_info_rule = rule( "pack_sources": attr.bool(default = False), "stamp_jar": attr.bool(default = False), "compile_jar": attr.label(allow_single_file = True), + "add_exports": attr.string_list(), + "add_opens": attr.string_list(), }, toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], ) From aec8d4125cfaa2b876fe54e399b7a3523868d0f8 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 28 May 2026 02:36:43 -0700 Subject: [PATCH 464/465] Simplify launcher tests setup (ignore-relnotes) PiperOrigin-RevId: 922647628 Change-Id: Icfb5c255867440ecef0cac070e7090308ab7ae46 --- test/java/common/rules/BUILD | 6 ++ .../common_launcher_java_binary_tests.bzl | 12 ++- .../common_launcher_java_library_tests.bzl | 74 ++++++++++--------- test/java/common/rules/java_binary_tests.bzl | 17 +---- test/java/common/rules/java_library_tests.bzl | 17 +---- 5 files changed, 55 insertions(+), 71 deletions(-) diff --git a/test/java/common/rules/BUILD b/test/java/common/rules/BUILD index 0f1d293c..97589249 100644 --- a/test/java/common/rules/BUILD +++ b/test/java/common/rules/BUILD @@ -1,6 +1,8 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load(":add_exports_tests.bzl", "add_exports_tests") +load(":common_launcher_java_binary_tests.bzl", "java_binary_launcher_tests") +load(":common_launcher_java_library_tests.bzl", "java_library_launcher_tests") load(":deploy_archive_builder_tests.bzl", "deploy_archive_builder_test_suite") load(":java_binary_tests.bzl", "java_binary_tests") load(":java_import_tests.bzl", "java_import_tests") @@ -19,10 +21,14 @@ merge_attrs_test_suite(name = "merge_attrs_tests") java_binary_tests(name = "java_binary_tests") +java_binary_launcher_tests(name = "java_binary_launcher_tests") + java_plugin_tests(name = "java_plugin_tests") java_library_tests(name = "java_library_tests") +java_library_launcher_tests(name = "java_library_launcher_tests") + java_launcher_tests(name = "java_launcher_tests") java_import_tests(name = "java_import_tests") diff --git a/test/java/common/rules/common_launcher_java_binary_tests.bzl b/test/java/common/rules/common_launcher_java_binary_tests.bzl index 34c6e3f5..572f27a0 100644 --- a/test/java/common/rules/common_launcher_java_binary_tests.bzl +++ b/test/java/common/rules/common_launcher_java_binary_tests.bzl @@ -1,6 +1,6 @@ """Parameterized tests for java_binary with --java_launcher""" -load("@rules_testing//lib:analysis_test.bzl", "analysis_test") +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:util.bzl", "util") load("//java:java_binary.bzl", "java_binary") @@ -23,6 +23,10 @@ def _test_java_binary_non_executable_rule_outputs_impl(env, target): "{package}/{name}.jar", ]) -JAVA_BINARY_LAUNCHER_TESTS = [ - _test_java_binary_non_executable_rule_outputs, -] +def java_binary_launcher_tests(name): + test_suite( + name = name, + tests = [ + _test_java_binary_non_executable_rule_outputs, + ], + ) diff --git a/test/java/common/rules/common_launcher_java_library_tests.bzl b/test/java/common/rules/common_launcher_java_library_tests.bzl index b1faa10b..6c6af1d0 100644 --- a/test/java/common/rules/common_launcher_java_library_tests.bzl +++ b/test/java/common/rules/common_launcher_java_library_tests.bzl @@ -2,7 +2,7 @@ load("@bazel_features//:features.bzl", "bazel_features") load("@rules_cc//cc:cc_library.bzl", "cc_library") -load("@rules_testing//lib:analysis_test.bzl", "analysis_test") +load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") load("@rules_testing//lib:truth.bzl", "matching") load("@rules_testing//lib:util.bzl", "util") load("//java:java_import.bzl", "java_import") @@ -76,7 +76,7 @@ def _test_java_library_deps_of_genrule_are_not_on_classpath(name): util.helper_target( native.genrule, name = name + "/has_java_dep", - outs = ["foo.jar"], + outs = [name + "_foo.jar"], cmd = "echo NOT EXECUTED", tools = [name + "/root_dep"], ) @@ -99,7 +99,7 @@ def _test_java_library_deps_of_genrule_are_not_on_classpath(name): ) def _test_java_library_deps_of_genrule_are_not_on_classpath_impl(env, target): - expected_classpath = "{bin_path}/{package}/_ijar/{test_name}/has_java_dep_import/{package}/foo-ijar.jar" + expected_classpath = "{bin_path}/{package}/_ijar/{test_name}/has_java_dep_import/{package}/{test_name}_foo-ijar.jar" javac_action_subject.of(env, target, "{package}/lib{name}.jar").classpath().contains_exactly([expected_classpath]) def _test_java_library_compile_and_run_time_paths(name): @@ -1096,35 +1096,39 @@ def _test_exported_plugins_are_propagated_through_exports_impl(env, targets): "{package}/lib{test_name}/leaf_lib.jar", ).processors().contains_exactly(["com.example.process.stuff"]) -JAVA_LIBRARY_LAUNCHER_TESTS = [ - _test_java_library_rule_outputs, - _test_java_library_action_graph, - _test_java_library_deps_of_genrule_are_not_on_classpath, - _test_java_library_compile_and_run_time_paths, - _test_java_library_files_to_compile, - _test_java_library_runtime_deps_are_not_on_classpath, - _test_java_library_runtime_deps_are_not_on_classpath_with_header_compilation, - _test_java_library_propagates_native_libraries, - _test_java_library_gen_source_no_processor_names, - _test_java_library_annotation_processing_using_javacopt, - _test_java_library_javacopts_with_location_expansion, - _test_java_library_invalid_plugin, - _test_java_library_plugin_with_runtime_deps, - _test_java_library_source_jar_without_annotation_processing, - _test_java_library_source_jars_with_source_jars, - _test_java_library_should_set_bootclasspath, - _test_java_library_command_line_contains_target_label_and_rule_kind, - _test_java_library_compilation_info_provider, - _test_java_library_native_header_outputs, - _test_java_library_module_javacopts, - _test_java_library_forwarded_deps, - _test_java_library_transitive_strict_deps, - _test_java_library_emit_output_deps, - _test_java_library_deps_without_srcs, - _test_dependency_artifacts_with_exports, - _test_exports_are_indirect_not_direct, - _test_exports_runfiles, - _test_exports_collect_source_jars, - _test_exported_plugins_are_inherited, - _test_exported_plugins_are_propagated_through_exports, -] +def java_library_launcher_tests(name): + test_suite( + name = name, + tests = [ + _test_java_library_rule_outputs, + _test_java_library_action_graph, + _test_java_library_deps_of_genrule_are_not_on_classpath, + _test_java_library_compile_and_run_time_paths, + _test_java_library_files_to_compile, + _test_java_library_runtime_deps_are_not_on_classpath, + _test_java_library_runtime_deps_are_not_on_classpath_with_header_compilation, + _test_java_library_propagates_native_libraries, + _test_java_library_gen_source_no_processor_names, + _test_java_library_annotation_processing_using_javacopt, + _test_java_library_javacopts_with_location_expansion, + _test_java_library_invalid_plugin, + _test_java_library_plugin_with_runtime_deps, + _test_java_library_source_jar_without_annotation_processing, + _test_java_library_source_jars_with_source_jars, + _test_java_library_should_set_bootclasspath, + _test_java_library_command_line_contains_target_label_and_rule_kind, + _test_java_library_compilation_info_provider, + _test_java_library_native_header_outputs, + _test_java_library_module_javacopts, + _test_java_library_forwarded_deps, + _test_java_library_transitive_strict_deps, + _test_java_library_emit_output_deps, + _test_java_library_deps_without_srcs, + _test_dependency_artifacts_with_exports, + _test_exports_are_indirect_not_direct, + _test_exports_runfiles, + _test_exports_collect_source_jars, + _test_exported_plugins_are_inherited, + _test_exported_plugins_are_propagated_through_exports, + ], + ) diff --git a/test/java/common/rules/java_binary_tests.bzl b/test/java/common/rules/java_binary_tests.bzl index f2ab5be9..b483516d 100644 --- a/test/java/common/rules/java_binary_tests.bzl +++ b/test/java/common/rules/java_binary_tests.bzl @@ -11,7 +11,6 @@ load("//java:java_binary.bzl", "java_binary") load("//java:java_library.bzl", "java_library") load("//java/common:java_semantics.bzl", "semantics") load("//java/common/rules:java_helper.bzl", "helper") -load("//test/java/common/rules:common_launcher_java_binary_tests.bzl", "JAVA_BINARY_LAUNCHER_TESTS") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:mock_java_toolchain.bzl", "mock_java_toolchain") @@ -408,7 +407,7 @@ def _test_one_version_check_disabled_impl(env, target): def java_binary_tests(name): test_suite( - name = "_basic_" + name, + name = name, tests = [ _test_java_binary_provides_binary_java_info, _test_stamp_conversion_does_not_override_int, @@ -421,17 +420,3 @@ def java_binary_tests(name): _test_one_version_check_disabled, ], ) - - # TODO: unset --java_launcher explicitly - test_suite( - name = "_jdk_launcher_" + name, - tests = JAVA_BINARY_LAUNCHER_TESTS, - ) - - native.test_suite( - name = name, - tests = [ - "_basic_" + name, - "_jdk_launcher_" + name, - ], - ) diff --git a/test/java/common/rules/java_library_tests.bzl b/test/java/common/rules/java_library_tests.bzl index 77980f2f..4115b121 100644 --- a/test/java/common/rules/java_library_tests.bzl +++ b/test/java/common/rules/java_library_tests.bzl @@ -9,7 +9,6 @@ load("@rules_testing//lib:util.bzl", "util") load("//java:java_library.bzl", "java_library") load("//java:java_plugin.bzl", "java_plugin") load("//java/common:java_info.bzl", "JavaInfo") -load("//test/java/common/rules:common_launcher_java_library_tests.bzl", "JAVA_LIBRARY_LAUNCHER_TESTS") load("//test/java/testutil:helper.bzl", "always_passes") load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") load("//test/java/testutil:javac_action_subject.bzl", "javac_action_subject") @@ -351,7 +350,7 @@ def _test_strict_java_deps_error(name): def java_library_tests(name): test_suite( - name = "_basic_" + name, + name = name, tests = [ _test_exposes_plugins, _test_exposes_java_info, @@ -364,17 +363,3 @@ def java_library_tests(name): _test_strict_java_deps_error, ], ) - - # TODO: unset --java_launcher explicitly - test_suite( - name = "_jdk_launcher_" + name, - tests = JAVA_LIBRARY_LAUNCHER_TESTS, - ) - - native.test_suite( - name = name, - tests = [ - "_basic_" + name, - "_jdk_launcher_" + name, - ], - ) From 70844db4b45d59560c252087ffeade335172e707 Mon Sep 17 00:00:00 2001 From: Googler Date: Thu, 28 May 2026 03:06:42 -0700 Subject: [PATCH 465/465] Fix test formatting and hard-coded value(s) (ignore-relnotes) PiperOrigin-RevId: 922659214 Change-Id: Ib8e6bc47538d28a0d3f03e36b96c7585f2b3f5bd --- .../common_launcher_java_library_tests.bzl | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/test/java/common/rules/common_launcher_java_library_tests.bzl b/test/java/common/rules/common_launcher_java_library_tests.bzl index 6c6af1d0..c66256ec 100644 --- a/test/java/common/rules/common_launcher_java_library_tests.bzl +++ b/test/java/common/rules/common_launcher_java_library_tests.bzl @@ -210,10 +210,10 @@ def _test_java_library_runtime_deps_are_not_on_classpath_with_header_compilation analysis_test( name = name, - impl = _test_java_library_runtime_deps_are_not_on_classpath_with_header_compilation_impl, config_settings = { "//command_line_option:java_header_compilation": True, }, + impl = _test_java_library_runtime_deps_are_not_on_classpath_with_header_compilation_impl, target = name + "/depends_on_runtimedep", ) @@ -291,9 +291,9 @@ def _test_java_library_invalid_plugin(name): analysis_test( name = name, + expect_failure = True, impl = _test_java_library_invalid_plugin_impl, target = name + "/lib", - expect_failure = True, ) def _test_java_library_invalid_plugin_impl(env, target): @@ -437,12 +437,12 @@ def _test_java_library_should_set_bootclasspath(name): analysis_test( name = name, - impl = _test_java_library_should_set_bootclasspath_impl, config_settings = { "//command_line_option:extra_toolchains": [ native.package_relative_label(name + "/toolchain"), ], }, + impl = _test_java_library_should_set_bootclasspath_impl, target = name + "/test_lib", ) @@ -450,7 +450,7 @@ def _test_java_library_should_set_bootclasspath_impl(env, target): javac_action = javac_action_subject.of(env, target, "{package}/lib{name}.jar") javac_action.bootclasspath().contains_exactly([ - "{bin_path}/{package}/test_java_library_should_set_bootclasspath/boot.jar", + "{bin_path}/{package}/{test_name}/boot.jar", ]) def _test_java_library_command_line_contains_target_label_and_rule_kind(name): @@ -620,12 +620,12 @@ def _test_java_library_compilation_info_provider(name): analysis_test( name = name, - impl = _test_java_library_compilation_info_provider_impl, config_settings = { "//command_line_option:extra_toolchains": [ native.package_relative_label(name + "/toolchain"), ], }, + impl = _test_java_library_compilation_info_provider_impl, target = name + "/test_lib", ) @@ -757,10 +757,10 @@ def _test_java_library_transitive_strict_deps(name): analysis_test( name = name, - impl = _test_java_library_transitive_strict_deps_impl, config_settings = { "//command_line_option:experimental_strict_java_deps": "ERROR", }, + impl = _test_java_library_transitive_strict_deps_impl, target = name + "/a", ) @@ -784,10 +784,10 @@ def _test_java_library_emit_output_deps(name): analysis_test( name = name, - impl = _test_java_library_emit_output_deps_impl, config_settings = { "//command_line_option:java_deps": True, }, + impl = _test_java_library_emit_output_deps_impl, targets = { "a": name + "/a", "b": name + "/b", @@ -819,9 +819,9 @@ def _test_java_library_deps_without_srcs(name): analysis_test( name = name, + expect_failure = True, impl = _test_java_library_deps_without_srcs_impl, target = name + "/a", - expect_failure = True, ) def _test_java_library_deps_without_srcs_impl(env, target): @@ -868,11 +868,11 @@ def _test_dependency_artifacts_with_exports(name): analysis_test( name = name, - impl = _test_dependency_artifacts_with_exports_impl, - target = name + "/a", config_settings = { "//command_line_option:experimental_java_classpath": "javabuilder", }, + impl = _test_dependency_artifacts_with_exports_impl, + target = name + "/a", ) def _test_dependency_artifacts_with_exports_impl(env, target):