├── .bazel_checkout ├── __README └── setup.sh ├── .bazelci └── presubmit.yml ├── .bazelignore ├── .bazelrc ├── .bcr ├── metadata.template.json ├── presubmit.yml └── source.template.json ├── .github └── ISSUE_TEMPLATE │ └── release.md ├── .gitignore ├── AUTHORS ├── BUILD ├── CODEOWNERS ├── CONTRIBUTING.md ├── LICENSE ├── MODULE.bazel ├── README.md ├── WORKSPACE ├── WORKSPACE.bzlmod ├── distro ├── BUILD.bazel ├── README.md └── relnotes.bzl ├── examples └── hello_world │ ├── BUILD │ └── com │ └── google │ └── HelloWorld.java ├── java ├── BUILD ├── bazel │ ├── BUILD.bazel │ ├── common │ │ ├── BUILD.bazel │ │ └── empty.bzl │ ├── http_jar.bzl │ ├── repositories_util.bzl │ └── rules │ │ ├── BUILD.bazel │ │ ├── bazel_java_binary.bzl │ │ ├── bazel_java_binary_nonexec.bzl │ │ ├── bazel_java_binary_wrapper.bzl │ │ ├── bazel_java_import.bzl │ │ ├── bazel_java_library.bzl │ │ ├── bazel_java_plugin.bzl │ │ ├── bazel_java_test.bzl │ │ └── java_stub_template.txt ├── common │ ├── BUILD │ ├── java_common.bzl │ ├── java_info.bzl │ ├── java_plugin_info.bzl │ ├── java_semantics.bzl │ ├── proguard_spec_info.bzl │ └── rules │ │ ├── BUILD │ │ ├── android_lint.bzl │ │ ├── basic_java_library.bzl │ │ ├── impl │ │ ├── BUILD │ │ ├── basic_java_library_impl.bzl │ │ ├── bazel_java_import_impl.bzl │ │ ├── bazel_java_library_impl.bzl │ │ ├── compile_action.bzl │ │ ├── import_deps_check.bzl │ │ ├── java_binary_deploy_jar.bzl │ │ ├── java_binary_impl.bzl │ │ ├── java_helper.bzl │ │ └── proguard_validation.bzl │ │ ├── java_binary.bzl │ │ ├── java_binary_wrapper.bzl │ │ ├── java_import.bzl │ │ ├── java_library.bzl │ │ ├── java_package_configuration.bzl │ │ ├── java_plugin.bzl │ │ ├── java_runtime.bzl │ │ ├── java_toolchain.bzl │ │ └── rule_util.bzl ├── defs.bzl ├── docs │ ├── BUILD.bazel │ ├── rule.vm │ ├── rules.bzl │ └── rules.md ├── extensions.bzl ├── http_jar.bzl ├── java_binary.bzl ├── java_import.bzl ├── java_library.bzl ├── java_plugin.bzl ├── java_single_jar.bzl ├── java_test.bzl ├── java_utils.bzl ├── private │ ├── BUILD │ ├── android_support.bzl │ ├── boot_class_path_info.bzl │ ├── java_common.bzl │ ├── java_common_internal.bzl │ ├── java_info.bzl │ ├── legacy_native.bzl │ ├── message_bundle_info.bzl │ ├── native.bzl │ └── proto_support.bzl ├── proto │ └── BUILD ├── repositories.bzl ├── rules_java_deps.bzl ├── runfiles │ ├── BUILD │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── google │ │ └── devtools │ │ └── build │ │ └── runfiles │ │ ├── AutoBazelRepository.java │ │ ├── AutoBazelRepositoryProcessor.java │ │ ├── BUILD │ │ ├── Runfiles.java │ │ └── Util.java ├── testutil.bzl └── toolchains │ ├── BUILD │ ├── java_package_configuration.bzl │ ├── java_runtime.bzl │ └── java_toolchain.bzl ├── renovate.json ├── test ├── BUILD.bazel ├── check_release_notes_test.sh ├── check_remote_java_tools_configs.sh ├── check_remote_jdk_configs.sh ├── check_remotejdk_configs_match.bzl ├── java │ ├── BUILD │ ├── bazel │ │ ├── BUILD.bazel │ │ └── rules │ │ │ ├── BUILD.bazel │ │ │ └── java_binary_tests.bzl │ ├── common │ │ ├── BUILD │ │ ├── java_common_tests.bzl │ │ ├── java_info_tests.bzl │ │ ├── java_plugin_info_tests.bzl │ │ └── rules │ │ │ ├── BUILD │ │ │ ├── java_binary_tests.bzl │ │ │ ├── java_import_tests.bzl │ │ │ ├── java_library_tests.bzl │ │ │ ├── java_plugin_tests.bzl │ │ │ ├── java_test_tests.bzl │ │ │ └── merge_attrs_tests.bzl │ ├── private │ │ ├── BUILD │ │ └── android_support_tests.bzl │ ├── runfiles │ │ └── src │ │ │ └── test │ │ │ └── java │ │ │ └── com │ │ │ └── google │ │ │ └── devtools │ │ │ └── build │ │ │ └── runfiles │ │ │ ├── BUILD.bazel │ │ │ ├── RunfilesTest.java │ │ │ └── UtilTest.java │ ├── testutil │ │ ├── BUILD │ │ ├── artifact_closure.bzl │ │ ├── cc_info_subject.bzl │ │ ├── helper.bzl │ │ ├── java_info_subject.bzl │ │ ├── java_runtime_info_subject.bzl │ │ ├── java_toolchain_info_subject.bzl │ │ ├── javac_action_subject.bzl │ │ ├── javac_action_subject_tests.bzl │ │ └── rules │ │ │ ├── bad_java_info_rules.bzl │ │ │ ├── custom_java_info_rule.bzl │ │ │ ├── custom_library.bzl │ │ │ ├── custom_library_extended_compile_jdeps.bzl │ │ │ ├── custom_library_with_additional_inputs.bzl │ │ │ ├── custom_library_with_bootclasspath.bzl │ │ │ ├── custom_library_with_custom_output_source_jar.bzl │ │ │ ├── custom_library_with_exports.bzl │ │ │ ├── custom_library_with_named_outputs.bzl │ │ │ ├── custom_library_with_sourcepaths.bzl │ │ │ ├── custom_library_with_strict_deps.bzl │ │ │ ├── custom_library_with_wrong_plugins_type.bzl │ │ │ ├── custom_plugin.bzl │ │ │ ├── forward_java_info.bzl │ │ │ ├── forward_java_runtime_info.bzl │ │ │ └── wrap_java_info.bzl │ └── toolchains │ │ ├── BUILD │ │ ├── java_runtime_tests.bzl │ │ └── java_toolchain_tests.bzl ├── repo │ ├── .bazelrc │ ├── BUILD.bazel │ ├── MODULE.bazel │ ├── WORKSPACE │ ├── WORKSPACE.bzlmod │ ├── setup.bat │ ├── setup.sh │ └── src │ │ ├── Main.java │ │ ├── MakeVarTest.sh │ │ ├── MyTest.java │ │ └── data.txt ├── repositories.bzl ├── testdata │ ├── BUILD.bazel │ └── MyLib.java └── toolchains │ ├── BUILD.bazel │ └── bootclasspath_tests.bzl └── toolchains ├── BUILD ├── DumpPlatformClassPath.java ├── bootclasspath.bzl ├── default_java_toolchain.bzl ├── fail_rule.bzl ├── java_toolchain_alias.bzl ├── jdk_build_file.bzl ├── local_java_repository.bzl ├── remote_java_repository.bzl ├── toolchain_utils.bzl └── utf8_environment.bzl /.bazel_checkout/__README: -------------------------------------------------------------------------------- 1 | This directory exists just so we can clone Bazel sources and run tests on presubmit 2 | 3 | At some point, we should migrate the tests we care about, out of Bazel and into 4 | rules_java. -------------------------------------------------------------------------------- /.bazel_checkout/setup.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | set -x 4 | 5 | FAKE_BCR_ROOT=$(mktemp -d --tmpdir fake-bcr.XXX) 6 | FAKE_RULES_JAVA_ROOT=${FAKE_BCR_ROOT}/modules/rules_java 7 | FAKE_MODULE_VERSION=9999 8 | FAKE_MODULE_ROOT=${FAKE_RULES_JAVA_ROOT}/${FAKE_MODULE_VERSION} 9 | FAKE_ARCHIVE=${FAKE_MODULE_ROOT}/rules_java.tar.gz 10 | mkdir -p ${FAKE_MODULE_ROOT} 11 | 12 | # relying on the line number is not great, but :shrugs: 13 | sed -e "3 c version = \"${FAKE_MODULE_VERSION}\"," ../MODULE.bazel > ${FAKE_MODULE_ROOT}/MODULE.bazel 14 | 15 | tar zcf ${FAKE_ARCHIVE} ../ 16 | RULES_JAVA_INTEGRITY_SHA256=`cat ${FAKE_ARCHIVE} | openssl dgst -sha256 -binary | base64` 17 | cat << EOF > ${FAKE_MODULE_ROOT}/source.json 18 | { 19 | "integrity": "sha256-${RULES_JAVA_INTEGRITY_SHA256}", 20 | "strip_prefix": "", 21 | "url": "file://${FAKE_ARCHIVE}" 22 | } 23 | EOF 24 | 25 | # fetch and setup bazel sources 26 | git init 27 | git remote add origin https://github.com/bazelbuild/bazel.git 28 | git pull origin master 29 | sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' \ 30 | -e 's/^# android_ndk_repository/android_ndk_repository/' \ 31 | WORKSPACE.bzlmod 32 | rm -f WORKSPACE.bzlmod.bak 33 | rm -rf $HOME/bazeltest 34 | mkdir $HOME/bazeltest 35 | 36 | echo "common --registry=https://bcr.bazel.build" >> .bazelrc 37 | echo "common --registry=file://${FAKE_BCR_ROOT}" >> .bazelrc 38 | echo "add_to_bazelrc \"common --registry=https://bcr.bazel.build\"" >> src/test/shell/testenv.sh.tmpl 39 | echo "add_to_bazelrc \"common --registry=file://${FAKE_BCR_ROOT}\"" >> src/test/shell/testenv.sh.tmpl 40 | 41 | SED_CMD="s/bazel_dep(name = \"rules_java\".*/bazel_dep(name = \"rules_java\", version = \"${FAKE_MODULE_VERSION}\")/" 42 | sed -i "${SED_CMD}" MODULE.bazel 43 | sed -i "${SED_CMD}" src/MODULE.tools 44 | 45 | BAZEL_QUIET_MODE_ARGS="--ui_event_filters=error,fail" 46 | 47 | bazel run ${BAZEL_QUIET_MODE_ARGS} //src/test/tools/bzlmod:update_default_lock_file -- \ 48 | --registry="https://bcr.bazel.build" --registry="file://${FAKE_BCR_ROOT}" ${BAZEL_QUIET_MODE_ARGS} 49 | bazel mod deps --lockfile_mode=update 50 | # populate repo cache so tests don't need to access network 51 | bazel fetch --config=ci-linux --all ${BAZEL_QUIET_MODE_ARGS} 52 | -------------------------------------------------------------------------------- /.bazelci/presubmit.yml: -------------------------------------------------------------------------------- 1 | --- 2 | build_targets: &build_targets 3 | - "//..." 4 | # can't build some analysis tests on older Bazel versions 5 | - "-//test/java/..." 6 | # build java_tools from source 7 | - "@remote_java_tools//:ijar_cc_binary" 8 | - "@remote_java_tools//:one_version_cc_bin" 9 | - "@remote_java_tools//:proguard" 10 | - "@remote_java_tools//:singlejar_cc_bin" 11 | # can't build @remote_java_tools_X repos for other platforms 12 | - "-//toolchains/..." 13 | # TODO: re-enable docs after moving them out of https://bazel.build/reference/be/java 14 | - "-//java/docs/..." 15 | - "-//test:docs_up_to_date_test" 16 | 17 | build_targets_bazel6: &build_targets_bazel6 18 | - "//:all" 19 | # build java_tools from source 20 | - "@remote_java_tools//:ijar_cc_binary" 21 | - "@remote_java_tools//:one_version_cc_bin" 22 | - "@remote_java_tools//:proguard" 23 | - "@remote_java_tools//:singlejar_cc_bin" 24 | - "//examples/..." 25 | 26 | build_targets_integration: &build_targets_integration 27 | - "//..." 28 | - "//:bin_deploy.jar" 29 | 30 | test_targets: &test_targets 31 | - "//test/..." 32 | # TODO: re-enable docs after moving them out of https://bazel.build/reference/be/java 33 | - "-//test:docs_up_to_date_test" 34 | 35 | test_targets_bazel6: &test_targets_bazel6 36 | - "//test/java/..." 37 | - "-//test/java/private/..." 38 | 39 | test_target_integration: &test_target_integration 40 | - "//:MyTest" 41 | 42 | flags_workspace_integration: &flags_workspace_integration 43 | - "--noenable_bzlmod" 44 | - "--enable_workspace" 45 | # TODO(hvd): remove after Bazel 8.3.0 46 | - "--repositories_without_autoloads=bazel_features_version,bazel_features_globals" 47 | 48 | buildifier: latest 49 | 50 | matrix: 51 | all_platforms: ["ubuntu2004", "macos", "macos_arm64", "windows"] 52 | bazel: ["7.6.1", "8.2.1", "last_green"] # Bazel 6 tested separately, needs different flags 53 | modern_bazel: ["last_green"] # Fully supported Bazel versions 54 | 55 | tasks: 56 | # Bazel 9+ 57 | build_and_test: 58 | name: "Bazel {modern_bazel}" 59 | bazel: ${{ modern_bazel }} 60 | platform: ${{ all_platforms }} 61 | build_targets: *build_targets 62 | test_targets: *test_targets 63 | # Bazel 8.x 64 | build_and_test_bazel8: 65 | name: "Bazel 8.2.1" 66 | bazel: "8.2.1" 67 | platform: ${{ all_platforms }} 68 | build_targets: *build_targets 69 | test_targets: *test_targets 70 | test_flags: 71 | - "--test_tag_filters=-min_bazel_9" 72 | # Bazel 7.x 73 | build_and_test_bazel7: 74 | name: "Bazel 7.6.1" 75 | bazel: "7.6.1" 76 | platform: ${{ all_platforms }} 77 | build_targets: *build_targets 78 | test_targets: *test_targets 79 | test_flags: 80 | - "--test_tag_filters=-min_bazel_8,-min_bazel_9" 81 | # Bazel 6.x 82 | build_and_test_bazel6: 83 | name: "Bazel 6.5.0" 84 | bazel: 6.5.0 85 | platform: ${{ all_platforms }} 86 | build_targets: *build_targets_bazel6 87 | test_targets: *test_targets_bazel6 88 | test_flags: 89 | - "--test_tag_filters=-min_bazel_7,-min_bazel_8,-min_bazel_9" 90 | ubuntu2004_integration_bazel6: 91 | name: "Integration w/ Bazel 6.5.0" 92 | bazel: 6.5.0 93 | platform: ${{ all_platforms }} 94 | working_directory: "test/repo" 95 | shell_commands: 96 | - sh setup.sh 97 | batch_commands: 98 | - setup.bat 99 | build_targets: *build_targets_integration 100 | test_targets: *test_target_integration 101 | 102 | # Integration tests 103 | integration_build_and_test: 104 | name: "Integration w/ Bazel {bazel}" 105 | bazel: ${{ bazel }} 106 | platform: ${{ all_platforms }} 107 | working_directory: "test/repo" 108 | shell_commands: 109 | - sh setup.sh 110 | batch_commands: 111 | - setup.bat 112 | build_targets: *build_targets_integration 113 | test_targets: *test_target_integration 114 | integration_build_and_test_workspace: 115 | name: "Integration (WORKSPACE) w/ Bazel {bazel}" 116 | bazel: ${{ bazel }} 117 | platform: ${{ all_platforms }} 118 | working_directory: "test/repo" 119 | shell_commands: 120 | - sh setup.sh 121 | batch_commands: 122 | - setup.bat 123 | build_targets: *build_targets_integration 124 | build_flags: *flags_workspace_integration 125 | test_targets: *test_target_integration 126 | test_flags: *flags_workspace_integration 127 | # Linux-only tests 128 | linux_only_tests: 129 | name: "Extra tests w/ Bazel {bazel}" 130 | bazel: ${{ bazel }} 131 | platform: "ubuntu2004" 132 | shell_commands: 133 | - "git init" 134 | - "git config user.name 'fake-user-for-testing'" 135 | - "git commit --allow-empty -m 'Fake init commit'" 136 | - "git tag -a 'fake-tag-for-testing' -m 'ignore'" 137 | - "git commit --allow-empty -m 'Fake commit message for testing'" 138 | test_targets: 139 | - "//test:check_remote_jdk_configs_test" 140 | - "//test:check_release_notes_test" 141 | -------------------------------------------------------------------------------- /.bazelignore: -------------------------------------------------------------------------------- 1 | test/repo 2 | -------------------------------------------------------------------------------- /.bazelrc: -------------------------------------------------------------------------------- 1 | common --incompatible_disallow_empty_glob 2 | 3 | # Use hermetic JDKs for testing and ensure compatibliity with Java 8. 4 | common --java_language_version=8 5 | common --java_runtime_version=remotejdk_8 6 | common --tool_java_language_version=8 7 | common --tool_java_runtime_version=remotejdk_8 8 | 9 | # Hide Java 8 deprecation warnings. 10 | common --javacopt=-Xlint:-options 11 | 12 | # Enable modern C++ features, for compiling java_tools from source 13 | build --cxxopt=-std=c++17 14 | build --host_cxxopt=-std=c++17 15 | 16 | # Some tests relies on dynamic libs that are not interface libs 17 | # 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 18 | # we can't use a transition because toolchain deps exceed the default --analysis_testing_deps_limit. 19 | test --nointerface_shared_objects -------------------------------------------------------------------------------- /.bcr/metadata.template.json: -------------------------------------------------------------------------------- 1 | { 2 | "homepage": "https://github.com/bazelbuild/rules_java", 3 | "maintainers": [ 4 | { 5 | "email": "hvd@google.com", 6 | "github": "hvadehra", 7 | "name": "Hemanshu Vadehra" 8 | } 9 | ], 10 | "versions": [], 11 | "yanked_versions": {}, 12 | "repository": [ 13 | "github:bazelbuild/rules_java" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /.bcr/presubmit.yml: -------------------------------------------------------------------------------- 1 | matrix: 2 | platform: 3 | - rockylinux8 4 | - debian10 5 | - macos 6 | - ubuntu2004 7 | - windows 8 | bazel: 9 | - 7.x 10 | - 8.x 11 | tasks: 12 | verify_build_targets: 13 | name: "Verify build targets w/ Bazel {bazel}" 14 | platform: ${{ platform }} 15 | bazel: ${{ bazel }} 16 | build_targets: 17 | - "@rules_java//java/..." 18 | -------------------------------------------------------------------------------- /.bcr/source.template.json: -------------------------------------------------------------------------------- 1 | { 2 | "integrity": "", 3 | "strip_prefix": "", 4 | "url": "https://github.com/{OWNER}/{REPO}/releases/download/{TAG}/rules_java-{TAG}.tar.gz" 5 | } 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/release.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 'Release tracker' 3 | about: Use this template to request for a new rules_java release 4 | title: 'Release: rules_java X.Y.Z' 5 | labels: ['release','P1'] 6 | assignees: 7 | - iancha1992 8 | - sgowroji 9 | --- 10 | 11 | **Link to relevant issue and/or commit:** 12 | 13 | **Other details:** 14 | 15 | 16 | 17 | 18 | cc @bazelbuild/triage 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore backup files. 2 | *~ 3 | # Ignore Vim swap files. 4 | .*.swp 5 | # Ignore files generated by IDEs. 6 | /.classpath 7 | /.factorypath 8 | /.idea/ 9 | /.ijwb/ 10 | /.project 11 | /.settings 12 | # Ignore all bazel-* symlinks. There is no full list since this can change 13 | # based on the name of the directory bazel is cloned into. 14 | /bazel-* 15 | # Ignore outputs generated during Bazel bootstrapping. 16 | /output/ 17 | # Ignore jekyll build output. 18 | /production 19 | /.sass-cache 20 | # Ignore MODULE.bazel.lock as this is a library project. 21 | MODULE.bazel.lock 22 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | # This the official list of Bazel authors for copyright purposes. 2 | # This file is distinct from the CONTRIBUTORS files. 3 | # See the latter for an explanation. 4 | 5 | # Names should be added to this file as: 6 | # Name or Organization 7 | # The email address is not required for organizations. 8 | 9 | Google Inc. 10 | -------------------------------------------------------------------------------- /BUILD: -------------------------------------------------------------------------------- 1 | load("@rules_license//rules:license.bzl", "license") 2 | 3 | package(default_applicable_licenses = ["@rules_java//:license"]) 4 | 5 | licenses(["notice"]) 6 | 7 | exports_files([ 8 | "LICENSE", 9 | "WORKSPACE", 10 | ]) 11 | 12 | filegroup( 13 | name = "distribution", 14 | srcs = [ 15 | "AUTHORS", 16 | "BUILD", 17 | "LICENSE", 18 | "MODULE.bazel", 19 | "WORKSPACE", 20 | "//java:srcs", 21 | "//toolchains:srcs", 22 | ], 23 | visibility = ["//visibility:public"], 24 | ) 25 | 26 | license( 27 | name = "license", 28 | package_name = "rules_java", 29 | ) 30 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Each line is a file pattern followed by one or more owners. 2 | 3 | # Order is important; the last matching pattern takes the most precedence. 4 | 5 | # When someone opens a pull request that only modifies files in directory, only 6 | # component owners and not the global owner(s) will be requested for a review. 7 | 8 | # Syntax: https://help.github.com/articles/about-codeowners/ 9 | 10 | # Use individual usernames instead of teams (like @bazelbuild/android) for 11 | # auto-assignment to work, unless everyone in the team has write permissions to the repository. 12 | # See https://github.community/t5/How-to-use-Git-and-GitHub/CODEOWNERS-works-with-users-but-not-teams/td-p/4986 13 | 14 | # Component owners 15 | # ---------------- 16 | 17 | * @comius @bazelbuild/java-team 18 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution; 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows 28 | [Google's Open Source Community Guidelines](https://opensource.google.com/conduct/). 29 | -------------------------------------------------------------------------------- /MODULE.bazel: -------------------------------------------------------------------------------- 1 | module( 2 | name = "rules_java", 3 | version = "8.12.0", 4 | bazel_compatibility = [">=6.4.0"], 5 | compatibility_level = 1, 6 | ) 7 | 8 | bazel_dep(name = "platforms", version = "0.0.11") 9 | bazel_dep(name = "rules_cc", version = "0.0.15") 10 | bazel_dep(name = "bazel_features", version = "1.30.0") 11 | bazel_dep(name = "bazel_skylib", version = "1.6.1") 12 | bazel_dep(name = "protobuf", version = "27.0", repo_name = "com_google_protobuf") 13 | bazel_dep(name = "zlib", version = "1.3.1.bcr.5") 14 | 15 | # Required by @remote_java_tools, which is loaded via module extension. 16 | bazel_dep(name = "rules_license", version = "0.0.3") 17 | bazel_dep(name = "abseil-cpp", version = "20230802.1", repo_name = "com_google_absl") 18 | 19 | register_toolchains("//toolchains:all") 20 | 21 | toolchains = use_extension("//java:extensions.bzl", "toolchains") 22 | 23 | # Declare remote java tools repos 24 | use_repo(toolchains, "remote_java_tools") 25 | use_repo(toolchains, "remote_java_tools_linux") 26 | use_repo(toolchains, "remote_java_tools_windows") 27 | use_repo(toolchains, "remote_java_tools_darwin_x86_64") 28 | use_repo(toolchains, "remote_java_tools_darwin_arm64") 29 | 30 | # Declare local jdk repo 31 | use_repo(toolchains, "local_jdk") 32 | 33 | register_toolchains( 34 | "@local_jdk//:runtime_toolchain_definition", 35 | "@local_jdk//:bootstrap_runtime_toolchain_definition", 36 | ) 37 | 38 | # Declare all remote jdk toolchain config repos 39 | JDKS = { 40 | # Must match JDK repos defined in remote_jdk8_repos() 41 | "8": [ 42 | "linux", 43 | "linux_aarch64", 44 | "linux_s390x", 45 | "macos", 46 | "macos_aarch64", 47 | "windows", 48 | ], 49 | # Must match JDK repos defined in remote_jdk11_repos() 50 | "11": [ 51 | "linux", 52 | "linux_aarch64", 53 | "linux_ppc64le", 54 | "linux_s390x", 55 | "macos", 56 | "macos_aarch64", 57 | "win", 58 | "win_arm64", 59 | ], 60 | # Must match JDK repos defined in remote_jdk17_repos() 61 | "17": [ 62 | "linux", 63 | "linux_aarch64", 64 | "linux_ppc64le", 65 | "linux_s390x", 66 | "macos", 67 | "macos_aarch64", 68 | "win", 69 | "win_arm64", 70 | ], 71 | # Must match JDK repos defined in remote_jdk21_repos() 72 | "21": [ 73 | "linux", 74 | "linux_aarch64", 75 | "linux_ppc64le", 76 | "linux_riscv64", 77 | "linux_s390x", 78 | "macos", 79 | "macos_aarch64", 80 | "win", 81 | "win_arm64", 82 | ], 83 | } 84 | 85 | REMOTE_JDK_REPOS = [(("remote_jdk" if version == "8" else "remotejdk") + version + "_" + platform) for version in JDKS for platform in JDKS[version]] 86 | 87 | [use_repo( 88 | toolchains, 89 | repo + "_toolchain_config_repo", 90 | ) for repo in REMOTE_JDK_REPOS] 91 | 92 | [register_toolchains("@" + name + "_toolchain_config_repo//:all") for name in REMOTE_JDK_REPOS] 93 | 94 | # Compatibility layer 95 | compat = use_extension("//java:rules_java_deps.bzl", "compatibility_proxy") 96 | use_repo(compat, "compatibility_proxy") 97 | 98 | # Dev dependencies 99 | bazel_dep(name = "rules_pkg", version = "0.9.1", dev_dependency = True) 100 | bazel_dep(name = "stardoc", version = "0.7.1", dev_dependency = True) 101 | bazel_dep(name = "rules_shell", version = "0.2.0", dev_dependency = True) 102 | bazel_dep(name = "rules_testing", version = "0.7.0", dev_dependency = True) 103 | archive_override( 104 | module_name = "rules_testing", 105 | integrity = "sha256-0+3pLjeZCqn+K1qS7HNr7HbwMXBjxLvJm+pMSUhDel8=", 106 | strip_prefix = "rules_testing-db007bfee840cebcb6f955b80973ba866de38947", 107 | urls = ["https://github.com/bazelbuild/rules_testing/archive/db007bfee840cebcb6f955b80973ba866de38947.tar.gz"], 108 | ) 109 | 110 | test_repositories = use_extension("//test:repositories.bzl", "test_repositories_ext", dev_dependency = True) 111 | use_repo(test_repositories, "guava", "truth") 112 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rules_java 2 | 3 | * Postsubmit [![Build status](https://badge.buildkite.com/d4f950ef5f481b8ca066624ba06c238fa1446d84a057ddbf89.svg?branch=master)](https://buildkite.com/bazel/rules-java-java) 4 | * Postsubmit + Current Bazel Incompatible Flags [![Build status](https://badge.buildkite.com/ef265d270238c02aff65106a0b861abb9265efacdf4af399c3.svg?branch=master)](https://buildkite.com/bazel/rules-java-plus-bazelisk-migrate) 5 | 6 | Java Rules for Bazel https://bazel.build. 7 | 8 | **Documentation** 9 | 10 | For a quickstart tutorial, see https://bazel.build/start/java 11 | 12 | For slightly more advanced usage, like setting up toolchains 13 | or writing your own java-like rules, 14 | see https://bazel.build/docs/bazel-and-java 15 | 16 | 17 | ***Core Java rules*** 18 | 19 | Add a load like: 20 | ```build 21 | load("@rules_java//java:java_library.bzl", "java_library") 22 | ``` 23 | to your `BUILD` / `BUILD.bazel` / bzl` files 24 | 25 | For detailed docs on the core rules, see https://bazel.build/reference/be/java 26 | -------------------------------------------------------------------------------- /WORKSPACE: -------------------------------------------------------------------------------- 1 | workspace(name = "rules_java") 2 | 3 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") 4 | 5 | http_archive( 6 | name = "bazel_skylib", 7 | sha256 = "bc283cdfcd526a52c3201279cda4bc298652efa898b10b4db0837dc51652756f", 8 | urls = [ 9 | "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", 10 | "https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz", 11 | ], 12 | ) 13 | 14 | load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace") 15 | 16 | bazel_skylib_workspace() 17 | 18 | http_archive( 19 | name = "rules_pkg", 20 | sha256 = "8f9ee2dc10c1ae514ee599a8b42ed99fa262b757058f65ad3c384289ff70c4b8", 21 | urls = [ 22 | "https://mirror.bazel.build/github.com/bazelbuild/rules_pkg/releases/download/0.9.1/rules_pkg-0.9.1.tar.gz", 23 | "https://github.com/bazelbuild/rules_pkg/releases/download/0.9.1/rules_pkg-0.9.1.tar.gz", 24 | ], 25 | ) 26 | 27 | load("@rules_pkg//:deps.bzl", "rules_pkg_dependencies") 28 | 29 | rules_pkg_dependencies() 30 | 31 | http_archive( 32 | name = "stardoc", 33 | sha256 = "62bd2e60216b7a6fec3ac79341aa201e0956477e7c8f6ccc286f279ad1d96432", 34 | urls = [ 35 | "https://mirror.bazel.build/github.com/bazelbuild/stardoc/releases/download/0.6.2/stardoc-0.6.2.tar.gz", 36 | "https://github.com/bazelbuild/stardoc/releases/download/0.6.2/stardoc-0.6.2.tar.gz", 37 | ], 38 | ) 39 | 40 | load("//java:rules_java_deps.bzl", "rules_java_dependencies") 41 | 42 | rules_java_dependencies() 43 | 44 | load("@bazel_features//:deps.bzl", "bazel_features_deps") 45 | 46 | bazel_features_deps() 47 | 48 | load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_bazel_features") # buildifier: disable=bzl-visibility 49 | 50 | proto_bazel_features(name = "proto_bazel_features") 51 | 52 | load("//java:repositories.bzl", "rules_java_toolchains") 53 | 54 | rules_java_toolchains() 55 | 56 | load("@stardoc//:setup.bzl", "stardoc_repositories") 57 | 58 | stardoc_repositories() 59 | 60 | http_archive( 61 | name = "rules_testing", 62 | sha256 = "d3ede92e37990aa9fe2b5a92ec736bec76f0317063c4bbc99bea4c4948437a5f", 63 | strip_prefix = "rules_testing-db007bfee840cebcb6f955b80973ba866de38947", 64 | urls = ["https://github.com/bazelbuild/rules_testing/archive/db007bfee840cebcb6f955b80973ba866de38947.tar.gz"], 65 | ) 66 | 67 | load("//test:repositories.bzl", "test_repositories") 68 | 69 | test_repositories() 70 | -------------------------------------------------------------------------------- /WORKSPACE.bzlmod: -------------------------------------------------------------------------------- 1 | # A completely empty WORKSPACE file to replace the original WORKSPACE content when enabling Bzlmod. 2 | # No WORKSPACE prefix or suffix are added for this file. 3 | -------------------------------------------------------------------------------- /distro/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load("@rules_pkg//pkg:tar.bzl", "pkg_tar") 2 | load(":relnotes.bzl", "print_rel_notes") 3 | 4 | package( 5 | default_applicable_licenses = ["@rules_java//:license"], 6 | default_visibility = ["//visibility:private"], 7 | ) 8 | 9 | # Build the artifact to put on the github release page. 10 | pkg_tar( 11 | name = "rules_java-%s" % module_version(), 12 | srcs = ["//:distribution"], 13 | extension = "tar.gz", 14 | # It is all source code, so make it read-only. 15 | mode = "0444", 16 | # Make it owned by root so it does not have the uid of the CI robot. 17 | owner = "0.0", 18 | package_dir = ".", 19 | strip_prefix = ".", 20 | ) 21 | 22 | print_rel_notes( 23 | name = "relnotes", 24 | archive = ":rules_java-%s" % module_version(), 25 | version = module_version(), 26 | ) 27 | -------------------------------------------------------------------------------- /distro/README.md: -------------------------------------------------------------------------------- 1 | # Releasing rules_java 2 | 3 | 1. Update version in [MODULE.bazel](/MODULE.bazel) and merge it 4 | 2. Build the release running `bazel build //distro:rules_java-{version}` 5 | 3. Prepare release notes running `bazel build //distro:relnotes` 6 | 4. Create a new release on GitHub 7 | 5. Copy/paste the produced `relnotes.txt` into the notes. Adjust as needed. 8 | 6. Upload the produced tar.gz file as an artifact. 9 | 10 | ------ 11 | 12 | **Note:** Steps 2-6 have been automated. Trigger a new build of the [rules_java release pipeline](https://buildkite.com/bazel-trusted/rules-java-release/). Set the message to "rules_java [version]" (or anything else), and leave the commit and branch fields as is. 13 | 14 | A new release will be created [here](https://github.com/bazelbuild/rules_java/releases) -- edit the description as needed. A PR will be submitted against the [bazel-central-registry](https://github.com/bazelbuild/bazel-central-registry) repo. 15 | 16 | rules_java 6.5.0 example: 17 | 18 | - Build: https://buildkite.com/bazel-trusted/rules-java-release/builds/1 19 | - Release: https://github.com/bazelbuild/rules_java/releases/tag/6.5.0 20 | - BCR PR: bazelbuild/bazel-central-registry#818 21 | 22 | -------------------------------------------------------------------------------- /distro/relnotes.bzl: -------------------------------------------------------------------------------- 1 | """Release notes generator""" 2 | 3 | def print_rel_notes(*, name, version, archive): 4 | native.genrule( 5 | name = name, 6 | outs = [name + ".txt"], 7 | cmd = """ 8 | last_rel=$$(git describe --tags --abbrev=0) 9 | changelog=$$(/usr/bin/git log tags/$$last_rel..HEAD --format=oneline --invert-grep --grep 'ignore-relnotes' --) 10 | sha=$$(/usr/bin/sha256sum $(SRCS) | cut -d ' ' -f1) 11 | cat > $@ < $@ 28 | while read -r config; do 29 | TMP_FILE=$$(mktemp -q /tmp/remotejdk.XXXXXX) 30 | IFS=\\| read -r name version urls strip_prefix target_compatible_with primary_url <<< "$$config" 31 | echo "fetching: $$primary_url to $$TMP_FILE" > /dev/stderr 32 | curl --silent --fail -o $$TMP_FILE -L "$$primary_url" > /dev/stderr 33 | sha256=`sha256sum $$TMP_FILE | cut -d' ' -f1` 34 | echo "struct(" 35 | echo " name = \\"$$name\\"," 36 | echo " target_compatible_with = $$target_compatible_with," 37 | echo " sha256 = \\"$$sha256\\"," 38 | echo " strip_prefix = \\"$$strip_prefix\\"," 39 | echo " urls = $$urls," 40 | echo " version = \\"$$version\\"," 41 | echo ")," 42 | done <<< '{configs}' >> $@ 43 | """.format(configs = "\n".join([ 44 | "|".join([ 45 | config.name, 46 | config.version, 47 | json.encode(config.urls), 48 | config.strip_prefix, 49 | json.encode(config.target_compatible_with), 50 | config.urls[0], 51 | ]) 52 | for config in FLAT_CONFIGS 53 | ])), 54 | tags = [ 55 | "local", 56 | "manual", 57 | ], 58 | visibility = ["//visibility:private"], 59 | ) 60 | 61 | bzl_library( 62 | name = "http_jar_bzl", 63 | srcs = ["http_jar.bzl"], 64 | visibility = ["@compatibility_proxy//:__pkg__"], 65 | deps = ["@bazel_tools//tools:bzl_srcs"], 66 | ) 67 | 68 | filegroup( 69 | name = "for_bazel_tests", 70 | testonly = 1, 71 | visibility = ["//java:__pkg__"], 72 | ) 73 | 74 | filegroup( 75 | name = "srcs", 76 | srcs = glob(["**"]), 77 | visibility = ["//java:__pkg__"], 78 | ) 79 | -------------------------------------------------------------------------------- /java/bazel/common/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load("@bazel_skylib//:bzl_library.bzl", "bzl_library") 2 | 3 | package(default_applicable_licenses = ["@rules_java//:license"]) 4 | 5 | bzl_library( 6 | name = "common", 7 | srcs = glob(["*.bzl"]), 8 | visibility = ["//java:__pkg__"], 9 | ) 10 | 11 | filegroup( 12 | name = "srcs", 13 | srcs = glob(["**"]), 14 | visibility = ["//java:__pkg__"], 15 | ) 16 | -------------------------------------------------------------------------------- /java/bazel/common/empty.bzl: -------------------------------------------------------------------------------- 1 | """Placeholder for glob""" 2 | -------------------------------------------------------------------------------- /java/bazel/rules/BUILD.bazel: -------------------------------------------------------------------------------- 1 | # Copyright 2024 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | load("@bazel_skylib//:bzl_library.bzl", "bzl_library") 15 | 16 | package(default_applicable_licenses = ["@rules_java//:license"]) 17 | 18 | filegroup( 19 | name = "srcs", 20 | srcs = glob(["**"]), 21 | visibility = ["//java:__pkg__"], 22 | ) 23 | 24 | bzl_library( 25 | name = "rules", 26 | srcs = glob(["*.bzl"]), 27 | visibility = ["//visibility:public"], # for Bazel docgen 28 | deps = [ 29 | "//java/common:semantics_bzl", 30 | "//java/common/rules:core_rules", 31 | "//java/common/rules/impl", 32 | "//java/private:internals", 33 | "@bazel_skylib//lib:paths", 34 | "@rules_cc//cc:find_cc_toolchain_bzl", 35 | "@rules_cc//cc/common", 36 | ], 37 | ) 38 | 39 | filegroup( 40 | name = "for_bazel_tests", 41 | testonly = 1, 42 | srcs = [ 43 | "BUILD.bazel", 44 | ":java_stub_template.txt", 45 | ":rules", 46 | ], 47 | visibility = ["//java:__pkg__"], 48 | ) 49 | 50 | # TODO: remove this in the next major version (rules_java 9.x / Bazel 9.x) 51 | exports_files( 52 | ["java_stub_template.txt"], 53 | visibility = ["@bazel_tools//tools/java:__pkg__"], 54 | ) 55 | -------------------------------------------------------------------------------- /java/bazel/rules/bazel_java_binary_nonexec.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2022 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Defines a java_binary rule class that is non-executable. 16 | 17 | There are two physical rule classes for java_binary and we want both of them 18 | to have a name string of "java_binary" because various tooling expects that. 19 | """ 20 | 21 | load(":bazel_java_binary.bzl", "make_java_binary") 22 | 23 | visibility("private") 24 | 25 | java_binary = make_java_binary(executable = False) 26 | -------------------------------------------------------------------------------- /java/bazel/rules/bazel_java_binary_wrapper.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2022 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Macro encapsulating the java_binary implementation 16 | 17 | This is needed since the `executable` nature of the target must be computed from 18 | the supplied value of the `create_executable` attribute. 19 | """ 20 | 21 | load("//java/common:java_semantics.bzl", "semantics") 22 | load( 23 | "//java/common/rules:java_binary_wrapper.bzl", 24 | "register_java_binary_rules", 25 | "register_legacy_java_binary_rules", 26 | ) 27 | load(":bazel_java_binary.bzl", java_bin_exec = "java_binary") 28 | load(":bazel_java_binary_nonexec.bzl", java_bin_nonexec = "java_binary") 29 | 30 | # copybara: default visibility 31 | 32 | def java_binary(**kwargs): 33 | if semantics.INCOMPATIBLE_DISABLE_NON_EXECUTABLE_JAVA_BINARY: 34 | register_java_binary_rules( 35 | java_bin_exec, 36 | **kwargs 37 | ) 38 | else: 39 | register_legacy_java_binary_rules( 40 | java_bin_exec, 41 | java_bin_nonexec, 42 | **kwargs 43 | ) 44 | -------------------------------------------------------------------------------- /java/bazel/rules/bazel_java_import.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Definition of java_import rule. 17 | """ 18 | 19 | load("//java/common:java_semantics.bzl", "semantics") 20 | load("//java/common/rules:java_import.bzl", "JAVA_IMPORT_ATTRS") 21 | load("//java/common/rules/impl:bazel_java_import_impl.bzl", "bazel_java_import_rule") 22 | load("//java/private:java_info.bzl", "JavaInfo") 23 | 24 | def _proxy(ctx): 25 | return bazel_java_import_rule( 26 | ctx, 27 | ctx.attr.jars, 28 | ctx.file.srcjar, 29 | ctx.attr.deps, 30 | ctx.attr.runtime_deps, 31 | ctx.attr.exports, 32 | ctx.attr.neverlink, 33 | ctx.files.proguard_specs, 34 | ctx.attr.add_exports, 35 | ctx.attr.add_opens, 36 | ).values() 37 | 38 | java_import = rule( 39 | _proxy, 40 | doc = """ 41 |

42 | This rule allows the use of precompiled .jar files as 43 | libraries for java_library and 44 | java_binary rules. 45 |

46 | 47 |

Examples

48 | 49 |
50 | 
51 |     java_import(
52 |         name = "maven_model",
53 |         jars = [
54 |             "maven_model/maven-aether-provider-3.2.3.jar",
55 |             "maven_model/maven-model-3.2.3.jar",
56 |             "maven_model/maven-model-builder-3.2.3.jar",
57 |         ],
58 |     )
59 | 
60 | 
61 | """, 62 | attrs = JAVA_IMPORT_ATTRS, 63 | provides = [JavaInfo], 64 | fragments = ["java", "cpp"], 65 | toolchains = [semantics.JAVA_TOOLCHAIN], 66 | ) 67 | -------------------------------------------------------------------------------- /java/bazel/rules/bazel_java_library.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Definition of java_library rule. 17 | """ 18 | 19 | load("//java/common:java_semantics.bzl", "semantics") 20 | load("//java/common/rules:android_lint.bzl", "android_lint_subrule") 21 | load("//java/common/rules:java_library.bzl", "JAVA_LIBRARY_ATTRS") 22 | load("//java/common/rules/impl:bazel_java_library_impl.bzl", "bazel_java_library_rule") 23 | load("//java/private:java_info.bzl", "JavaInfo") 24 | 25 | def _proxy(ctx): 26 | return bazel_java_library_rule( 27 | ctx, 28 | ctx.files.srcs, 29 | ctx.attr.deps, 30 | ctx.attr.runtime_deps, 31 | ctx.attr.plugins, 32 | ctx.attr.exports, 33 | ctx.attr.exported_plugins, 34 | ctx.files.resources, 35 | ctx.attr.javacopts, 36 | ctx.attr.neverlink, 37 | ctx.files.proguard_specs, 38 | ctx.attr.add_exports, 39 | ctx.attr.add_opens, 40 | ctx.attr.bootclasspath, 41 | ctx.attr.javabuilder_jvm_flags, 42 | ).values() 43 | 44 | java_library = rule( 45 | _proxy, 46 | doc = """ 47 |

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

48 | 49 |

Implicit outputs

50 |
    51 |
  • libname.jar: A Java archive containing the class files.
  • 52 |
  • libname-src.jar: An archive containing the sources ("source 53 | jar").
  • 54 |
55 | """, 56 | attrs = JAVA_LIBRARY_ATTRS, 57 | provides = [JavaInfo], 58 | outputs = { 59 | "classjar": "lib%{name}.jar", 60 | "sourcejar": "lib%{name}-src.jar", 61 | }, 62 | fragments = ["java", "cpp"], 63 | toolchains = [semantics.JAVA_TOOLCHAIN], 64 | subrules = [android_lint_subrule], 65 | ) 66 | -------------------------------------------------------------------------------- /java/common/BUILD: -------------------------------------------------------------------------------- 1 | load("@bazel_skylib//:bzl_library.bzl", "bzl_library") 2 | 3 | package( 4 | default_applicable_licenses = ["@rules_java//:license"], 5 | default_visibility = ["//visibility:public"], 6 | ) 7 | 8 | licenses(["notice"]) 9 | 10 | filegroup( 11 | name = "srcs", 12 | srcs = glob(["**"]) + [ 13 | "//java/common/rules:srcs", 14 | ], 15 | visibility = ["//java:__pkg__"], 16 | ) 17 | 18 | bzl_library( 19 | name = "common", 20 | srcs = glob( 21 | ["*.bzl"], 22 | exclude = [ 23 | "java_semantics.bzl", 24 | "proguard_spec_info.bzl", 25 | ], 26 | ), 27 | visibility = ["//visibility:public"], 28 | deps = [ 29 | ":proguard_spec_info_bzl", 30 | ":semantics_bzl", 31 | "@compatibility_proxy//:proxy_bzl", 32 | ], 33 | ) 34 | 35 | bzl_library( 36 | name = "semantics_bzl", 37 | srcs = ["java_semantics.bzl"], 38 | visibility = ["//visibility:public"], 39 | deps = [ 40 | "@rules_cc//cc/common", 41 | ], 42 | ) 43 | 44 | bzl_library( 45 | name = "proguard_spec_info_bzl", 46 | srcs = ["proguard_spec_info.bzl"], 47 | visibility = ["//visibility:public"], 48 | ) 49 | 50 | filegroup( 51 | name = "for_bazel_tests", 52 | testonly = 1, 53 | srcs = [ 54 | "BUILD", 55 | ":common", 56 | "//java/common/rules:for_bazel_tests", 57 | ], 58 | visibility = ["//java:__pkg__"], 59 | ) 60 | -------------------------------------------------------------------------------- /java/common/java_common.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2023 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """java_common module""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", _java_common = "java_common") 17 | 18 | java_common = _java_common 19 | -------------------------------------------------------------------------------- /java/common/java_info.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2023 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """JavaInfo provider""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", _JavaInfo = "JavaInfo") 17 | 18 | JavaInfo = _JavaInfo 19 | -------------------------------------------------------------------------------- /java/common/java_plugin_info.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2023 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """JavaPluginInfo provider""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", _JavaPluginInfo = "JavaPluginInfo") 17 | 18 | JavaPluginInfo = _JavaPluginInfo 19 | -------------------------------------------------------------------------------- /java/common/java_semantics.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Bazel Java Semantics""" 15 | 16 | load("@rules_cc//cc/common:cc_helper.bzl", "cc_helper") 17 | 18 | # copybara: default visibility 19 | 20 | def _find_java_toolchain(ctx): 21 | return ctx.toolchains["@bazel_tools//tools/jdk:toolchain_type"].java 22 | 23 | def _find_java_runtime_toolchain(ctx): 24 | return ctx.toolchains["@bazel_tools//tools/jdk:runtime_toolchain_type"].java_runtime 25 | 26 | def _get_default_resource_path(path, segment_extractor): 27 | # Look for src/.../resources to match Maven repository structure. 28 | segments = path.split("/") 29 | for idx in range(0, len(segments) - 2): 30 | if segments[idx] == "src" and segments[idx + 2] == "resources": 31 | return "/".join(segments[idx + 3:]) 32 | java_segments = segment_extractor(path) 33 | return "/".join(java_segments) if java_segments != None else path 34 | 35 | def _compatible_javac_options(*_args): 36 | return depset() 37 | 38 | def _check_java_info_opens_exports(): 39 | pass 40 | 41 | def _minimize_cc_info(cc_info): 42 | return cc_info 43 | 44 | _DOCS = struct( 45 | ATTRS = { 46 | "resources": """ 47 |

48 | If resources are specified, they will be bundled in the jar along with the usual 49 | .class files produced by compilation. The location of the resources inside 50 | of the jar file is determined by the project structure. Bazel first looks for Maven's 51 | standard directory layout, 52 | (a "src" directory followed by a "resources" directory grandchild). If that is not 53 | found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for 54 | example, if a resource is at <workspace root>/x/java/y/java/z, the 55 | path of the resource will be y/java/z. This heuristic cannot be overridden, 56 | however, the resource_strip_prefix attribute can be used to specify a 57 | specific alternative directory for resource files. 58 | """, 59 | "use_testrunner": """ 60 | Use the test runner (by default 61 | com.google.testing.junit.runner.BazelTestRunner) class as the 62 | main entry point for a Java program, and provide the test class 63 | to the test runner as a value of bazel.test_suite 64 | system property. 65 | """, 66 | }, 67 | ) 68 | 69 | def _tokenize_javacopts(opts): 70 | result = [] 71 | for opt_str in opts: 72 | cc_helper.tokenize(result, opt_str) 73 | return result 74 | 75 | semantics = struct( 76 | JAVA_TOOLCHAIN_LABEL = "@bazel_tools//tools/jdk:current_java_toolchain", 77 | JAVA_TOOLCHAIN_TYPE = "@bazel_tools//tools/jdk:toolchain_type", 78 | JAVA_TOOLCHAIN = config_common.toolchain_type("@bazel_tools//tools/jdk:toolchain_type", mandatory = True), 79 | find_java_toolchain = _find_java_toolchain, 80 | JAVA_RUNTIME_TOOLCHAIN_TYPE = "@bazel_tools//tools/jdk:runtime_toolchain_type", 81 | JAVA_RUNTIME_TOOLCHAIN = config_common.toolchain_type("@bazel_tools//tools/jdk:runtime_toolchain_type", mandatory = True), 82 | find_java_runtime_toolchain = _find_java_runtime_toolchain, 83 | JAVA_PLUGINS_FLAG_ALIAS_LABEL = "@bazel_tools//tools/jdk:java_plugins_flag_alias", 84 | EXTRA_SRCS_TYPES = [], 85 | ALLOWED_RULES_IN_DEPS = [ 86 | "cc_binary", # NB: linkshared=1 87 | "cc_library", 88 | "genrule", 89 | "genproto", # TODO(bazel-team): we should filter using providers instead (starlark rule). 90 | "java_import", 91 | "java_library", 92 | "java_proto_library", 93 | "java_lite_proto_library", 94 | "proto_library", 95 | "sh_binary", 96 | "sh_library", 97 | ], 98 | ALLOWED_RULES_IN_DEPS_WITH_WARNING = [], 99 | LINT_PROGRESS_MESSAGE = "Running Android Lint for: %{label}", 100 | JAVA_STUB_TEMPLATE_LABEL = "@rules_java//java/bazel/rules:java_stub_template.txt", # copybara-use-repo-external-label 101 | BUILD_INFO_TRANSLATOR_LABEL = "@bazel_tools//tools/build_defs/build_info:java_build_info", 102 | JAVA_TEST_RUNNER_LABEL = "@bazel_tools//tools/jdk:TestRunner", 103 | IS_BAZEL = True, 104 | get_default_resource_path = _get_default_resource_path, 105 | compatible_javac_options = _compatible_javac_options, 106 | LAUNCHER_FLAG_LABEL = Label("@bazel_tools//tools/jdk:launcher_flag_alias"), 107 | PROGUARD_ALLOWLISTER_LABEL = "@bazel_tools//tools/jdk:proguard_whitelister", 108 | check_java_info_opens_exports = _check_java_info_opens_exports, 109 | DOCS = struct( 110 | for_attribute = lambda name: _DOCS.ATTRS.get(name, ""), 111 | ), 112 | minimize_cc_info = _minimize_cc_info, 113 | tokenize_javacopts = _tokenize_javacopts, 114 | PLATFORMS_ROOT = "@platforms//", 115 | INCOMPATIBLE_DISABLE_NON_EXECUTABLE_JAVA_BINARY = False, # Flip when java_single_jar is feature complete 116 | ) 117 | -------------------------------------------------------------------------------- /java/common/proguard_spec_info.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2023 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """ProguardSpecInfo provider""" 15 | 16 | def _proguard_spec_info_init(specs): 17 | # The constructor supports positional parameter, i.e. ProguardSpecInfo([file]) 18 | return {"specs": specs} 19 | 20 | ProguardSpecInfo, _ = provider( 21 | doc = "Information about proguard specs for Android binaries.", 22 | fields = { 23 | "specs": "A list of proguard specs files", 24 | }, 25 | init = _proguard_spec_info_init, 26 | ) 27 | -------------------------------------------------------------------------------- /java/common/rules/BUILD: -------------------------------------------------------------------------------- 1 | load("@bazel_skylib//:bzl_library.bzl", "bzl_library") 2 | 3 | package( 4 | default_applicable_licenses = ["@rules_java//:license"], 5 | default_visibility = ["//visibility:public"], 6 | ) 7 | 8 | filegroup( 9 | name = "srcs", 10 | srcs = glob(["**"]) + [ 11 | "//java/common/rules/impl:srcs", 12 | ], 13 | visibility = ["//java/common:__pkg__"], 14 | ) 15 | 16 | bzl_library( 17 | name = "android_lint_bzl", 18 | srcs = ["android_lint.bzl"], 19 | visibility = ["//visibility:private"], 20 | ) 21 | 22 | bzl_library( 23 | name = "rule_util_bzl", 24 | srcs = ["rule_util.bzl"], 25 | visibility = ["//visibility:private"], 26 | ) 27 | 28 | bzl_library( 29 | name = "core_rules", 30 | srcs = [ 31 | "basic_java_library.bzl", 32 | "java_binary.bzl", 33 | "java_binary_wrapper.bzl", 34 | "java_import.bzl", 35 | "java_library.bzl", 36 | "java_plugin.bzl", 37 | ], 38 | visibility = [ 39 | "//java:__subpackages__", 40 | ], 41 | deps = [ 42 | ":android_lint_bzl", 43 | ":rule_util_bzl", 44 | "//java/private:internals", 45 | "@bazel_skylib//lib:paths", 46 | "@rules_cc//cc/common", 47 | ], 48 | ) 49 | 50 | bzl_library( 51 | name = "toolchain_rules", 52 | srcs = [ 53 | "java_package_configuration.bzl", 54 | "java_runtime.bzl", 55 | "java_toolchain.bzl", 56 | ], 57 | visibility = [ 58 | "//java:__subpackages__", 59 | "@compatibility_proxy//:__pkg__", 60 | ], 61 | ) 62 | 63 | filegroup( 64 | name = "for_bazel_tests", 65 | testonly = 1, 66 | srcs = [ 67 | "BUILD", 68 | ":core_rules", 69 | ":toolchain_rules", 70 | "//java/common/rules/impl:for_bazel_tests", 71 | "@rules_cc//cc/private/rules_impl:srcs", 72 | ], 73 | visibility = ["//java/common:__pkg__"], 74 | ) 75 | -------------------------------------------------------------------------------- /java/common/rules/basic_java_library.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Common code for reuse across java_* rules 17 | """ 18 | 19 | load("//java/common:java_semantics.bzl", "semantics") 20 | load("//java/private:java_common.bzl", "java_common") 21 | load("//java/private:java_info.bzl", "JavaPluginInfo") 22 | load(":rule_util.bzl", "merge_attrs") 23 | 24 | # copybara: default multiline visibility 25 | 26 | BASIC_JAVA_LIBRARY_IMPLICIT_ATTRS = merge_attrs( 27 | { 28 | "_java_plugins": attr.label( 29 | default = semantics.JAVA_PLUGINS_FLAG_ALIAS_LABEL, 30 | providers = [JavaPluginInfo], 31 | ), 32 | # TODO(b/245144242): Used by IDE integration, remove when toolchains are used 33 | "_java_toolchain": attr.label( 34 | default = semantics.JAVA_TOOLCHAIN_LABEL, 35 | providers = [java_common.JavaToolchainInfo], 36 | ), 37 | "_use_auto_exec_groups": attr.bool(default = True), 38 | }, 39 | ) 40 | -------------------------------------------------------------------------------- /java/common/rules/impl/BUILD: -------------------------------------------------------------------------------- 1 | load("@bazel_skylib//:bzl_library.bzl", "bzl_library") 2 | 3 | package( 4 | default_applicable_licenses = ["@rules_java//:license"], 5 | default_visibility = ["//visibility:public"], 6 | ) 7 | 8 | filegroup( 9 | name = "srcs", 10 | srcs = glob(["**"]), 11 | visibility = ["//java/common/rules:__pkg__"], 12 | ) 13 | 14 | bzl_library( 15 | name = "impl", 16 | srcs = glob( 17 | ["*.bzl"], 18 | exclude = ["java_helper.bzl"], 19 | ), 20 | visibility = ["//java:__subpackages__"], 21 | deps = [ 22 | ":java_helper_bzl", 23 | "//java/common:proguard_spec_info_bzl", 24 | "@com_google_protobuf//bazel/common:proto_info_bzl", 25 | ], 26 | ) 27 | 28 | bzl_library( 29 | name = "java_helper_bzl", 30 | srcs = ["java_helper.bzl"], 31 | visibility = ["//java:__subpackages__"], 32 | ) 33 | 34 | filegroup( 35 | name = "for_bazel_tests", 36 | testonly = 1, 37 | srcs = [ 38 | "BUILD", 39 | ":impl", 40 | ], 41 | visibility = ["//java/common/rules:__pkg__"], 42 | ) 43 | -------------------------------------------------------------------------------- /java/common/rules/impl/bazel_java_library_impl.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Definition of java_library rule. 17 | """ 18 | 19 | load("//java/common/rules/impl:basic_java_library_impl.bzl", "basic_java_library", "construct_defaultinfo") 20 | 21 | # copybara: default visibility 22 | 23 | def bazel_java_library_rule( 24 | ctx, 25 | srcs = [], 26 | deps = [], 27 | runtime_deps = [], 28 | plugins = [], 29 | exports = [], 30 | exported_plugins = [], 31 | resources = [], 32 | javacopts = [], 33 | neverlink = False, 34 | proguard_specs = [], 35 | add_exports = [], 36 | add_opens = [], 37 | bootclasspath = None, 38 | javabuilder_jvm_flags = None): 39 | """Implements java_library. 40 | 41 | Use this call when you need to produce a fully fledged java_library from 42 | another rule's implementation. 43 | 44 | Args: 45 | ctx: (RuleContext) Used to register the actions. 46 | srcs: (list[File]) The list of source files that are processed to create the target. 47 | deps: (list[Target]) The list of other libraries to be linked in to the target. 48 | runtime_deps: (list[Target]) Libraries to make available to the final binary or test at runtime only. 49 | plugins: (list[Target]) Java compiler plugins to run at compile-time. 50 | exports: (list[Target]) Exported libraries. 51 | exported_plugins: (list[Target]) The list of `java_plugin`s (e.g. annotation 52 | processors) to export to libraries that directly depend on this library. 53 | resources: (list[File]) A list of data files to include in a Java jar. 54 | javacopts: (list[str]) Extra compiler options for this library. 55 | neverlink: (bool) Whether this library should only be used for compilation and not at runtime. 56 | proguard_specs: (list[File]) Files to be used as Proguard specification. 57 | add_exports: (list[str]) Allow this library to access the given /. 58 | add_opens: (list[str]) Allow this library to reflectively access the given /. 59 | bootclasspath: (Target) The JDK APIs to compile this library against. 60 | javabuilder_jvm_flags: (list[str]) Additional JVM flags to pass to JavaBuilder. 61 | Returns: 62 | (dict[str, provider]) A list containing DefaultInfo, JavaInfo, 63 | InstrumentedFilesInfo, OutputGroupsInfo, ProguardSpecProvider providers. 64 | """ 65 | if not srcs and deps: 66 | fail("deps not allowed without srcs; move to runtime_deps?") 67 | 68 | target, base_info = basic_java_library( 69 | ctx, 70 | srcs = srcs, 71 | deps = deps, 72 | runtime_deps = runtime_deps, 73 | plugins = plugins, 74 | exports = exports, 75 | exported_plugins = exported_plugins, 76 | resources = resources, 77 | resource_jars = [], 78 | classpath_resources = [], 79 | javacopts = javacopts, 80 | neverlink = neverlink, 81 | proguard_specs = proguard_specs, 82 | add_exports = add_exports, 83 | add_opens = add_opens, 84 | bootclasspath = bootclasspath, 85 | javabuilder_jvm_flags = javabuilder_jvm_flags, 86 | ) 87 | 88 | target["DefaultInfo"] = construct_defaultinfo( 89 | ctx, 90 | base_info.files_to_build, 91 | base_info.runfiles, 92 | neverlink, 93 | exports, 94 | runtime_deps, 95 | ) 96 | target["OutputGroupInfo"] = OutputGroupInfo(**base_info.output_groups) 97 | 98 | return target 99 | -------------------------------------------------------------------------------- /java/common/rules/impl/import_deps_check.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2022 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Creates the import deps checker for java rules""" 16 | 17 | load("//java/common:java_semantics.bzl", "semantics") 18 | 19 | visibility(["//java/common/rules/..."]) 20 | 21 | def import_deps_check( 22 | ctx, 23 | jars_to_check, 24 | declared_deps, 25 | transitive_deps, 26 | rule_class): 27 | """ 28 | Creates actions that checks import deps for java rules. 29 | 30 | Args: 31 | ctx: (RuleContext) Used to register the actions. 32 | jars_to_check: (list[File]) A list of jars files to check. 33 | declared_deps: (list[File]) A list of direct dependencies. 34 | transitive_deps: (list[File]) A list of transitive dependencies. 35 | rule_class: (String) Rule class. 36 | 37 | Returns: 38 | (File) Output file of the created action. 39 | """ 40 | java_toolchain = semantics.find_java_toolchain(ctx) 41 | deps_checker = java_toolchain._deps_checker 42 | if deps_checker == None: 43 | return None 44 | 45 | jdeps_output = ctx.actions.declare_file("_%s/%s/jdeps.proto" % (rule_class, ctx.label.name)) 46 | 47 | args = ctx.actions.args() 48 | args.add("-jar", deps_checker) 49 | args.add_all(jars_to_check, before_each = "--input") 50 | args.add_all(declared_deps, before_each = "--directdep") 51 | args.add_all( 52 | depset(order = "preorder", transitive = [declared_deps, transitive_deps]), 53 | before_each = "--classpath_entry", 54 | ) 55 | args.add_all(java_toolchain.bootclasspath, before_each = "--bootclasspath_entry") 56 | args.add("--checking_mode=error") 57 | args.add("--jdeps_output", jdeps_output) 58 | args.add("--rule_label", ctx.label) 59 | 60 | inputs = depset( 61 | jars_to_check, 62 | transitive = [ 63 | declared_deps, 64 | transitive_deps, 65 | java_toolchain.bootclasspath, 66 | ], 67 | ) 68 | tools = [deps_checker, java_toolchain.java_runtime.files] 69 | 70 | ctx.actions.run( 71 | mnemonic = "ImportDepsChecker", 72 | progress_message = "Checking the completeness of the deps for %s" % jars_to_check, 73 | executable = java_toolchain.java_runtime.java_executable_exec_path, 74 | arguments = [args], 75 | inputs = inputs, 76 | outputs = [jdeps_output], 77 | tools = tools, 78 | toolchain = semantics.JAVA_TOOLCHAIN_TYPE, 79 | use_default_shell_env = True, 80 | ) 81 | 82 | return jdeps_output 83 | -------------------------------------------------------------------------------- /java/common/rules/impl/proguard_validation.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Proguard 17 | """ 18 | 19 | load("//java/common:java_semantics.bzl", "semantics") 20 | load("//java/common:proguard_spec_info.bzl", "ProguardSpecInfo") 21 | 22 | visibility("private") 23 | 24 | def _filter_provider(provider, *attrs): 25 | return [dep[provider] for attr in attrs for dep in attr if provider in dep] 26 | 27 | def _validate_spec(ctx, spec_file): 28 | validated_proguard_spec = ctx.actions.declare_file( 29 | "validated_proguard/%s/%s_valid" % (ctx.label.name, spec_file.path), 30 | ) 31 | 32 | toolchain = semantics.find_java_toolchain(ctx) 33 | 34 | args = ctx.actions.args() 35 | args.add("--path", spec_file) 36 | args.add("--output", validated_proguard_spec) 37 | 38 | ctx.actions.run( 39 | mnemonic = "ValidateProguard", 40 | progress_message = "Validating proguard configuration %{input}", 41 | executable = toolchain.proguard_allowlister, 42 | arguments = [args], 43 | inputs = [spec_file], 44 | outputs = [validated_proguard_spec], 45 | toolchain = Label(semantics.JAVA_TOOLCHAIN_TYPE), 46 | use_default_shell_env = True, 47 | ) 48 | 49 | return validated_proguard_spec 50 | 51 | def validate_proguard_specs(ctx, proguard_specs = [], transitive_attrs = []): 52 | """ 53 | Creates actions that validate Proguard specification and returns ProguardSpecProvider. 54 | 55 | Use transtive_attrs parameter to collect Proguard validations from `deps`, 56 | `runtime_deps`, `exports`, `plugins`, and `exported_plugins` attributes. 57 | 58 | Args: 59 | ctx: (RuleContext) Used to register the actions. 60 | proguard_specs: (list[File]) List of Proguard specs files. 61 | transitive_attrs: (list[list[Target]]) Attributes to collect transitive 62 | proguard validations from. 63 | Returns: 64 | (ProguardSpecProvider) A ProguardSpecProvider. 65 | """ 66 | proguard_validations = _filter_provider(ProguardSpecInfo, *transitive_attrs) 67 | return ProguardSpecInfo( 68 | depset( 69 | [_validate_spec(ctx, spec_file) for spec_file in proguard_specs], 70 | transitive = [validation.specs for validation in proguard_validations], 71 | ), 72 | ) 73 | -------------------------------------------------------------------------------- /java/common/rules/java_binary_wrapper.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2022 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Macro encapsulating the java_binary implementation 16 | 17 | This is needed since the `executable` nature of the target must be computed from 18 | the supplied value of the `create_executable` attribute. 19 | """ 20 | 21 | load("//java/common:java_semantics.bzl", "semantics") 22 | 23 | # copybara: default visibility 24 | 25 | def register_legacy_java_binary_rules( 26 | rule_exec, 27 | rule_nonexec, 28 | **kwargs): 29 | """Registers the correct java_binary rule and deploy jar rule 30 | 31 | Args: 32 | rule_exec: (Rule) The executable java_binary rule 33 | rule_nonexec: (Rule) The non-executable java_binary rule 34 | **kwargs: Actual args to instantiate the rule 35 | """ 36 | 37 | create_executable = "create_executable" not in kwargs or kwargs["create_executable"] 38 | 39 | # TODO(hvd): migrate depot to integers / maybe use decompose_select_list() 40 | if "stamp" in kwargs and type(kwargs["stamp"]) == type(True): 41 | kwargs["stamp"] = 1 if kwargs["stamp"] else 0 42 | if not create_executable: 43 | rule_nonexec(**kwargs) 44 | else: 45 | if "use_launcher" in kwargs and not kwargs["use_launcher"]: 46 | kwargs["launcher"] = None 47 | else: 48 | # If launcher is not set or None, set it to config flag 49 | if "launcher" not in kwargs or not kwargs["launcher"]: 50 | kwargs["launcher"] = semantics.LAUNCHER_FLAG_LABEL 51 | rule_exec(**kwargs) 52 | 53 | def register_java_binary_rules( 54 | java_binary, 55 | **kwargs): 56 | """Creates a java_binary rule and a deploy jar rule 57 | 58 | Args: 59 | java_binary: (Rule) The executable java_binary rule 60 | **kwargs: Actual args to instantiate the rule 61 | """ 62 | 63 | # TODO(hvd): migrate depot to integers / maybe use decompose_select_list() 64 | if "stamp" in kwargs and type(kwargs["stamp"]) == type(True): 65 | kwargs["stamp"] = 1 if kwargs["stamp"] else 0 66 | 67 | if "use_launcher" in kwargs and not kwargs["use_launcher"]: 68 | kwargs["launcher"] = None 69 | else: 70 | # If launcher is not set or None, set it to config flag 71 | if "launcher" not in kwargs or not kwargs["launcher"]: 72 | kwargs["launcher"] = semantics.LAUNCHER_FLAG_LABEL 73 | java_binary(**kwargs) 74 | -------------------------------------------------------------------------------- /java/common/rules/java_import.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Definition of java_import rule. 17 | """ 18 | 19 | load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") 20 | load("//java/common:java_semantics.bzl", "semantics") 21 | load("//java/private:java_info.bzl", "JavaInfo") 22 | 23 | # copybara: default visibility 24 | 25 | _ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT = [ 26 | "java_library", 27 | "java_import", 28 | "cc_library", 29 | "cc_binary", 30 | ] 31 | 32 | # buildifier: disable=attr-licenses 33 | JAVA_IMPORT_ATTRS = { 34 | "data": attr.label_list( 35 | allow_files = True, 36 | flags = ["SKIP_CONSTRAINTS_OVERRIDE"], 37 | doc = """ 38 | The list of files needed by this rule at runtime. 39 | """, 40 | ), 41 | "deps": attr.label_list( 42 | providers = [JavaInfo], 43 | allow_rules = _ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT, 44 | doc = """ 45 | The list of other libraries to be linked in to the target. 46 | See java_library.deps. 47 | """, 48 | ), 49 | "exports": attr.label_list( 50 | providers = [JavaInfo], 51 | allow_rules = _ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT, 52 | doc = """ 53 | Targets to make available to users of this rule. 54 | See java_library.exports. 55 | """, 56 | ), 57 | "runtime_deps": attr.label_list( 58 | allow_files = [".jar"], 59 | allow_rules = _ALLOWED_RULES_IN_DEPS_FOR_JAVA_IMPORT, 60 | providers = [[CcInfo], [JavaInfo]], 61 | flags = ["SKIP_ANALYSIS_TIME_FILETYPE_CHECK"], 62 | doc = """ 63 | Libraries to make available to the final binary or test at runtime only. 64 | See java_library.runtime_deps. 65 | """, 66 | ), 67 | # JavaImportBazeRule attr 68 | "jars": attr.label_list( 69 | allow_files = [".jar"], 70 | mandatory = True, 71 | doc = """ 72 | The list of JAR files provided to Java targets that depend on this target. 73 | """, 74 | ), 75 | "srcjar": attr.label( 76 | allow_single_file = [".srcjar", ".jar"], 77 | flags = ["DIRECT_COMPILE_TIME_INPUT"], 78 | doc = """ 79 | A JAR file that contains source code for the compiled JAR files. 80 | """, 81 | ), 82 | "neverlink": attr.bool( 83 | default = False, 84 | doc = """ 85 | Only use this library for compilation and not at runtime. 86 | Useful if the library will be provided by the runtime environment 87 | during execution. Examples of libraries like this are IDE APIs 88 | for IDE plug-ins or tools.jar for anything running on 89 | a standard JDK. 90 | """, 91 | ), 92 | "constraints": attr.string_list( 93 | doc = """ 94 | Extra constraints imposed on this rule as a Java library. 95 | """, 96 | ), 97 | # ProguardLibraryRule attr 98 | "proguard_specs": attr.label_list( 99 | allow_files = True, 100 | doc = """ 101 | Files to be used as Proguard specification. 102 | These will describe the set of specifications to be used by Proguard. If specified, 103 | they will be added to any android_binary target depending on this library. 104 | 105 | The files included here must only have idempotent rules, namely -dontnote, -dontwarn, 106 | assumenosideeffects, and rules that start with -keep. Other options can only appear in 107 | android_binary's proguard_specs, to ensure non-tautological merges. 108 | """, 109 | ), 110 | # Additional attrs 111 | "add_exports": attr.string_list( 112 | doc = """ 113 | Allow this library to access the given module or package. 114 |

115 | This corresponds to the javac and JVM --add-exports= flags. 116 | """, 117 | ), 118 | "add_opens": attr.string_list( 119 | doc = """ 120 | Allow this library to reflectively access the given module or 121 | package. 122 |

123 | This corresponds to the javac and JVM --add-opens= flags. 124 | """, 125 | ), 126 | "licenses": attr.license() if hasattr(attr, "license") else attr.string_list(), 127 | "_java_toolchain_type": attr.label(default = semantics.JAVA_TOOLCHAIN_TYPE), 128 | } 129 | -------------------------------------------------------------------------------- /java/common/rules/java_package_configuration.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2023 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Implementation for the java_package_configuration rule""" 16 | 17 | load("//java/common/rules/impl:java_helper.bzl", "helper") 18 | load("//java/private:boot_class_path_info.bzl", "BootClassPathInfo") 19 | load("//java/private:native.bzl", "get_internal_java_common") 20 | 21 | # copybara: default visibility 22 | 23 | JavaPackageConfigurationInfo = provider( 24 | "A provider for Java per-package configuration", 25 | fields = [ 26 | "data", 27 | "javac_opts", 28 | "matches", 29 | "package_specs", 30 | "system", 31 | ], 32 | ) 33 | 34 | def _matches(package_specs, label): 35 | for spec in package_specs: 36 | if spec.contains(label): 37 | return True 38 | return False 39 | 40 | def _rule_impl(ctx): 41 | javacopts = get_internal_java_common().expand_java_opts(ctx, "javacopts", tokenize = True) 42 | javacopts_depset = helper.detokenize_javacopts(javacopts) 43 | package_specs = [package[PackageSpecificationInfo] for package in ctx.attr.packages] 44 | system = ctx.attr.system[BootClassPathInfo] if ctx.attr.system else None 45 | return [ 46 | DefaultInfo(), 47 | JavaPackageConfigurationInfo( 48 | data = depset(ctx.files.data), 49 | javac_opts = javacopts_depset, 50 | matches = _matches, 51 | package_specs = package_specs, 52 | system = system, 53 | ), 54 | ] 55 | 56 | java_package_configuration = rule( 57 | implementation = _rule_impl, 58 | doc = """ 59 |

60 | Configuration to apply to a set of packages. 61 | Configurations can be added to 62 | java_toolchain.javacoptss. 63 |

64 | 65 |

Example:

66 | 67 |
 68 | 
 69 | 
 70 | java_package_configuration(
 71 |     name = "my_configuration",
 72 |     packages = [":my_packages"],
 73 |     javacopts = ["-Werror"],
 74 | )
 75 | 
 76 | package_group(
 77 |     name = "my_packages",
 78 |     packages = [
 79 |         "//com/my/project/...",
 80 |         "-//com/my/project/testing/...",
 81 |     ],
 82 | )
 83 | 
 84 | java_toolchain(
 85 |     ...,
 86 |     package_configuration = [
 87 |         ":my_configuration",
 88 |     ]
 89 | )
 90 | 
 91 | 
 92 | 
93 | """, 94 | attrs = { 95 | "packages": attr.label_list( 96 | cfg = "exec", 97 | providers = [PackageSpecificationInfo], 98 | doc = """ 99 | The set of package_groups 100 | the configuration should be applied to. 101 | """, 102 | ), 103 | "javacopts": attr.string_list( 104 | doc = """ 105 | Java compiler flags. 106 | """, 107 | ), 108 | "data": attr.label_list( 109 | cfg = "exec", 110 | allow_files = True, 111 | doc = """ 112 | The list of files needed by this configuration at runtime. 113 | """, 114 | ), 115 | "system": attr.label( 116 | providers = [BootClassPathInfo], 117 | doc = """ 118 | Corresponds to javac's --system flag. 119 | """, 120 | ), 121 | # buildifier: disable=attr-licenses 122 | "output_licenses": attr.string_list(), 123 | }, 124 | ) 125 | -------------------------------------------------------------------------------- /java/common/rules/java_plugin.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Definition of java_plugin rule. 17 | """ 18 | 19 | load(":java_library.bzl", "JAVA_LIBRARY_ATTRS") 20 | load(":rule_util.bzl", "merge_attrs") 21 | 22 | # copybara: default visibility 23 | 24 | JAVA_PLUGIN_ATTRS = merge_attrs( 25 | JAVA_LIBRARY_ATTRS, 26 | { 27 | "generates_api": attr.bool(doc = """ 28 | This attribute marks annotation processors that generate API code. 29 |

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

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

36 | """), 37 | "processor_class": attr.string(doc = """ 38 | The processor class is the fully qualified type of the class that the Java compiler should 39 | use as entry point to the annotation processor. If not specified, this rule will not 40 | contribute an annotation processor to the Java compiler's annotation processing, but its 41 | runtime classpath will still be included on the compiler's annotation processor path. (This 42 | is primarily intended for use by 43 | Error Prone plugins, which are loaded 44 | from the annotation processor path using 45 | 46 | java.util.ServiceLoader.) 47 | """), 48 | # buildifier: disable=attr-licenses 49 | "output_licenses": attr.string_list(), 50 | }, 51 | remove_attrs = ["runtime_deps", "exports", "exported_plugins"], 52 | ) 53 | -------------------------------------------------------------------------------- /java/common/rules/rule_util.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Defines rule utilities.""" 15 | 16 | # copybara: rules_java visibility 17 | 18 | def merge_attrs(*attribute_dicts, override_attrs = {}, remove_attrs = []): 19 | """Merges attributes together. 20 | 21 | Attributes are first merged, then overridden and removed. 22 | 23 | If there are duplicate definitions of an attribute, the last one is used. 24 | (Current API doesn't let us compare) 25 | 26 | Overridden and removed attributes need to be present. 27 | 28 | Args: 29 | *attribute_dicts: (*dict[str,Attribute]) A list of attribute dictionaries 30 | to merge together. 31 | override_attrs: (dict[str,Attribute]) A dictionary of attributes to override 32 | remove_attrs: (list[str]) A list of attributes to remove. 33 | Returns: 34 | (dict[str,Attribute]) The merged attributes dictionary. 35 | """ 36 | all_attributes = {} 37 | for attribute_dict in attribute_dicts: 38 | for key, attr in attribute_dict.items(): 39 | all_attributes.setdefault(key, attr) 40 | for key, attr in override_attrs.items(): 41 | if all_attributes.get(key) == None: 42 | fail("Trying to override attribute %s where there is none." % key) 43 | all_attributes[key] = attr 44 | for key in remove_attrs: 45 | if key in override_attrs: 46 | fail("Trying to remove overridden attribute %s." % key) 47 | if key not in all_attributes: 48 | fail("Trying to remove non-existent attribute %s." % key) 49 | all_attributes.pop(key) 50 | return all_attributes 51 | -------------------------------------------------------------------------------- /java/defs.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2019 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Starlark rules for building Java projects.""" 15 | 16 | load("@com_google_protobuf//bazel:java_lite_proto_library.bzl", _java_lite_proto_library = "java_lite_proto_library") 17 | load("@com_google_protobuf//bazel:java_proto_library.bzl", _java_proto_library = "java_proto_library") 18 | load("//java:java_binary.bzl", _java_binary = "java_binary") 19 | load("//java:java_import.bzl", _java_import = "java_import") 20 | load("//java:java_library.bzl", _java_library = "java_library") 21 | load("//java:java_plugin.bzl", _java_plugin = "java_plugin") 22 | load("//java:java_test.bzl", _java_test = "java_test") 23 | load("//java/common:java_common.bzl", _java_common = "java_common") 24 | load("//java/common:java_info.bzl", _JavaInfo = "JavaInfo") 25 | load("//java/common:java_plugin_info.bzl", _JavaPluginInfo = "JavaPluginInfo") 26 | load("//java/toolchains:java_package_configuration.bzl", _java_package_configuration = "java_package_configuration") 27 | load("//java/toolchains:java_runtime.bzl", _java_runtime = "java_runtime") 28 | load("//java/toolchains:java_toolchain.bzl", _java_toolchain = "java_toolchain") 29 | 30 | # Language rules 31 | 32 | java_binary = _java_binary 33 | java_test = _java_test 34 | java_library = _java_library 35 | java_plugin = _java_plugin 36 | java_import = _java_import 37 | 38 | # Toolchain rules 39 | 40 | java_runtime = _java_runtime 41 | java_toolchain = _java_toolchain 42 | java_package_configuration = _java_package_configuration 43 | 44 | # Proto rules 45 | # Deprecated: don't use java proto libraries from here 46 | def java_proto_library(**kwargs): 47 | if "deprecation" not in kwargs: 48 | _java_proto_library( 49 | deprecation = "Use java_proto_library from @com_google_protobuf//bazel:java_proto_library.bzl", 50 | **kwargs 51 | ) 52 | else: 53 | _java_proto_library(**kwargs) 54 | 55 | def java_lite_proto_library(**kwargs): 56 | if "deprecation" not in kwargs: 57 | _java_lite_proto_library( 58 | deprecation = "Use java_lite_proto_library from @com_google_protobuf//bazel:java_lite_proto_library.bzl", 59 | **kwargs 60 | ) 61 | else: 62 | _java_lite_proto_library(**kwargs) 63 | 64 | # Modules and providers 65 | 66 | JavaInfo = _JavaInfo 67 | JavaPluginInfo = _JavaPluginInfo 68 | java_common = _java_common 69 | -------------------------------------------------------------------------------- /java/docs/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load("@bazel_skylib//:bzl_library.bzl", "bzl_library") 2 | load("@stardoc//stardoc:stardoc.bzl", "stardoc") 3 | 4 | package(default_applicable_licenses = ["@rules_java//:license"]) 5 | 6 | exports_files( 7 | ["rules.md"], 8 | visibility = ["//test:__pkg__"], 9 | ) 10 | 11 | bzl_library( 12 | name = "rules_bzl", 13 | srcs = ["rules.bzl"], 14 | deps = [ 15 | "//java/bazel/rules", 16 | "//java/common/rules:toolchain_rules", 17 | ], 18 | ) 19 | 20 | stardoc( 21 | name = "rules_docs", 22 | out = "rules_docs.out", 23 | input = "rules.bzl", 24 | rule_template = ":rule.vm", 25 | symbol_names = [ 26 | # core rules 27 | "java_binary", 28 | "java_import", 29 | "java_library", 30 | "java_plugin", 31 | "java_test", 32 | 33 | # toolchain rules 34 | "java_package_configuration", 35 | "java_runtime", 36 | "java_toolchain", 37 | ], 38 | table_of_contents_template = "@stardoc//stardoc:templates/markdown_tables/table_of_contents.vm", 39 | visibility = ["//test:__pkg__"], 40 | deps = [":rules_bzl"], 41 | ) 42 | -------------------------------------------------------------------------------- /java/docs/rule.vm: -------------------------------------------------------------------------------- 1 | 2 | 3 | #[[##]]# ${ruleName} 4 | 5 |
 6 | ${util.ruleSummary($ruleName, $ruleInfo)}
 7 | 
8 | 9 | ${ruleInfo.docString} 10 | 11 | **ATTRIBUTES** 12 | 13 | #if (!$ruleInfo.getAttributeList().isEmpty()) 14 | 15 | | Name | Description | Type | Mandatory | Default | 16 | | :------------- | :------------- | :------------- | :------------- | :------------- | 17 | #foreach ($attribute in $ruleInfo.getAttributeList()) 18 | | $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 | 19 | #end 20 | #end -------------------------------------------------------------------------------- /java/docs/rules.bzl: -------------------------------------------------------------------------------- 1 | """Java rules""" 2 | 3 | load("//java/bazel/rules:bazel_java_binary.bzl", _java_binary = "java_binary") 4 | load("//java/bazel/rules:bazel_java_import.bzl", _java_import = "java_import") 5 | load("//java/bazel/rules:bazel_java_library.bzl", _java_library = "java_library") 6 | load("//java/bazel/rules:bazel_java_plugin.bzl", _java_plugin = "java_plugin") 7 | load("//java/bazel/rules:bazel_java_test.bzl", _java_test = "java_test") 8 | load("//java/common/rules:java_package_configuration.bzl", _java_package_configuration = "java_package_configuration") 9 | load("//java/common/rules:java_runtime.bzl", _java_runtime = "java_runtime") 10 | load("//java/common/rules:java_toolchain.bzl", _java_toolchain = "java_toolchain") 11 | 12 | visibility("private") 13 | 14 | java_binary = _java_binary 15 | java_import = _java_import 16 | java_library = _java_library 17 | java_plugin = _java_plugin 18 | java_test = _java_test 19 | 20 | java_package_configuration = _java_package_configuration 21 | java_runtime = _java_runtime 22 | java_toolchain = _java_toolchain 23 | -------------------------------------------------------------------------------- /java/extensions.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Module extensions for rules_java.""" 15 | 16 | load("@bazel_features//:features.bzl", "bazel_features") 17 | load( 18 | "//java:repositories.bzl", 19 | "java_tools_repos", 20 | "local_jdk_repo", 21 | "remote_jdk11_repos", 22 | "remote_jdk17_repos", 23 | "remote_jdk21_repos", 24 | "remote_jdk8_repos", 25 | ) 26 | 27 | def _toolchains_impl(module_ctx): 28 | java_tools_repos() 29 | local_jdk_repo() 30 | remote_jdk8_repos() 31 | remote_jdk11_repos() 32 | remote_jdk17_repos() 33 | remote_jdk21_repos() 34 | 35 | if bazel_features.external_deps.extension_metadata_has_reproducible: 36 | return module_ctx.extension_metadata(reproducible = True) 37 | else: 38 | return None 39 | 40 | toolchains = module_extension(_toolchains_impl) 41 | -------------------------------------------------------------------------------- /java/http_jar.bzl: -------------------------------------------------------------------------------- 1 | """The http_jar repo rule, for downloading jars over HTTP. 2 | 3 | ### Setup 4 | 5 | To use this rule in a module extension, load it in your .bzl file and then call it from your 6 | extension's implementation function. For example: 7 | 8 | ```python 9 | load("@rules_java//java:http_jar.bzl", "http_jar") 10 | 11 | def _my_extension_impl(mctx): 12 | http_jar(name = "foo", urls = [...]) 13 | 14 | my_extension = module_extension(implementation = _my_extension_impl) 15 | ``` 16 | 17 | Alternatively, you can directly call it your MODULE.bazel file with `use_repo_rule`: 18 | 19 | ```python 20 | http_jar = use_repo_rule("@rules_java//java:http_jar.bzl", "http_jar") 21 | http_jar(name = "foo", urls = [...]) 22 | ``` 23 | """ 24 | 25 | load("@compatibility_proxy//:proxy.bzl", _http_jar = "http_jar") 26 | 27 | http_jar = _http_jar 28 | -------------------------------------------------------------------------------- /java/java_binary.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2024 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """java_binary rule""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", _java_binary = "java_binary") 17 | 18 | def java_binary(**attrs): 19 | """Bazel java_binary rule. 20 | 21 | https://docs.bazel.build/versions/master/be/java.html#java_binary 22 | 23 | Args: 24 | **attrs: Rule attributes 25 | """ 26 | 27 | _java_binary(**attrs) 28 | -------------------------------------------------------------------------------- /java/java_import.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2024 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """java_import rule""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", _java_import = "java_import") 17 | 18 | def java_import(**attrs): 19 | """Bazel java_import rule. 20 | 21 | https://docs.bazel.build/versions/master/be/java.html#java_import 22 | 23 | Args: 24 | **attrs: Rule attributes 25 | """ 26 | 27 | _java_import(**attrs) 28 | -------------------------------------------------------------------------------- /java/java_library.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2024 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """java_library rule""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", _java_library = "java_library") 17 | 18 | def java_library(**attrs): 19 | """Bazel java_library rule. 20 | 21 | https://docs.bazel.build/versions/master/be/java.html#java_library 22 | 23 | Args: 24 | **attrs: Rule attributes 25 | """ 26 | 27 | _java_library(**attrs) 28 | -------------------------------------------------------------------------------- /java/java_plugin.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2024 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """java_plugin rule""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", _java_plugin = "java_plugin") 17 | 18 | def java_plugin(**attrs): 19 | """Bazel java_plugin rule. 20 | 21 | https://docs.bazel.build/versions/master/be/java.html#java_plugin 22 | 23 | Args: 24 | **attrs: Rule attributes 25 | """ 26 | 27 | _java_plugin(**attrs) 28 | -------------------------------------------------------------------------------- /java/java_test.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2024 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """java_test rule""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", _java_test = "java_test") 17 | 18 | def java_test(**attrs): 19 | """Bazel java_test rule. 20 | 21 | https://docs.bazel.build/versions/master/be/java.html#java_test 22 | 23 | Args: 24 | **attrs: Rule attributes 25 | """ 26 | 27 | _java_test(**attrs) 28 | -------------------------------------------------------------------------------- /java/java_utils.bzl: -------------------------------------------------------------------------------- 1 | """Utility methods for interacting with the java rules""" 2 | 3 | def _tokenize_javacopts(ctx, opts): 4 | """Tokenizes a list or depset of options to a list. 5 | 6 | Iff opts is a depset, we reverse the flattened list to ensure right-most 7 | duplicates are preserved in their correct position. 8 | 9 | Args: 10 | ctx: (RuleContext) the rule context 11 | opts: (depset[str]|[str]) the javac options to tokenize 12 | Returns: 13 | [str] list of tokenized options 14 | """ 15 | if hasattr(opts, "to_list"): 16 | opts = reversed(opts.to_list()) 17 | return [ 18 | token 19 | for opt in opts 20 | for token in ctx.tokenize(opt) 21 | ] 22 | 23 | utils = struct( 24 | tokenize_javacopts = _tokenize_javacopts, 25 | ) 26 | -------------------------------------------------------------------------------- /java/private/BUILD: -------------------------------------------------------------------------------- 1 | load("@bazel_skylib//:bzl_library.bzl", "bzl_library") 2 | 3 | package(default_applicable_licenses = ["@rules_java//:license"]) 4 | 5 | licenses(["notice"]) 6 | 7 | bzl_library( 8 | name = "native_bzl", 9 | srcs = [ 10 | "native.bzl", 11 | ], 12 | visibility = ["//java:__subpackages__"], 13 | ) 14 | 15 | bzl_library( 16 | name = "legacy_native_bzl", 17 | srcs = [ 18 | "legacy_native.bzl", 19 | ], 20 | visibility = ["@compatibility_proxy//:__pkg__"], 21 | ) 22 | 23 | bzl_library( 24 | name = "internals", 25 | srcs = [ 26 | "boot_class_path_info.bzl", 27 | "java_common.bzl", 28 | "java_common_internal.bzl", 29 | "java_info.bzl", 30 | "message_bundle_info.bzl", 31 | ], 32 | visibility = [ 33 | "//java:__subpackages__", 34 | "@compatibility_proxy//:__pkg__", 35 | ], 36 | deps = [ 37 | ":native_bzl", 38 | "//java/common/rules:toolchain_rules", 39 | "//java/common/rules/impl:java_helper_bzl", 40 | "@bazel_skylib//lib:paths", 41 | "@rules_cc//cc:find_cc_toolchain_bzl", 42 | "@rules_cc//cc/common", 43 | ], 44 | ) 45 | 46 | # Exposed for use by the protobuf. 47 | bzl_library( 48 | name = "proto_support", 49 | srcs = ["proto_support.bzl"], 50 | visibility = ["//visibility:public"], 51 | deps = ["@compatibility_proxy//:proxy_bzl"], 52 | ) 53 | 54 | # Exposed for use by the android rules. 55 | bzl_library( 56 | name = "android_support", 57 | srcs = ["android_support.bzl"], 58 | visibility = ["//visibility:public"], 59 | deps = ["@compatibility_proxy//:proxy_bzl"], 60 | ) 61 | 62 | filegroup( 63 | name = "srcs", 64 | srcs = glob(["**"]), 65 | visibility = ["//java:__pkg__"], 66 | ) 67 | 68 | filegroup( 69 | name = "for_bazel_tests", 70 | testonly = 1, 71 | srcs = [ 72 | "BUILD", 73 | ":android_support", 74 | ":internals", 75 | ":native_bzl", 76 | ":proto_support", 77 | ], 78 | visibility = ["//java:__pkg__"], 79 | ) 80 | -------------------------------------------------------------------------------- /java/private/android_support.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2024 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Legacy support for the android rules.""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", "java_info_to_implicit_exportable") 17 | 18 | android_support = struct( 19 | enable_implicit_sourceless_deps_exports_compatibility = java_info_to_implicit_exportable, 20 | ) 21 | -------------------------------------------------------------------------------- /java/private/boot_class_path_info.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2023 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Definition of the BootClassPathInfo provider. 17 | """ 18 | 19 | load("@bazel_skylib//lib:paths.bzl", "paths") 20 | 21 | visibility( 22 | ["//java/..."], 23 | ) 24 | 25 | def _init(bootclasspath = [], auxiliary = [], system = None): 26 | """The BootClassPathInfo constructor. 27 | 28 | Args: 29 | bootclasspath: ([File]) 30 | auxiliary: ([File]) 31 | system: ([File]|File|None) 32 | """ 33 | if not system: # None or [] 34 | system_inputs = depset() 35 | system_path = None 36 | elif type(system) == "File": 37 | system_inputs = depset([system]) 38 | if not system.is_directory: 39 | fail("for system,", system, "is not a directory") 40 | system_path = system.path 41 | elif type(system) == type([]): 42 | system_inputs = depset(system) 43 | system_paths = [input.path for input in system if input.basename == "release"] 44 | if not system_paths: 45 | fail("for system, expected inputs to contain 'release'") 46 | system_path = paths.dirname(system_paths[0]) 47 | else: 48 | fail("for system, got", type(system), ", want File, sequence, or None") 49 | 50 | return { 51 | "bootclasspath": depset(bootclasspath), 52 | "_auxiliary": depset(auxiliary), 53 | "_system_inputs": system_inputs, 54 | "_system_path": system_path, 55 | } 56 | 57 | BootClassPathInfo, _new_bootclasspathinfo = provider( 58 | doc = "Information about the system APIs for a Java compilation.", 59 | fields = [ 60 | "bootclasspath", 61 | # private 62 | "_auxiliary", 63 | "_system_inputs", 64 | "_system_path", 65 | ], 66 | init = _init, 67 | ) 68 | -------------------------------------------------------------------------------- /java/private/legacy_native.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2022 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # Redefine native symbols with a new name as a workaround for 16 | # exporting them in @compatibility_proxy//:proxy.bzl with their original name. 17 | 18 | """Lovely workaround to be able to expose native constants pretending to be Starlark.""" 19 | 20 | # Unused with Bazel@HEAD, only used by the compatibility layer for older Bazel versions 21 | 22 | # buildifier: disable=native-java-common 23 | native_java_common = java_common 24 | 25 | # buildifier: disable=native-java-info 26 | NativeJavaInfo = JavaInfo 27 | 28 | # buildifier: disable=native-java-plugin-info 29 | NativeJavaPluginInfo = JavaPluginInfo 30 | -------------------------------------------------------------------------------- /java/private/message_bundle_info.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2023 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Definition of MessageBundleInfo provider. 17 | """ 18 | 19 | visibility("private") 20 | 21 | MessageBundleInfo = provider( 22 | doc = "Marks configured targets that are able to supply message bundles to their dependents.", 23 | fields = { 24 | "messages": "Sequence of message bundles", 25 | }, 26 | ) 27 | -------------------------------------------------------------------------------- /java/private/native.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2022 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Redirects for private native APIs""" 16 | 17 | # Used for some private native APIs that we can't replicate just yet in Starlark 18 | def get_internal_java_common(): 19 | return java_common.internal_DO_NOT_USE() # buildifier: disable=native-java-common 20 | -------------------------------------------------------------------------------- /java/private/proto_support.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2024 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Support for Java compilation of protocol buffer generated code.""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", "java_common", "java_common_internal_compile", "java_info_internal_merge") 17 | 18 | def compile(*, injecting_rule_kind, enable_jspecify, include_compilation_info, **kwargs): 19 | if java_common_internal_compile: 20 | return java_common_internal_compile( 21 | injecting_rule_kind = injecting_rule_kind, 22 | enable_jspecify = enable_jspecify, 23 | include_compilation_info = include_compilation_info, 24 | **kwargs 25 | ) 26 | else: 27 | return java_common.compile(**kwargs) 28 | 29 | def merge(providers, *, merge_java_outputs = True, merge_source_jars = True): 30 | if java_info_internal_merge: 31 | return java_info_internal_merge( 32 | providers, 33 | merge_java_outputs = merge_java_outputs, 34 | merge_source_jars = merge_source_jars, 35 | ) 36 | else: 37 | return java_common.merge(providers) 38 | -------------------------------------------------------------------------------- /java/proto/BUILD: -------------------------------------------------------------------------------- 1 | package( 2 | default_applicable_licenses = ["@rules_java//:license"], 3 | default_visibility = ["//visibility:public"], 4 | ) 5 | 6 | # Toolchain type provided by proto_lang_toolchain rule and used by java_proto_library 7 | toolchain_type(name = "toolchain_type") 8 | 9 | # Toolchain type provided by proto_lang_toolchain rule and used by java_lite_proto_library 10 | toolchain_type(name = "lite_toolchain_type") 11 | 12 | filegroup( 13 | name = "srcs", 14 | srcs = glob(["**"]), 15 | visibility = ["//java:__pkg__"], 16 | ) 17 | -------------------------------------------------------------------------------- /java/runfiles/BUILD: -------------------------------------------------------------------------------- 1 | package(default_applicable_licenses = ["@rules_java//:license"]) 2 | 3 | alias( 4 | name = "runfiles", 5 | actual = "//java/runfiles/src/main/java/com/google/devtools/build/runfiles", 6 | visibility = ["//visibility:public"], 7 | ) 8 | 9 | filegroup( 10 | name = "srcs", 11 | srcs = glob(["**"]) + [ 12 | "//java/runfiles/src/main/java/com/google/devtools/build/runfiles:srcs", 13 | ], 14 | visibility = ["//java:__pkg__"], 15 | ) 16 | -------------------------------------------------------------------------------- /java/runfiles/src/main/java/com/google/devtools/build/runfiles/AutoBazelRepository.java: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Bazel Authors. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package com.google.devtools.build.runfiles; 16 | 17 | import java.lang.annotation.ElementType; 18 | import java.lang.annotation.Retention; 19 | import java.lang.annotation.RetentionPolicy; 20 | import java.lang.annotation.Target; 21 | 22 | /** 23 | * Annotating a class {@code Fooer} with this annotation generates a class {@code 24 | * AutoBazelRepository_Fooer} defining a {@link String} constant {@code NAME} containing the 25 | * canonical name of the repository containing the Bazel target that compiled the annotated class. 26 | */ 27 | @Retention(RetentionPolicy.SOURCE) 28 | @Target(ElementType.TYPE) 29 | public @interface AutoBazelRepository {} 30 | -------------------------------------------------------------------------------- /java/runfiles/src/main/java/com/google/devtools/build/runfiles/BUILD: -------------------------------------------------------------------------------- 1 | load("//java:defs.bzl", "java_library", "java_plugin") 2 | 3 | package(default_applicable_licenses = ["@rules_java//:license"]) 4 | 5 | java_library( 6 | name = "runfiles", 7 | srcs = [ 8 | "Runfiles.java", 9 | "Util.java", 10 | ], 11 | exported_plugins = [":auto_bazel_repository_processor"], 12 | visibility = ["//java/runfiles:__pkg__"], 13 | exports = [":auto_bazel_repository"], 14 | ) 15 | 16 | java_library( 17 | name = "auto_bazel_repository", 18 | srcs = ["AutoBazelRepository.java"], 19 | ) 20 | 21 | java_plugin( 22 | name = "auto_bazel_repository_processor", 23 | srcs = ["AutoBazelRepositoryProcessor.java"], 24 | processor_class = "com.google.devtools.build.runfiles.AutoBazelRepositoryProcessor", 25 | ) 26 | 27 | filegroup( 28 | name = "srcs", 29 | srcs = glob(["**"]), 30 | visibility = ["//java/runfiles:__pkg__"], 31 | ) 32 | -------------------------------------------------------------------------------- /java/runfiles/src/main/java/com/google/devtools/build/runfiles/Util.java: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Bazel Authors. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package com.google.devtools.build.runfiles; 16 | 17 | /** 18 | * Utilities for the other classes in this package. 19 | * 20 | *

These functions are implementations of some basic utilities in the Guava library. We 21 | * reimplement these functions instead of depending on Guava, so that the Runfiles library has no 22 | * third-party dependencies, thus any Java project can depend on it without the risk of pulling 23 | * unwanted or conflicting dependencies (for example if the project already depends on Guava, or 24 | * wishes not to depend on it at all). 25 | */ 26 | class Util { 27 | private Util() {} 28 | 29 | /** Returns true when {@code s} is null or an empty string. */ 30 | public static boolean isNullOrEmpty(String s) { 31 | return s == null || s.isEmpty(); 32 | } 33 | 34 | /** Throws an {@code IllegalArgumentException} if {@code condition} is false. */ 35 | public static void checkArgument(boolean condition) { 36 | checkArgument(condition, null, null); 37 | } 38 | 39 | /** Throws an {@code IllegalArgumentException} if {@code condition} is false. */ 40 | public static void checkArgument(boolean condition, String error, Object arg1) { 41 | if (!condition) { 42 | if (isNullOrEmpty(error)) { 43 | throw new IllegalArgumentException("argument validation failed"); 44 | } else { 45 | throw new IllegalArgumentException(String.format(error, arg1)); 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /java/testutil.bzl: -------------------------------------------------------------------------------- 1 | """Exposes some private APIs for tests""" 2 | 3 | # copybara: rules_java visibility 4 | 5 | # TODO: consider eventually upstreaming to rules_cc 6 | 7 | def _cc_info_transitive_native_libraries(cc_info): 8 | return cc_info.transitive_native_libraries() 9 | 10 | def _cc_library_to_link_static_library(library_to_link): 11 | return library_to_link.static_library or library_to_link.pic_static_library 12 | 13 | testutil = struct( 14 | cc_info_transitive_native_libraries = _cc_info_transitive_native_libraries, 15 | cc_library_to_link_static_library = _cc_library_to_link_static_library, 16 | ) 17 | -------------------------------------------------------------------------------- /java/toolchains/BUILD: -------------------------------------------------------------------------------- 1 | load("@bazel_skylib//:bzl_library.bzl", "bzl_library") 2 | 3 | package( 4 | default_applicable_licenses = ["@rules_java//:license"], 5 | default_visibility = ["//visibility:public"], 6 | ) 7 | 8 | licenses(["notice"]) 9 | 10 | filegroup( 11 | name = "srcs", 12 | srcs = glob(["**"]), 13 | visibility = ["//java:__pkg__"], 14 | ) 15 | 16 | bzl_library( 17 | name = "toolchain_rules", 18 | srcs = glob(["*.bzl"]), 19 | visibility = ["//visibility:public"], 20 | deps = ["@compatibility_proxy//:proxy_bzl"], 21 | ) 22 | 23 | filegroup( 24 | name = "for_bazel_tests", 25 | srcs = [ 26 | "BUILD", 27 | "java_toolchain.bzl", 28 | ], 29 | ) 30 | -------------------------------------------------------------------------------- /java/toolchains/java_package_configuration.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2023 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """java_package_configuration rule""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", _java_package_configuration = "java_package_configuration") 17 | 18 | def java_package_configuration(**attrs): 19 | """Bazel java_package_configuration rule. 20 | 21 | https://docs.bazel.build/versions/master/be/java.html#java_package_configuration 22 | 23 | Args: 24 | **attrs: Rule attributes 25 | """ 26 | 27 | _java_package_configuration(**attrs) 28 | -------------------------------------------------------------------------------- /java/toolchains/java_runtime.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2023 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """java_runtime rule""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", _java_runtime = "java_runtime") 17 | 18 | def java_runtime(**attrs): 19 | """Bazel java_runtime rule. 20 | 21 | https://docs.bazel.build/versions/master/be/java.html#java_runtime 22 | 23 | Args: 24 | **attrs: Rule attributes 25 | """ 26 | 27 | _java_runtime(**attrs) 28 | -------------------------------------------------------------------------------- /java/toolchains/java_toolchain.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2023 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """java_toolchain rule""" 15 | 16 | load("@compatibility_proxy//:proxy.bzl", _java_toolchain = "java_toolchain") 17 | 18 | def java_toolchain(**attrs): 19 | """Bazel java_toolchain rule. 20 | 21 | https://docs.bazel.build/versions/master/be/java.html#java_toolchain 22 | 23 | Args: 24 | **attrs: Rule attributes 25 | """ 26 | 27 | _java_toolchain(**attrs) 28 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /test/BUILD.bazel: -------------------------------------------------------------------------------- 1 | # Copyright 2024 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | load("@bazel_skylib//rules:diff_test.bzl", "diff_test") 16 | load("@rules_shell//shell:sh_test.bzl", "sh_test") 17 | load("//java:repositories.bzl", "JAVA_TOOLS_CONFIG", "REMOTE_JDK_CONFIGS") 18 | load(":check_remotejdk_configs_match.bzl", "validate_configs") 19 | 20 | package(default_applicable_licenses = ["@rules_java//:license"]) 21 | 22 | sh_test( 23 | name = "check_remote_jdk_configs_test", 24 | srcs = ["check_remote_jdk_configs.sh"], 25 | args = [ 26 | ",".join([ 27 | config.name, 28 | config.urls[0], 29 | config.urls[1] if len(config.urls) > 1 else "", 30 | config.sha256, 31 | config.strip_prefix, 32 | ]) 33 | for configs in REMOTE_JDK_CONFIGS.values() 34 | for config in configs 35 | ], 36 | tags = ["manual"], # explicitly tested only on Linux 37 | ) 38 | 39 | sh_test( 40 | name = "check_remote_java_tools_configs_test", 41 | srcs = ["check_remote_java_tools_configs.sh"], 42 | args = [ 43 | ",".join([ 44 | name, 45 | config["mirror_url"], 46 | config["github_url"], 47 | config["sha"], 48 | ]) 49 | for name, config in JAVA_TOOLS_CONFIG["artifacts"].items() 50 | ], 51 | ) 52 | 53 | sh_test( 54 | name = "check_release_notes_test", 55 | srcs = ["check_release_notes_test.sh"], 56 | args = [ 57 | "$(location //distro:relnotes.txt)", 58 | module_version(), 59 | ], 60 | data = ["//distro:relnotes.txt"], 61 | tags = ["manual"], # explicitly tested only on Linux 62 | ) 63 | 64 | diff_test( 65 | name = "docs_up_to_date_test", 66 | failure_message = """ 67 | Docs are no longer up to date. Regenerate them by running: 68 | 69 | bazel build //java/docs:rules_docs && \ 70 | cp bazel-bin/java/docs/rules_docs.out java/docs/rules.md 71 | """, 72 | file1 = "//java/docs:rules.md", 73 | file2 = "//java/docs:rules_docs", 74 | ) 75 | 76 | validate_configs() 77 | 78 | starlark_doc_extract( 79 | name = "proxy_bzl_graph", 80 | src = "@compatibility_proxy//:proxy.bzl", 81 | deps = ["@compatibility_proxy//:proxy_bzl"], 82 | ) 83 | -------------------------------------------------------------------------------- /test/check_release_notes_test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Copyright 2025 The Bazel Authors. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | RELNOTES_FILE=$1 17 | VERSION=$2 18 | 19 | function fail() { 20 | echo "ERROR: ${1}" 21 | echo "Release notes content:" 22 | echo "--------------------------------------" 23 | cat ${RELNOTES_FILE} 24 | echo "--------------------------------------" 25 | exit 1 26 | } 27 | 28 | echo "Checking generated release notes: ${RELNOTES_FILE}" 29 | 30 | grep -q '**Changes since fake-tag-for-tests**' ${RELNOTES_FILE} || fail "No changelog header" 31 | grep -q 'Fake commit message for testing' ${RELNOTES_FILE} || fail "No changelog commit" 32 | grep -q '**MODULE.bazel setup**' ${RELNOTES_FILE} || fail "No bzlmod setup header" 33 | grep -q "bazel_dep(name = \"rules_java\", version = \"${VERSION}\")" ${RELNOTES_FILE} || fail "No bzlmod dep stanza" 34 | grep -q '**WORKSPACE setup**' ${RELNOTES_FILE} || fail "No WORKSPACE setup header" 35 | grep -q '**Using the rules**' ${RELNOTES_FILE} || fail "No using the rules header" 36 | -------------------------------------------------------------------------------- /test/check_remote_java_tools_configs.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Copyright 2024 The Bazel Authors. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | echo "Checking hashes for $# configs" 17 | 18 | function download_and_check_hash() { 19 | name=$1 20 | url=$2 21 | hash=$3 22 | TMP_FILE=$(mktemp -q /tmp/remotejavatools.XXXXXX) 23 | echo "fetching $name from $url to ${TMP_FILE}" 24 | curl --silent -o ${TMP_FILE} -L "$url" 25 | actual_hash=`sha256sum ${TMP_FILE} | cut -d' ' -f1` 26 | if [ "${hash}" != "${actual_hash}" ]; then 27 | echo "ERROR: wrong hash for ${name}! wanted: ${hash}, got: ${actual_hash}" 28 | exit 1 29 | fi 30 | } 31 | 32 | for config in "$@"; do 33 | IFS=, read -r name mirror_url gh_url hash <<< "${config}" 34 | download_and_check_hash ${name} ${mirror_url} ${hash} 35 | download_and_check_hash ${name} ${gh_url} ${hash} 36 | done -------------------------------------------------------------------------------- /test/check_remote_jdk_configs.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Copyright 2024 The Bazel Authors. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | echo "Checking hashes and strip_prefix for $# configs" 17 | 18 | _MISSING_MIRRORS=() 19 | for config in "$@"; do 20 | TMP_FILE=$(mktemp -q /tmp/remotejdk.XXXXXX) 21 | IFS=, read -r name url mirror_url hash strip_prefix <<< "${config}" 22 | echo "fetching $name from $url to ${TMP_FILE}" 23 | curl --silent -o ${TMP_FILE} -L "$url" 24 | actual_hash=$(sha256sum ${TMP_FILE} | cut -d' ' -f1) 25 | if [ "${hash}" != "${actual_hash}" ]; then 26 | echo "ERROR: wrong hash for ${name}! wanted: ${hash}, got: ${actual_hash}" 27 | exit 1 28 | fi 29 | if [[ -z "${url##*.tar.gz}" ]]; then 30 | root_dir=$(tar ztf ${TMP_FILE} --exclude='*/*') 31 | elif [[ -z "${url##*.zip}" ]]; then 32 | root_dir=$(unzip -Z1 ${TMP_FILE} | head -n1) 33 | else 34 | echo "ERROR: unexpected archive type for ${name}" 35 | exit 1 36 | fi 37 | if [ "${root_dir}" != "${strip_prefix}/" ]; then 38 | echo "ERROR: bad strip_prefix for ${name}, wanted: ${strip_prefix}/, got: ${root_dir}" 39 | exit 1 40 | fi 41 | if [[ -n "${mirror_url}" ]]; then 42 | echo "checking mirror: ${mirror_url}" 43 | curl --silent --fail -I -L ${mirror_url} > /dev/null || { _MISSING_MIRRORS+=("${mirror_url}"); } 44 | fi 45 | done 46 | 47 | if [[ ${#_MISSING_MIRRORS[@]} -gt 0 ]]; then 48 | echo "Missing mirror URLs:" 49 | for m in "${_MISSING_MIRRORS[@]}"; do 50 | echo " ${m}" 51 | done 52 | exit 1 53 | fi -------------------------------------------------------------------------------- /test/check_remotejdk_configs_match.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2024 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Checks for keeping repository_util.bzl and repositories.bzl in sync""" 15 | 16 | load("//java:repositories.bzl", "REMOTE_JDK_CONFIGS") 17 | load("//java/bazel:repositories_util.bzl", "FLAT_CONFIGS") 18 | 19 | def validate_configs(): 20 | """Ensures repository_util.bzl and repositories.bzl are in sync""" 21 | for expected in FLAT_CONFIGS: 22 | actual = [cfg for cfg in REMOTE_JDK_CONFIGS[expected.version] if cfg.name == expected.name] 23 | if len(actual) != 1: 24 | fail("Expected to find exactly one configuration for:", expected.name, "found: ", actual) 25 | actual = actual[0] 26 | if expected.urls != actual.urls or expected.strip_prefix != actual.strip_prefix: 27 | fail("config mismatch! wanted:", expected, "got:", actual) 28 | -------------------------------------------------------------------------------- /test/java/BUILD: -------------------------------------------------------------------------------- 1 | package(default_applicable_licenses = ["@rules_java//:license"]) 2 | -------------------------------------------------------------------------------- /test/java/bazel/BUILD.bazel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bazelbuild/rules_java/fecb9fbe5e5417997bb8dda24c1873a130baf7d4/test/java/bazel/BUILD.bazel -------------------------------------------------------------------------------- /test/java/bazel/rules/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load(":java_binary_tests.bzl", "java_binary_tests") 2 | 3 | java_binary_tests(name = "java_binary_tests") 4 | -------------------------------------------------------------------------------- /test/java/bazel/rules/java_binary_tests.bzl: -------------------------------------------------------------------------------- 1 | """Tests for the Bazel java_binary rule""" 2 | 3 | load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") 4 | load("@rules_testing//lib:util.bzl", "util") 5 | load("//java:java_binary.bzl", "java_binary") 6 | 7 | def _test_java_binary_cross_compilation_to_unix(name): 8 | # A Unix platform that: 9 | # - has a JDK 10 | # - does not require a launcher 11 | # - is not supported by the default C++ toolchain 12 | util.helper_target( 13 | native.platform, 14 | name = name + "/platform", 15 | constraint_values = [ 16 | "@platforms//os:linux", 17 | "@platforms//cpu:s390x", 18 | ], 19 | ) 20 | 21 | util.helper_target( 22 | java_binary, 23 | name = name + "/bin", 24 | srcs = ["java/C.java"], 25 | main_class = "C", 26 | ) 27 | 28 | analysis_test( 29 | name = name, 30 | impl = _test_java_binary_cross_compilation_to_unix_impl, 31 | target = name + "/bin", 32 | config_settings = { 33 | "//command_line_option:platforms": [Label(name + "/platform")], 34 | }, 35 | # Requires the launcher_maker toolchain. 36 | attr_values = {"tags": ["min_bazel_9"]}, 37 | ) 38 | 39 | def _test_java_binary_cross_compilation_to_unix_impl(env, target): 40 | # The main assertion is that analysis succeeds, but verify the absence of a 41 | # binary launcher for good measure. We do this by checking that the output 42 | # executable is the stub script, and not a bespoke launcher 43 | executable = target[DefaultInfo].files_to_run.executable.short_path 44 | assert_action = env.expect.that_target(target).action_generating(executable) 45 | assert_action.mnemonic().equals("TemplateExpand") 46 | assert_action.substitutions().keys().contains("%jvm_flags%") 47 | assert_action.inputs().contains_exactly(["java/bazel/rules/java_stub_template.txt"]) 48 | 49 | def java_binary_tests(name): 50 | test_suite( 51 | name = name, 52 | tests = [ 53 | _test_java_binary_cross_compilation_to_unix, 54 | ], 55 | ) 56 | -------------------------------------------------------------------------------- /test/java/common/BUILD: -------------------------------------------------------------------------------- 1 | load(":java_common_tests.bzl", "java_common_tests") 2 | load(":java_info_tests.bzl", "java_info_tests") 3 | load(":java_plugin_info_tests.bzl", "java_plugin_info_tests") 4 | 5 | package(default_applicable_licenses = ["@rules_java//:license"]) 6 | 7 | java_common_tests(name = "java_common_tests") 8 | 9 | java_info_tests(name = "java_info_tests") 10 | 11 | java_plugin_info_tests(name = "java_plugin_info_tests") 12 | -------------------------------------------------------------------------------- /test/java/common/rules/BUILD: -------------------------------------------------------------------------------- 1 | load(":java_binary_tests.bzl", "java_binary_tests") 2 | load(":java_import_tests.bzl", "java_import_tests") 3 | load(":java_library_tests.bzl", "java_library_tests") 4 | load(":java_plugin_tests.bzl", "java_plugin_tests") 5 | load(":java_test_tests.bzl", "java_test_tests") 6 | load(":merge_attrs_tests.bzl", "merge_attrs_test_suite") 7 | 8 | package(default_applicable_licenses = ["@rules_java//:license"]) 9 | 10 | merge_attrs_test_suite(name = "merge_attrs_tests") 11 | 12 | java_binary_tests(name = "java_binary_tests") 13 | 14 | java_plugin_tests(name = "java_plugin_tests") 15 | 16 | java_library_tests(name = "java_library_tests") 17 | 18 | java_import_tests(name = "java_import_tests") 19 | 20 | java_test_tests(name = "java_test_tests") 21 | -------------------------------------------------------------------------------- /test/java/common/rules/java_plugin_tests.bzl: -------------------------------------------------------------------------------- 1 | """Tests for the java_plugin rule""" 2 | 3 | load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") 4 | load("@rules_testing//lib:util.bzl", "util") 5 | load("//java:java_library.bzl", "java_library") 6 | load("//java:java_plugin.bzl", "java_plugin") 7 | load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") 8 | load("//test/java/testutil:java_info_subject.bzl", "java_plugin_info_subject") 9 | 10 | def _test_exposes_plugins_to_starlark(name): 11 | target_name = name + "/plugin" 12 | util.helper_target( 13 | java_library, 14 | name = target_name + "/plugin_dep", 15 | srcs = ["ProcessorDep.java"], 16 | data = ["depfile.dat"], 17 | ) 18 | util.helper_target( 19 | java_plugin, 20 | name = target_name, 21 | srcs = ["AnnotationProcessor.java"], 22 | data = ["pluginfile.dat"], 23 | processor_class = "com.google.process.stuff", 24 | deps = [target_name + "/plugin_dep"], 25 | ) 26 | 27 | analysis_test( 28 | name = name, 29 | impl = _test_exposes_plugins_to_starlark_impl, 30 | target = target_name, 31 | ) 32 | 33 | def _test_exposes_plugins_to_starlark_impl(env, target): 34 | assert_plugin_data = java_plugin_info_subject.from_target(env, target).plugins() 35 | assert_plugin_data.processor_classes().contains_exactly(["com.google.process.stuff"]) 36 | assert_plugin_data.processor_jars().contains_exactly([ 37 | "{package}/lib{name}.jar", 38 | "{package}/lib{name}/plugin_dep.jar", 39 | ]) 40 | assert_plugin_data.processor_data().contains_exactly(["{package}/pluginfile.dat"]) 41 | 42 | java_plugin_info_subject.from_target(env, target).api_generating_plugins().is_empty() 43 | 44 | def _test_exposes_api_generating_plugins_to_starlark(name): 45 | target_name = name + "/plugin" 46 | util.helper_target( 47 | java_library, 48 | name = target_name + "/plugin_dep", 49 | srcs = ["ProcessorDep.java"], 50 | data = ["depfile.dat"], 51 | ) 52 | util.helper_target( 53 | java_plugin, 54 | name = target_name, 55 | srcs = ["AnnotationProcessor.java"], 56 | data = ["pluginfile.dat"], 57 | processor_class = "com.google.process.stuff", 58 | deps = [target_name + "/plugin_dep"], 59 | generates_api = True, 60 | ) 61 | 62 | analysis_test( 63 | name = name, 64 | impl = _test_exposes_api_generating_plugins_to_starlark_impl, 65 | target = target_name, 66 | ) 67 | 68 | def _test_exposes_api_generating_plugins_to_starlark_impl(env, target): 69 | assert_api_plugin_data = java_plugin_info_subject.from_target(env, target).api_generating_plugins() 70 | assert_api_plugin_data.processor_classes().contains_exactly(["com.google.process.stuff"]) 71 | assert_api_plugin_data.processor_jars().contains_exactly([ 72 | "{package}/lib{name}.jar", 73 | "{package}/lib{name}/plugin_dep.jar", 74 | ]) 75 | assert_api_plugin_data.processor_data().contains_exactly(["{package}/pluginfile.dat"]) 76 | assert_api_plugin_data.equals(target[JavaPluginInfo].plugins) 77 | 78 | def java_plugin_tests(name): 79 | test_suite( 80 | name = name, 81 | tests = [ 82 | _test_exposes_plugins_to_starlark, 83 | _test_exposes_api_generating_plugins_to_starlark, 84 | ], 85 | ) 86 | -------------------------------------------------------------------------------- /test/java/common/rules/java_test_tests.bzl: -------------------------------------------------------------------------------- 1 | """Tests for the java_test rule""" 2 | 3 | load("@rules_cc//cc:cc_binary.bzl", "cc_binary") 4 | load("@rules_cc//cc:cc_library.bzl", "cc_library") 5 | load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") 6 | load("@rules_testing//lib:truth.bzl", "matching", "subjects") 7 | load("@rules_testing//lib:util.bzl", "util") 8 | load("//java:java_library.bzl", "java_library") 9 | load("//java:java_test.bzl", "java_test") 10 | load("//test/java/testutil:rules/custom_java_info_rule.bzl", "custom_java_info_rule") 11 | 12 | def _test_java_test_propagates_direct_native_libraries(name): 13 | util.helper_target( 14 | cc_library, 15 | name = name + "/cclib", 16 | srcs = ["z.cc"], 17 | ) 18 | util.helper_target( 19 | cc_binary, 20 | name = name + "/native", 21 | srcs = ["cc/x.cc"], 22 | deps = [name + "/cclib"], 23 | linkshared = 1, 24 | linkstatic = 1, 25 | ) 26 | util.helper_target( 27 | java_library, 28 | name = name + "/jl", 29 | srcs = ["java/A.java"], 30 | deps = [name + "/native"], 31 | ) 32 | util.helper_target( 33 | cc_binary, 34 | name = name + "/ccl", 35 | srcs = ["cc/x.cc"], 36 | deps = [name + "/cclib"], 37 | linkshared = 1, 38 | linkstatic = 1, 39 | ) 40 | util.helper_target( 41 | custom_java_info_rule, 42 | name = name + "/r", 43 | output_jar = name + "-out.jar", 44 | cc_dep = [name + "/ccl"], 45 | dep = [name + "/jl"], 46 | ) 47 | util.helper_target( 48 | java_test, 49 | name = name + "/binary", 50 | srcs = ["java/C.java"], 51 | deps = [name + "/r"], 52 | main_class = "C", 53 | ) 54 | 55 | analysis_test( 56 | name = name, 57 | impl = _test_java_test_propagates_direct_native_libraries_impl, 58 | target = name + "/binary", 59 | # in Bazel 6, the windows stub was created by a bespoke, native and 60 | # opaque-to-Starlark LauncherFileWriteAction 61 | attr_values = {"tags": ["min_bazel_7"]}, 62 | ) 63 | 64 | def _test_java_test_propagates_direct_native_libraries_impl(env, target): 65 | executable = target[DefaultInfo].files_to_run.executable.short_path 66 | assert_action = env.expect.that_target(target).action_generating(executable) 67 | if assert_action.actual.substitutions: 68 | # TemplateExpansion action on linux/mac 69 | assert_jvm_flags = assert_action.substitutions().get( 70 | "%jvm_flags%", 71 | factory = lambda v, meta: subjects.collection([v], meta), 72 | ) 73 | else: 74 | # windows 75 | assert_jvm_flags = assert_action.argv() 76 | assert_jvm_flags.contains_predicate( 77 | matching.str_matches("-Djava.library.path=${JAVA_RUNFILES}/*/test_java_test_propagates_direct_native_libraries"), 78 | ) 79 | 80 | def java_test_tests(name): 81 | test_suite( 82 | name = name, 83 | tests = [ 84 | _test_java_test_propagates_direct_native_libraries, 85 | ], 86 | ) 87 | -------------------------------------------------------------------------------- /test/java/common/rules/merge_attrs_tests.bzl: -------------------------------------------------------------------------------- 1 | """Tests for merge_attrsfunction""" 2 | 3 | load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") 4 | load( 5 | "//java/common/rules:rule_util.bzl", 6 | "merge_attrs", 7 | ) 8 | 9 | _attr_string = attr.string() 10 | _attr_string_different_ref = attr.string() 11 | _attr_string_different = attr.string(default = "Some default") 12 | 13 | def _merge_attrs_merges_impl(ctx): 14 | env = unittest.begin(ctx) 15 | 16 | attrs = merge_attrs( 17 | {"A": _attr_string}, 18 | {"B": _attr_string_different_ref, "C": _attr_string_different}, 19 | override_attrs = {"B": _attr_string_different}, 20 | remove_attrs = ["C"], 21 | ) 22 | 23 | asserts.equals(env, attrs, {"A": _attr_string, "B": _attr_string_different}) 24 | 25 | return unittest.end(env) 26 | 27 | merge_attrs_merges_test = unittest.make(_merge_attrs_merges_impl) 28 | 29 | def merge_attrs_test_suite(name): 30 | """Sets up util test suite 31 | 32 | Args: 33 | name: the name of the test suite target 34 | """ 35 | unittest.suite( 36 | name, 37 | merge_attrs_merges_test, 38 | ) 39 | -------------------------------------------------------------------------------- /test/java/private/BUILD: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | load(":android_support_tests.bzl", "android_support_tests") 15 | 16 | package(default_applicable_licenses = ["@rules_java//:license"]) 17 | 18 | android_support_tests(name = "android_support_tests") 19 | -------------------------------------------------------------------------------- /test/java/private/android_support_tests.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Tests for //java/private:android_support.bzl""" 15 | 16 | load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") 17 | load("@rules_testing//lib:util.bzl", "util") 18 | load("//java:defs.bzl", "java_library", "java_plugin") 19 | load("//java/common:java_info.bzl", "JavaInfo") 20 | load("//java/private:android_support.bzl", "android_support") # buildifier: disable=bzl-visibility 21 | load("//test/java/testutil:java_info_subject.bzl", "java_info_subject") 22 | 23 | def _impl(ctx): 24 | return [ 25 | android_support.enable_implicit_sourceless_deps_exports_compatibility(ctx.attr.dep[JavaInfo]), 26 | ] 27 | 28 | my_rule = rule( 29 | implementation = _impl, 30 | attrs = { 31 | "dep": attr.label(), 32 | }, 33 | ) 34 | 35 | def _test_enable_implicit_sourceless_deps_exports_compatibility(name): 36 | util.helper_target( 37 | java_plugin, 38 | name = "my_plugin", 39 | srcs = ["MyPlugin.java"], 40 | ) 41 | util.helper_target( 42 | java_library, 43 | name = "base", 44 | srcs = ["Foo.java"], 45 | exported_plugins = [":my_plugin"], 46 | ) 47 | util.helper_target( 48 | my_rule, 49 | name = "transformed", 50 | dep = ":base", 51 | ) 52 | 53 | analysis_test( 54 | name = name, 55 | impl = _test_enable_implicit_sourceless_deps_exports_compatibility_impl, 56 | targets = { 57 | "base": Label(":base"), 58 | "transformed": Label(":transformed"), 59 | }, 60 | ) 61 | 62 | def _test_enable_implicit_sourceless_deps_exports_compatibility_impl(env, targets): 63 | base_info = java_info_subject.from_target(env, targets.base) 64 | transformed_info = java_info_subject.from_target(env, targets.transformed) 65 | transformed_info.compilation_args().equals_subject(base_info.compilation_args()) 66 | base_info.plugins().processor_jars().contains_exactly(["{package}/libmy_plugin.jar"]) 67 | transformed_info.plugins().processor_jars().contains_exactly([]) 68 | 69 | def android_support_tests(name): 70 | test_suite( 71 | name = name, 72 | tests = [ 73 | _test_enable_implicit_sourceless_deps_exports_compatibility, 74 | ], 75 | ) 76 | -------------------------------------------------------------------------------- /test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load("@rules_java//java:java_import.bzl", "java_import") 2 | load("@rules_java//java:java_test.bzl", "java_test") 3 | 4 | package(default_applicable_licenses = ["@rules_java//:license"]) 5 | 6 | java_test( 7 | name = "RunfilesTest", 8 | srcs = ["RunfilesTest.java"], 9 | test_class = "com.google.devtools.build.runfiles.RunfilesTest", 10 | deps = [ 11 | ":guava", 12 | ":truth", 13 | "//java/runfiles", 14 | ], 15 | ) 16 | 17 | java_test( 18 | name = "UtilTest", 19 | srcs = ["UtilTest.java"], 20 | test_class = "com.google.devtools.build.runfiles.UtilTest", 21 | deps = [ 22 | ":guava", 23 | ":truth", 24 | "//java/runfiles", 25 | ], 26 | ) 27 | 28 | java_import( 29 | name = "guava", 30 | jars = ["@guava//file"], 31 | ) 32 | 33 | java_import( 34 | name = "truth", 35 | jars = ["@truth//file"], 36 | ) 37 | -------------------------------------------------------------------------------- /test/java/runfiles/src/test/java/com/google/devtools/build/runfiles/UtilTest.java: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Bazel Authors. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package com.google.devtools.build.runfiles; 16 | 17 | import static com.google.common.truth.Truth.assertThat; 18 | import static org.junit.Assert.assertThrows; 19 | 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | import org.junit.runners.JUnit4; 23 | 24 | /** Unit tests for {@link Util}. */ 25 | @RunWith(JUnit4.class) 26 | public final class UtilTest { 27 | 28 | @Test 29 | public void testIsNullOrEmpty() { 30 | assertThat(Util.isNullOrEmpty(null)).isTrue(); 31 | assertThat(Util.isNullOrEmpty("")).isTrue(); 32 | assertThat(Util.isNullOrEmpty("\0")).isFalse(); 33 | assertThat(Util.isNullOrEmpty("some text")).isFalse(); 34 | } 35 | 36 | @Test 37 | public void testCheckArgument() { 38 | Util.checkArgument(true, null, null); 39 | 40 | IllegalArgumentException e = 41 | assertThrows(IllegalArgumentException.class, () -> Util.checkArgument(false, null, null)); 42 | assertThat(e).hasMessageThat().isEqualTo("argument validation failed"); 43 | 44 | e = assertThrows(IllegalArgumentException.class, () -> Util.checkArgument(false, "foo-%s", 42)); 45 | assertThat(e).hasMessageThat().isEqualTo("foo-42"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /test/java/testutil/BUILD: -------------------------------------------------------------------------------- 1 | load(":javac_action_subject_tests.bzl", "javac_action_subject_tests") 2 | 3 | package(default_applicable_licenses = ["@rules_java//:license"]) 4 | 5 | javac_action_subject_tests(name = "javac_action_subject_tests") 6 | -------------------------------------------------------------------------------- /test/java/testutil/artifact_closure.bzl: -------------------------------------------------------------------------------- 1 | """Helper for computing the artifact closure of a target""" 2 | 3 | # TODO: consider upstreaming this to @rules_testing 4 | 5 | def _of_target(target): 6 | to_process = target[DefaultInfo].files.to_list() 7 | if _ArtifactActionMapInfo not in target: 8 | fail("Did you forget to add the aspect to analysis_test(extra_target_under_test_aspects = )?") 9 | map = target[_ArtifactActionMapInfo].map 10 | result = [] 11 | visited = {} 12 | for __ in range(len(map)): 13 | if not to_process: 14 | break 15 | next_to_process = [] 16 | for x in to_process: 17 | if x in visited: 18 | continue 19 | visited[x] = None 20 | result.append(x) 21 | if x not in map: 22 | # source file or not visible to us (toolchain?) 23 | continue 24 | a = map[x] 25 | next_to_process.extend([f for f in a.inputs.to_list() if f not in visited]) 26 | to_process = next_to_process 27 | return result 28 | 29 | _ArtifactActionMapInfo = provider( 30 | "Map of artifacts to actions", 31 | fields = ["map"], 32 | ) 33 | 34 | def _aspect_impl(target, ctx): 35 | map = {} 36 | for action in target.actions: 37 | for output in action.outputs.to_list(): 38 | map[output] = action 39 | 40 | # Rollup from all dep attributes 41 | for attr_name in dir(ctx.rule.attr): 42 | attr = getattr(ctx.rule.attr, attr_name) 43 | if type(attr) != "list": 44 | attr = [attr] 45 | for val in attr: 46 | if type(val) == "Target" and _ArtifactActionMapInfo in val: 47 | map = map | val[_ArtifactActionMapInfo].map 48 | return _ArtifactActionMapInfo(map = map) 49 | 50 | _aspect = aspect(_aspect_impl, attr_aspects = ["*"]) 51 | 52 | artifact_closure = struct( 53 | aspect = _aspect, 54 | of_target = _of_target, 55 | ) 56 | -------------------------------------------------------------------------------- /test/java/testutil/cc_info_subject.bzl: -------------------------------------------------------------------------------- 1 | """A custom @rules_testing subject for the CcInfo provider""" 2 | 3 | load("@rules_testing//lib:truth.bzl", "subjects") 4 | load("//java:testutil.bzl", "testutil") 5 | 6 | def _new_cc_info_subject(cc_info, meta): 7 | self = struct( 8 | actual = cc_info, 9 | meta = meta, 10 | ) 11 | public = struct( 12 | linking_context = lambda: _new_cc_info_linking_context_subject(self.actual, self.meta), 13 | native_libraries = lambda: subjects.collection(testutil.cc_info_transitive_native_libraries(self.actual), self.meta.derive("transitive_native_libraries()")), 14 | ) 15 | return public 16 | 17 | def _new_cc_info_linking_context_subject(cc_info, meta): 18 | self = struct( 19 | actual = cc_info.linking_context, 20 | meta = meta.derive("linking_context"), 21 | ) 22 | public = struct( 23 | equals = lambda other: _cc_info_linking_context_equals(self.actual, other, self.meta), 24 | libraries_to_link = lambda: _new_cc_info_libraries_to_link_subject(self.actual.libraries_to_link, self.meta.derive("libraries_to_link")), 25 | static_mode_params_for_dynamic_library_libs = lambda: _new_static_mode_params_for_dynamic_library_libs_subject(self.actual, self.meta), 26 | ) 27 | return public 28 | 29 | def _new_static_mode_params_for_dynamic_library_libs_subject(linking_context, meta): 30 | libs = [] 31 | for input in linking_context.linker_inputs.to_list(): 32 | for lib in input.libraries: 33 | if lib.pic_static_library: 34 | libs.append(lib.pic_static_library) 35 | elif lib.static_library: 36 | libs.append(lib.static_library) 37 | elif lib.interface_library: 38 | libs.append(lib.interface_library) 39 | else: 40 | libs.append(lib.dynamic_library) 41 | 42 | return subjects.collection( 43 | libs, 44 | meta = meta.derive("static_mode_params_for_dynamic_library_libs"), 45 | ) 46 | 47 | def _cc_info_linking_context_equals(actual, expected, meta): 48 | if actual == expected: 49 | return 50 | meta.add_failure( 51 | "expected: {}".format(expected), 52 | "actual: {}".format(actual), 53 | ) 54 | 55 | def _new_cc_info_libraries_to_link_subject(libraries_to_link, meta): 56 | if hasattr(libraries_to_link, "to_list"): 57 | libraries_to_link = libraries_to_link.to_list() 58 | self = struct( 59 | actual = libraries_to_link, 60 | meta = meta, 61 | ) 62 | public = struct( 63 | static_libraries = lambda: _new_library_to_link_static_libraries_subject(self.actual, self.meta), 64 | singleton = lambda: _new_library_to_link_subject(_get_singleton(self.actual), self.meta.derive("[0]")), 65 | ) 66 | return public 67 | 68 | def _new_library_to_link_subject(library_to_link, meta): 69 | public = struct( 70 | dynamic_library = lambda: subjects.file(library_to_link.dynamic_library, meta.derive("dynamic_library")), 71 | ) 72 | return public 73 | 74 | def _new_library_to_link_static_libraries_subject(libraries_to_link, meta): 75 | self = subjects.collection( 76 | [testutil.cc_library_to_link_static_library(lib) for lib in libraries_to_link], 77 | meta = meta.derive("static_library()"), 78 | ).transform(desc = "basename", map_each = lambda file: file.basename) 79 | public = struct( 80 | contains_exactly = lambda expected: self.contains_exactly([meta.format_str(e) for e in expected]), 81 | contains_exactly_predicates = lambda expected: self.contains_exactly_predicates(expected), 82 | ) 83 | return public 84 | 85 | def _get_singleton(seq): 86 | if len(seq) != 1: 87 | fail("expected singleton, got:", seq) 88 | return seq[0] 89 | 90 | cc_info_subject = struct( 91 | new_from_java_info = lambda java_info, meta: _new_cc_info_subject(java_info.cc_link_params_info, meta.derive("cc_link_params_info")), 92 | libraries_to_link = _new_cc_info_libraries_to_link_subject, 93 | ) 94 | -------------------------------------------------------------------------------- /test/java/testutil/helper.bzl: -------------------------------------------------------------------------------- 1 | """Misc helpers for rules_java testing""" 2 | 3 | load("@rules_testing//lib:analysis_test.bzl", "analysis_test") 4 | load("@rules_testing//lib:util.bzl", "util") 5 | 6 | def always_passes(name): 7 | """Declares a fake, always passing test 8 | 9 | Args: 10 | name: (str) the name of the test 11 | """ 12 | util.helper_target( 13 | native.filegroup, 14 | name = name + "/empty", 15 | ) 16 | analysis_test( 17 | name = name, 18 | impl = lambda *a, **kw: None, 19 | target = name + "/empty", 20 | ) 21 | -------------------------------------------------------------------------------- /test/java/testutil/java_runtime_info_subject.bzl: -------------------------------------------------------------------------------- 1 | """Custom @rules_testing subject for the JavaRuntimeInfo provider""" 2 | 3 | load("@rules_testing//lib:truth.bzl", "subjects", "truth") 4 | load("@rules_testing//lib:util.bzl", "TestingAspectInfo") 5 | load("//java/common:java_common.bzl", "java_common") 6 | 7 | def _new_java_runtime_info_subject(java_runtime_info, meta): 8 | self = struct( 9 | actual = java_runtime_info, 10 | meta = meta.derive("JavaRuntimeInfo"), 11 | ) 12 | public = struct( 13 | java_home = lambda: _new_path_string_subject(self.actual.java_home, self.meta.derive("java_home")), 14 | java_home_runfiles_path = lambda: _new_path_string_subject(self.actual.java_home_runfiles_path, self.meta.derive("java_home_runfiles_path")), 15 | java_executable_exec_path = lambda: _new_path_string_subject(self.actual.java_executable_exec_path, self.meta.derive("java_executable_exec_path")), 16 | java_executable_runfiles_path = lambda: _new_path_string_subject(self.actual.java_executable_runfiles_path, self.meta.derive("java_executable_runfiles_path")), 17 | ) 18 | return public 19 | 20 | def _new_path_string_subject(str, meta): 21 | public = struct( 22 | equals = lambda other: subjects.str(str, meta).equals(meta.format_str(other)), 23 | is_in = lambda expected: subjects.str(str, meta).is_in([meta.format_str(e) for e in expected]), 24 | starts_with = lambda prefix: _check_str_prefix(str, prefix, meta), 25 | ) 26 | return public 27 | 28 | def _check_str_prefix(actual, prefix, meta): 29 | if not actual.startswith(meta.format_str(prefix)): 30 | meta.add_failure( 31 | "did not start with required prefix: {}".format(prefix), 32 | "actual: {}".format(actual), 33 | ) 34 | 35 | def _from_target(env, target): 36 | return _new_java_runtime_info_subject( 37 | target[java_common.JavaRuntimeInfo], 38 | meta = truth.expect(env).meta.derive( 39 | format_str_kwargs = { 40 | "name": target.label.name, 41 | "package": target.label.package, 42 | "bindir": target[TestingAspectInfo].bin_path, 43 | }, 44 | ), 45 | ) 46 | 47 | java_runtime_info_subject = struct( 48 | new = _new_java_runtime_info_subject, 49 | from_target = _from_target, 50 | ) 51 | -------------------------------------------------------------------------------- /test/java/testutil/java_toolchain_info_subject.bzl: -------------------------------------------------------------------------------- 1 | """Custom @rules_testing subject for the JavaToolchainInfo provider""" 2 | 3 | load("@rules_testing//lib:truth.bzl", "subjects") 4 | load("//java/common:java_common.bzl", "java_common") 5 | 6 | def _new_java_toolchain_info_subject(info, meta): 7 | public = struct( 8 | jacocorunner = lambda: subjects.file(info.jacocorunner.executable, meta.derive("jacocorunner.executable")), 9 | ) 10 | return public 11 | 12 | def _from_target(env, target): 13 | return env.expect.that_target(target).provider( 14 | java_common.JavaToolchainInfo, 15 | factory = _new_java_toolchain_info_subject, 16 | provider_name = "JavaToolchainInfo", 17 | ) 18 | 19 | java_toolchain_info_subject = struct( 20 | new = _new_java_toolchain_info_subject, 21 | from_target = _from_target, 22 | ) 23 | -------------------------------------------------------------------------------- /test/java/testutil/javac_action_subject.bzl: -------------------------------------------------------------------------------- 1 | """Bespoke rules_testing subject for the Java compilation action""" 2 | 3 | load("@rules_testing//lib:truth.bzl", "subjects", "truth") 4 | load("@rules_testing//lib:util.bzl", "TestingAspectInfo") 5 | 6 | def _new_javac_action_subject(env, target, output): 7 | action = env.expect.that_target(target).action_generating(output).actual 8 | self = struct( 9 | actual = action, 10 | parsed_flags = _parse_flags(action.argv), 11 | meta = truth.expect(env).meta.derive( 12 | "Javac", 13 | format_str_kwargs = { 14 | "name": target.label.name, 15 | "package": target.label.package, 16 | "bin_path": target[TestingAspectInfo].bin_path, 17 | }, 18 | ), 19 | ) 20 | public = struct( 21 | direct_dependencies = lambda: subjects.collection(self.parsed_flags["--direct_dependencies"], self.meta.derive("--direct_dependencies"), format = True), 22 | ) 23 | return public 24 | 25 | def _parse_flags(argv): 26 | flag_values = {} 27 | current_flag_name = None 28 | for idx, arg in enumerate(argv): 29 | if idx == 0: 30 | continue # java command 31 | if arg.startswith("-"): 32 | if "=" in arg: 33 | parts = arg.split("=", 1) 34 | flag_values.setdefault(parts[0], []).append(parts[1]) 35 | current_flag_name = None 36 | else: 37 | flag_values.setdefault(arg, []) 38 | current_flag_name = arg 39 | else: 40 | if not current_flag_name: 41 | fail("No preceding flag for value:", arg, "at index:", idx, "\nargv:\n", argv) 42 | flag_values[current_flag_name].append(arg) 43 | 44 | return flag_values 45 | 46 | javac_action_subject = struct( 47 | of = _new_javac_action_subject, 48 | parse_flags = _parse_flags, # exposed for testing this method itself 49 | ) 50 | -------------------------------------------------------------------------------- /test/java/testutil/javac_action_subject_tests.bzl: -------------------------------------------------------------------------------- 1 | """Tests for the javac_action_subject""" 2 | 3 | load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") 4 | load(":javac_action_subject.bzl", "javac_action_subject") 5 | 6 | def _parse_flags_test_impl(ctx): 7 | env = unittest.begin(ctx) 8 | flags = javac_action_subject.parse_flags([ 9 | "/usr/bin/java", 10 | "-Xmx1g", 11 | "-XX:SomeProp=SomeVal", 12 | "-Dcom.google.foo=bar", 13 | "--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", 14 | "--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED", 15 | "--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED", 16 | "--add-opens=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED", 17 | "-jar", 18 | "JavaBuilder_deploy.jar", 19 | "--output", 20 | "blaze-out/k8/bin/pkg/libfoo.jar", 21 | "-source", 22 | "21", 23 | "-target", 24 | "17", 25 | "-g", 26 | "-parameters", 27 | "-sourcepath", 28 | ":", 29 | "-Xmaxerrs", 30 | "123", 31 | "--", 32 | "--strict_java_deps", 33 | "ERROR", 34 | "--classpath", 35 | "pkg/bar-hjar.jar", 36 | "other/pkg/baz.jar", 37 | ]) 38 | asserts.equals(env, { 39 | "-Xmx1g": [], 40 | "-XX:SomeProp": ["SomeVal"], 41 | "-Dcom.google.foo": ["bar"], 42 | "--add-exports": [ 43 | "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", 44 | "jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED", 45 | ], 46 | "--add-opens": [ 47 | "jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED", 48 | "jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED", 49 | ], 50 | "-jar": ["JavaBuilder_deploy.jar"], 51 | "--output": ["blaze-out/k8/bin/pkg/libfoo.jar"], 52 | "-source": ["21"], 53 | "-target": ["17"], 54 | "-g": [], 55 | "-parameters": [], 56 | "-sourcepath": [":"], 57 | "-Xmaxerrs": ["123"], 58 | "--": [], 59 | "--strict_java_deps": ["ERROR"], 60 | "--classpath": ["pkg/bar-hjar.jar", "other/pkg/baz.jar"], 61 | }, flags) 62 | return unittest.end(env) 63 | 64 | _parse_flags_test = unittest.make(_parse_flags_test_impl) 65 | 66 | def javac_action_subject_tests(name): 67 | unittest.suite( 68 | name, 69 | _parse_flags_test, 70 | ) 71 | -------------------------------------------------------------------------------- /test/java/testutil/rules/bad_java_info_rules.bzl: -------------------------------------------------------------------------------- 1 | """Helper rules to test errors in JavaInfo instantiation""" 2 | 3 | load("//java/common:java_info.bzl", "JavaInfo") 4 | 5 | def _make_file(ctx): 6 | f = ctx.actions.declare_file(ctx.label.name + ".out") 7 | ctx.actions.write(f, "out") 8 | return f 9 | 10 | def _deps_impl(ctx): 11 | f = _make_file(ctx) 12 | return JavaInfo(output_jar = f, compile_jar = f, deps = [f]) 13 | 14 | def _runtime_deps_impl(ctx): 15 | f = _make_file(ctx) 16 | return JavaInfo(output_jar = f, compile_jar = f, runtime_deps = [f]) 17 | 18 | def _exports_impl(ctx): 19 | f = _make_file(ctx) 20 | return JavaInfo(output_jar = f, compile_jar = f, exports = [f]) 21 | 22 | def _nativelibs_impl(ctx): 23 | f = _make_file(ctx) 24 | return JavaInfo(output_jar = f, compile_jar = f, native_libraries = [f]) 25 | 26 | def _compile_jar_not_set_impl(ctx): 27 | f = _make_file(ctx) 28 | return JavaInfo(output_jar = f) 29 | 30 | def _compile_jar_set_to_none_impl(ctx): 31 | f = _make_file(ctx) 32 | return JavaInfo(output_jar = f, compile_jar = None) 33 | 34 | bad_deps = rule(_deps_impl) 35 | bad_runtime_deps = rule(_runtime_deps_impl) 36 | bad_exports = rule(_exports_impl) 37 | bad_libs = rule(_nativelibs_impl) 38 | compile_jar_not_set = rule(_compile_jar_not_set_impl) 39 | compile_jar_set_to_none = rule(_compile_jar_set_to_none_impl) 40 | -------------------------------------------------------------------------------- /test/java/testutil/rules/custom_java_info_rule.bzl: -------------------------------------------------------------------------------- 1 | """Helper rule for creating JavaInfo instances""" 2 | 3 | load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") 4 | load("//java/common:java_common.bzl", "java_common") 5 | load("//java/common:java_info.bzl", "JavaInfo") 6 | load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") 7 | load("//java/common:java_semantics.bzl", "semantics") 8 | 9 | def _impl(ctx): 10 | if ctx.attr.compile_jar and (ctx.attr.use_ijar or ctx.attr.stamp_jar): 11 | fail("Cannot set use_ijar/stamp_jar if compile_jar is set") 12 | if ctx.attr.use_ijar and ctx.attr.stamp_jar: 13 | fail("only one of use_ijar or stamp_jar may be set") 14 | ctx.actions.write(ctx.outputs.output_jar, "JavaInfo API Test", is_executable = False) 15 | dp = [dep[JavaInfo] for dep in ctx.attr.dep] 16 | dp_runtime = [dep[JavaInfo] for dep in ctx.attr.dep_runtime] 17 | dp_exports = [dep[java_common.provider] for dep in ctx.attr.dep_exports] 18 | dp_exported_plugins = [dep[JavaPluginInfo] for dep in ctx.attr.dep_exported_plugins] 19 | source_jar = java_common.pack_sources( 20 | ctx.actions, 21 | output_source_jar = ctx.actions.declare_file(ctx.outputs.output_jar.basename[:-4] + "-src.jar", sibling = ctx.outputs.output_jar), 22 | sources = ctx.files.sources, 23 | source_jars = ctx.files.source_jars, 24 | java_toolchain = semantics.find_java_toolchain(ctx), 25 | ) if ctx.attr.pack_sources else ( 26 | ctx.files.source_jars[0] if ctx.files.source_jars else None 27 | ) 28 | dp_libs = [dep[CcInfo] for dep in ctx.attr.cc_dep] 29 | if ctx.attr.compile_jar: 30 | compile_jar = ctx.file.compile_jar 31 | elif ctx.attr.use_ijar: 32 | compile_jar = java_common.run_ijar( 33 | ctx.actions, 34 | jar = ctx.outputs.output_jar, 35 | java_toolchain = semantics.find_java_toolchain(ctx), 36 | ) 37 | elif ctx.attr.stamp_jar: 38 | compile_jar = java_common.stamp_jar( 39 | ctx.actions, 40 | jar = ctx.outputs.output_jar, 41 | target_label = ctx.label, 42 | java_toolchain = semantics.find_java_toolchain(ctx), 43 | ) 44 | else: 45 | compile_jar = ctx.outputs.output_jar 46 | 47 | return [ 48 | JavaInfo( 49 | output_jar = ctx.outputs.output_jar, 50 | compile_jar = compile_jar, 51 | source_jar = source_jar, 52 | deps = dp, 53 | runtime_deps = dp_runtime, 54 | exports = dp_exports, 55 | exported_plugins = dp_exported_plugins, 56 | native_libraries = dp_libs, 57 | neverlink = ctx.attr.neverlink, 58 | jdeps = ctx.file.jdeps, 59 | compile_jdeps = ctx.file.compile_jdeps, 60 | generated_class_jar = ctx.file.generated_class_jar, 61 | generated_source_jar = ctx.file.generated_source_jar, 62 | native_headers_jar = ctx.file.native_headers_jar, 63 | manifest_proto = ctx.file.manifest_proto, 64 | ), 65 | ] 66 | 67 | custom_java_info_rule = rule( 68 | _impl, 69 | attrs = { 70 | "output_jar": attr.output(mandatory = True), 71 | "source_jars": attr.label_list(allow_files = [".jar"]), 72 | "sources": attr.label_list(allow_files = [".java"]), 73 | "dep": attr.label_list(), 74 | "dep_runtime": attr.label_list(), 75 | "dep_exports": attr.label_list(), 76 | "dep_exported_plugins": attr.label_list(), 77 | "cc_dep": attr.label_list(), 78 | "jdeps": attr.label(allow_single_file = True), 79 | "compile_jdeps": attr.label(allow_single_file = True), 80 | "generated_class_jar": attr.label(allow_single_file = True), 81 | "generated_source_jar": attr.label(allow_single_file = True), 82 | "native_headers_jar": attr.label(allow_single_file = True), 83 | "manifest_proto": attr.label(allow_single_file = True), 84 | "use_ijar": attr.bool(default = False), 85 | "neverlink": attr.bool(default = False), 86 | "pack_sources": attr.bool(default = False), 87 | "stamp_jar": attr.bool(default = False), 88 | "compile_jar": attr.label(allow_single_file = True), 89 | }, 90 | toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], 91 | ) 92 | -------------------------------------------------------------------------------- /test/java/testutil/rules/custom_library.bzl: -------------------------------------------------------------------------------- 1 | """Helper rule for testing compilation with default parameter values""" 2 | 3 | load("//java/common:java_common.bzl", "java_common") 4 | load("//java/common:java_info.bzl", "JavaInfo") 5 | load("//java/common:java_plugin_info.bzl", "JavaPluginInfo") 6 | load("//java/common:java_semantics.bzl", "semantics") 7 | 8 | def _custom_library_impl(ctx): 9 | output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") 10 | deps = [dep[JavaInfo] for dep in ctx.attr.deps] 11 | runtime_deps = [dep[JavaInfo] for dep in ctx.attr.runtime_deps] 12 | compilation_provider = java_common.compile( 13 | ctx, 14 | source_files = ctx.files.srcs, 15 | source_jars = ctx.files.source_jars, 16 | output = output_jar, 17 | neverlink = ctx.attr.neverlink, 18 | deps = deps, 19 | runtime_deps = runtime_deps, 20 | exports = [e[JavaInfo] for e in ctx.attr.exports], 21 | plugins = [p[JavaPluginInfo] for p in ctx.attr.plugins], 22 | javac_opts = ctx.attr.javac_opts, 23 | java_toolchain = semantics.find_java_toolchain(ctx), 24 | ) 25 | return [DefaultInfo(files = depset([output_jar])), compilation_provider] 26 | 27 | custom_library = rule( 28 | _custom_library_impl, 29 | attrs = { 30 | "srcs": attr.label_list(allow_files = [".java"]), 31 | "source_jars": attr.label_list(allow_files = [".jar"]), 32 | "deps": attr.label_list(), 33 | "runtime_deps": attr.label_list(), 34 | "exports": attr.label_list(), 35 | "plugins": attr.label_list(), 36 | "javac_opts": attr.string_list(), 37 | "neverlink": attr.bool(), 38 | }, 39 | toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], 40 | fragments = ["java"], 41 | ) 42 | -------------------------------------------------------------------------------- /test/java/testutil/rules/custom_library_extended_compile_jdeps.bzl: -------------------------------------------------------------------------------- 1 | """Helper rule to test extending compile time jdeps""" 2 | 3 | load("//java/common:java_common.bzl", "java_common") 4 | load("//java/common:java_info.bzl", "JavaInfo") 5 | load("//java/common:java_semantics.bzl", "semantics") 6 | 7 | CompileJdepsInfo = provider("Provider to testing compile jdeps", fields = ["before", "after"]) 8 | 9 | def _compile_time_jdeps(info): 10 | return depset([outputs.compile_jdeps for outputs in info.java_outputs if outputs.compile_jdeps != None]) 11 | 12 | def _impl(ctx): 13 | output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") 14 | info = java_common.compile( 15 | ctx, 16 | source_files = ctx.files.srcs, 17 | output = output_jar, 18 | deps = [d[JavaInfo] for d in ctx.attr.deps], 19 | exports = [e[JavaInfo] for e in ctx.attr.exports], 20 | java_toolchain = semantics.find_java_toolchain(ctx), 21 | ) 22 | jdeps_info = JavaInfo( 23 | output_jar = output_jar, 24 | compile_jar = None, 25 | compile_jdeps = ctx.file.extra_jdeps, 26 | ) 27 | extra_info = java_common.merge([info, jdeps_info]) 28 | return [ 29 | extra_info, 30 | CompileJdepsInfo( 31 | before = _compile_time_jdeps(info), 32 | after = _compile_time_jdeps(extra_info), 33 | ), 34 | ] 35 | 36 | custom_library_extended_jdeps = rule( 37 | implementation = _impl, 38 | outputs = { 39 | "my_output": "lib%{name}.jar", 40 | }, 41 | attrs = { 42 | "srcs": attr.label_list(allow_files = [".java"]), 43 | "extra_jdeps": attr.label(allow_single_file = True), 44 | "deps": attr.label_list(providers = [JavaInfo]), 45 | "exports": attr.label_list(providers = [JavaInfo]), 46 | }, 47 | toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], 48 | fragments = ["java"], 49 | ) 50 | -------------------------------------------------------------------------------- /test/java/testutil/rules/custom_library_with_additional_inputs.bzl: -------------------------------------------------------------------------------- 1 | """Custom rule to test java_common.compile() with additional inputs and outputs""" 2 | 3 | load("//java/common:java_common.bzl", "java_common") 4 | load("//java/common:java_semantics.bzl", "semantics") 5 | 6 | def _impl(ctx): 7 | output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") 8 | java_common.compile( 9 | ctx, 10 | source_jars = ctx.files.srcs, 11 | output = output_jar, 12 | annotation_processor_additional_inputs = ctx.files.additional_inputs, 13 | annotation_processor_additional_outputs = [ctx.outputs.additional_output], 14 | java_toolchain = semantics.find_java_toolchain(ctx), 15 | ) 16 | return [DefaultInfo(files = depset([output_jar]))] 17 | 18 | custom_library_with_additional_inputs = rule( 19 | implementation = _impl, 20 | outputs = { 21 | "additional_output": "%{name}_additional_output", 22 | }, 23 | attrs = { 24 | "srcs": attr.label_list(allow_files = [".jar"]), 25 | "additional_inputs": attr.label_list(allow_files = [".bin"]), 26 | }, 27 | toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], 28 | fragments = ["java"], 29 | ) 30 | -------------------------------------------------------------------------------- /test/java/testutil/rules/custom_library_with_bootclasspath.bzl: -------------------------------------------------------------------------------- 1 | """Helper rule to test custom bootclasspaths in java_common.compile()""" 2 | 3 | load("//java/common:java_common.bzl", "java_common") 4 | load("//java/common:java_semantics.bzl", "semantics") 5 | 6 | def _bootclasspath(ctx): 7 | return [java_common.BootClassPathInfo(bootclasspath = ctx.files.bootclasspath, system = ctx.files.system)] 8 | 9 | custom_bootclasspath = rule( 10 | implementation = _bootclasspath, 11 | attrs = { 12 | "bootclasspath": attr.label_list(allow_files = True), 13 | "system": attr.label_list(allow_files = True), 14 | }, 15 | ) 16 | 17 | def _impl(ctx): 18 | output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") 19 | compilation_provider = java_common.compile( 20 | ctx, 21 | source_files = ctx.files.srcs, 22 | output = output_jar, 23 | deps = [], 24 | sourcepath = ctx.files.sourcepath, 25 | strict_deps = "ERROR", 26 | java_toolchain = semantics.find_java_toolchain(ctx), 27 | bootclasspath = ctx.attr.bootclasspath[java_common.BootClassPathInfo], 28 | ) 29 | return [ 30 | DefaultInfo(files = depset([output_jar])), 31 | compilation_provider, 32 | ] 33 | 34 | custom_library_with_bootclasspath = rule( 35 | implementation = _impl, 36 | outputs = { 37 | "my_output": "lib%{name}.jar", 38 | }, 39 | attrs = { 40 | "srcs": attr.label_list(allow_files = [".java"]), 41 | "sourcepath": attr.label_list(allow_files = [".jar"]), 42 | "bootclasspath": attr.label(), 43 | }, 44 | toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], 45 | fragments = ["java"], 46 | ) 47 | -------------------------------------------------------------------------------- /test/java/testutil/rules/custom_library_with_custom_output_source_jar.bzl: -------------------------------------------------------------------------------- 1 | """Custom rule to test java_common.compile() with a custom output source jar""" 2 | 3 | load("//java/common:java_common.bzl", "java_common") 4 | load("//java/common:java_semantics.bzl", "semantics") 5 | 6 | def _impl(ctx): 7 | output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") 8 | output_source_jar = ctx.actions.declare_file("lib" + ctx.label.name + "-mysrc.jar") 9 | compilation_provider = java_common.compile( 10 | ctx, 11 | source_jars = ctx.files.srcs, 12 | output = output_jar, 13 | output_source_jar = output_source_jar, 14 | java_toolchain = semantics.find_java_toolchain(ctx), 15 | ) 16 | return [ 17 | DefaultInfo( 18 | files = depset([output_source_jar]), 19 | ), 20 | compilation_provider, 21 | ] 22 | 23 | custom_library_with_custom_output_source_jar = rule( 24 | implementation = _impl, 25 | attrs = { 26 | "srcs": attr.label_list(allow_files = [".jar"]), 27 | }, 28 | toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], 29 | fragments = ["java"], 30 | ) 31 | -------------------------------------------------------------------------------- /test/java/testutil/rules/custom_library_with_exports.bzl: -------------------------------------------------------------------------------- 1 | """Helper rule for testing compilation with `exports`""" 2 | 3 | load("//java/common:java_common.bzl", "java_common") 4 | load("//java/common:java_semantics.bzl", "semantics") 5 | 6 | def _custom_library_with_exports_impl(ctx): 7 | output_name = ( 8 | ctx.label.name + "/" + ctx.attr.output_name + ".jar" 9 | ) if ctx.attr.output_name else "lib" + ctx.label.name + ".jar" 10 | output_jar = ctx.actions.declare_file(output_name) 11 | compilation_provider = java_common.compile( 12 | ctx, 13 | source_files = ctx.files.srcs, 14 | exports = [export[java_common.provider] for export in ctx.attr.exports], 15 | output = output_jar, 16 | java_toolchain = semantics.find_java_toolchain(ctx), 17 | ) 18 | return [DefaultInfo(files = depset([output_jar])), compilation_provider] 19 | 20 | custom_library_with_exports = rule( 21 | _custom_library_with_exports_impl, 22 | attrs = { 23 | "srcs": attr.label_list(allow_files = [".java"]), 24 | "exports": attr.label_list(), 25 | "output_name": attr.string(), 26 | }, 27 | toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], 28 | fragments = ["java"], 29 | ) 30 | -------------------------------------------------------------------------------- /test/java/testutil/rules/custom_library_with_named_outputs.bzl: -------------------------------------------------------------------------------- 1 | """Custom rule to test that source jar names are derived from the output jar""" 2 | 3 | load("//java/common:java_common.bzl", "java_common") 4 | load("//java/common:java_semantics.bzl", "semantics") 5 | 6 | def _impl(ctx): 7 | output_jar = ctx.actions.declare_file(ctx.attr.name + "/amazing.jar") 8 | other_output_jar = ctx.actions.declare_file(ctx.attr.name + "/wonderful.jar") 9 | deps = [dep[java_common.provider] for dep in ctx.attr.deps] 10 | compilation_provider = java_common.compile( 11 | ctx, 12 | source_files = ctx.files.srcs, 13 | output = output_jar, 14 | deps = deps, 15 | java_toolchain = semantics.find_java_toolchain(ctx), 16 | ) 17 | other_compilation_provider = java_common.compile( 18 | ctx, 19 | source_files = ctx.files.srcs, 20 | output = other_output_jar, 21 | deps = deps, 22 | java_toolchain = semantics.find_java_toolchain(ctx), 23 | ) 24 | result_provider = java_common.merge([compilation_provider, other_compilation_provider]) 25 | return [ 26 | DefaultInfo( 27 | files = depset([output_jar]), 28 | ), 29 | result_provider, 30 | ] 31 | 32 | custom_library_with_named_outputs = rule( 33 | implementation = _impl, 34 | attrs = { 35 | "srcs": attr.label_list(allow_files = [".java"]), 36 | "deps": attr.label_list(), 37 | }, 38 | toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], 39 | fragments = ["java"], 40 | ) 41 | -------------------------------------------------------------------------------- /test/java/testutil/rules/custom_library_with_sourcepaths.bzl: -------------------------------------------------------------------------------- 1 | """Helper rule for testing compilation with `sourcepath`s""" 2 | 3 | load("//java/common:java_common.bzl", "java_common") 4 | load("//java/common:java_semantics.bzl", "semantics") 5 | 6 | def _custom_library_with_sourcepaths_impl(ctx): 7 | output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") 8 | compilation_provider = java_common.compile( 9 | ctx, 10 | source_files = ctx.files.srcs, 11 | output = output_jar, 12 | sourcepath = ctx.files.sourcepath, 13 | java_toolchain = semantics.find_java_toolchain(ctx), 14 | ) 15 | return [DefaultInfo(files = depset([output_jar])), compilation_provider] 16 | 17 | custom_library_with_sourcepaths = rule( 18 | _custom_library_with_sourcepaths_impl, 19 | attrs = { 20 | "srcs": attr.label_list(allow_files = [".java"]), 21 | "sourcepath": attr.label_list(allow_files = [".jar"]), 22 | }, 23 | toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], 24 | fragments = ["java"], 25 | ) 26 | -------------------------------------------------------------------------------- /test/java/testutil/rules/custom_library_with_strict_deps.bzl: -------------------------------------------------------------------------------- 1 | """Helper rule for testing compilation with default parameter values""" 2 | 3 | load("//java/common:java_common.bzl", "java_common") 4 | load("//java/common:java_semantics.bzl", "semantics") 5 | 6 | def _custom_library_impl(ctx): 7 | output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") 8 | compilation_provider = java_common.compile( 9 | ctx, 10 | output = output_jar, 11 | strict_deps = ctx.attr.strict_deps, 12 | java_toolchain = semantics.find_java_toolchain(ctx), 13 | ) 14 | return [DefaultInfo(files = depset([output_jar])), compilation_provider] 15 | 16 | custom_library_with_strict_deps = rule( 17 | _custom_library_impl, 18 | attrs = { 19 | "strict_deps": attr.string(), 20 | }, 21 | toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], 22 | fragments = ["java"], 23 | ) 24 | -------------------------------------------------------------------------------- /test/java/testutil/rules/custom_library_with_wrong_plugins_type.bzl: -------------------------------------------------------------------------------- 1 | """Custom rule to test java_common.compile(plugins = ...) expects JavaPluginInfo""" 2 | 3 | load("//java:defs.bzl", "JavaInfo", "java_common") 4 | load("//java/common:java_semantics.bzl", "semantics") 5 | 6 | def _impl(ctx): 7 | output_jar = ctx.actions.declare_file("lib" + ctx.label.name + ".jar") 8 | return java_common.compile( 9 | ctx, 10 | source_files = ctx.files.srcs, 11 | plugins = [p[JavaInfo] for p in ctx.attr.deps], 12 | output = output_jar, 13 | java_toolchain = semantics.find_java_toolchain(ctx), 14 | ) 15 | 16 | custom_library_with_wrong_plugins_type = rule( 17 | implementation = _impl, 18 | attrs = { 19 | "srcs": attr.label_list(allow_files = [".java"]), 20 | "deps": attr.label_list(), 21 | }, 22 | toolchains = [semantics.JAVA_TOOLCHAIN_TYPE], 23 | fragments = ["java"], 24 | ) 25 | -------------------------------------------------------------------------------- /test/java/testutil/rules/custom_plugin.bzl: -------------------------------------------------------------------------------- 1 | """Custom rule to test the JavaPluginInfo provider""" 2 | 3 | load("//java/common:java_info.bzl", "JavaInfo") 4 | load( 5 | "//java/common:java_plugin_info.bzl", 6 | "JavaPluginInfo", 7 | ) 8 | 9 | def _impl(ctx): 10 | output_jar = ctx.actions.declare_file(ctx.label.name + "/lib.jar") 11 | ctx.actions.write(output_jar, "") 12 | dep = JavaInfo( 13 | output_jar = output_jar, 14 | compile_jar = None, 15 | deps = [d[JavaInfo] for d in ctx.attr.deps], 16 | ) 17 | data = depset(ctx.files.data) if ctx.attr.data_as_depset else ctx.files.data 18 | return [JavaPluginInfo( 19 | runtime_deps = [dep], 20 | processor_class = ctx.attr.processor_class, 21 | data = data, 22 | generates_api = ctx.attr.generates_api, 23 | )] 24 | 25 | custom_plugin = rule( 26 | implementation = _impl, 27 | attrs = { 28 | "deps": attr.label_list(), 29 | "processor_class": attr.string(), 30 | "data": attr.label_list(allow_files = True), 31 | "generates_api": attr.bool(default = False), 32 | "data_as_depset": attr.bool(default = False), 33 | }, 34 | ) 35 | -------------------------------------------------------------------------------- /test/java/testutil/rules/forward_java_info.bzl: -------------------------------------------------------------------------------- 1 | """Custom rule to forward a JavaInfo""" 2 | 3 | load("//java/common:java_info.bzl", "JavaInfo") 4 | 5 | def _impl(ctx): 6 | dep_params = ctx.attr.dep[JavaInfo] 7 | return [dep_params] 8 | 9 | java_info_forwarding_rule = rule(_impl, attrs = {"dep": attr.label()}) 10 | -------------------------------------------------------------------------------- /test/java/testutil/rules/forward_java_runtime_info.bzl: -------------------------------------------------------------------------------- 1 | """Helper rule to test java_runtime and JavaRuntimeInfo""" 2 | 3 | load("//java/common:java_common.bzl", "java_common") 4 | 5 | def _impl(ctx): 6 | return ctx.attr.java_runtime[java_common.JavaRuntimeInfo] 7 | 8 | java_runtime_info_forwarding_rule = rule( 9 | _impl, 10 | attrs = { 11 | "java_runtime": attr.label(), 12 | }, 13 | ) 14 | -------------------------------------------------------------------------------- /test/java/testutil/rules/wrap_java_info.bzl: -------------------------------------------------------------------------------- 1 | """Custom rule to test wrapping of the JavaInfo provider""" 2 | 3 | load("//java/common:java_info.bzl", "JavaInfo") 4 | 5 | JavaInfoWrappingInfo = provider( 6 | "Simple provider to wrap a JavaInfo", 7 | fields = ["p"], 8 | ) 9 | 10 | def _impl(ctx): 11 | dep_params = ctx.attr.dep[JavaInfo] 12 | return [JavaInfoWrappingInfo(p = dep_params)] 13 | 14 | java_info_wrapping_rule = rule(_impl, attrs = {"dep": attr.label()}) 15 | -------------------------------------------------------------------------------- /test/java/toolchains/BUILD: -------------------------------------------------------------------------------- 1 | load(":java_runtime_tests.bzl", "java_runtime_tests") 2 | load(":java_toolchain_tests.bzl", "java_toolchain_tests") 3 | 4 | package(default_applicable_licenses = ["@rules_java//:license"]) 5 | 6 | java_runtime_tests(name = "java_runtime_tests") 7 | 8 | java_toolchain_tests(name = "java_toolchain_tests") 9 | -------------------------------------------------------------------------------- /test/java/toolchains/java_toolchain_tests.bzl: -------------------------------------------------------------------------------- 1 | """Tests for the java_toolchain rule""" 2 | 3 | load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") 4 | load("@rules_testing//lib:util.bzl", "util") 5 | load("//java/toolchains:java_runtime.bzl", "java_runtime") 6 | load("//java/toolchains:java_toolchain.bzl", "java_toolchain") 7 | load("//test/java/testutil:java_toolchain_info_subject.bzl", "java_toolchain_info_subject") 8 | 9 | def _declare_java_toolchain(*, name, **kwargs): 10 | if "java_runtime" not in kwargs: 11 | kwargs["java_runtime"] = name + "/runtime" 12 | java_runtime(name = name + "/runtime") 13 | util.helper_target( 14 | java_toolchain, 15 | name = name, 16 | genclass = [kwargs.get("genclass", "default_genclass.jar")], 17 | jacocorunner = kwargs.get("jacocorunner", None), 18 | javabuilder = [kwargs.get("javabuilder", "default_javabuilder.jar")], 19 | java_runtime = kwargs["java_runtime"], 20 | ijar = [kwargs.get("ijar", "default_ijar.jar")], 21 | singlejar = [kwargs.get("singlejar", "default_singlejar.jar")], 22 | ) 23 | 24 | def _test_jacocorunner(name): 25 | _declare_java_toolchain( 26 | name = name + "/java_toolchain", 27 | jacocorunner = "myjacocorunner.jar", 28 | ) 29 | 30 | analysis_test( 31 | name = name, 32 | impl = _test_jacocorunner_impl, 33 | target = name + "/java_toolchain", 34 | ) 35 | 36 | def _test_jacocorunner_impl(env, target): 37 | assert_toolchain = java_toolchain_info_subject.from_target(env, target) 38 | 39 | assert_toolchain.jacocorunner().short_path_equals("{package}/myjacocorunner.jar") 40 | 41 | def java_toolchain_tests(name): 42 | test_suite( 43 | name = name, 44 | tests = [ 45 | _test_jacocorunner, 46 | ], 47 | ) 48 | -------------------------------------------------------------------------------- /test/repo/.bazelrc: -------------------------------------------------------------------------------- 1 | build:bzlmod --experimental_enable_bzlmod 2 | 3 | common --incompatible_disallow_empty_glob 4 | 5 | # Enable modern C++ features, for compiling java_tools from source 6 | build --cxxopt=-std=c++17 7 | build --host_cxxopt=-std=c++17 8 | -------------------------------------------------------------------------------- /test/repo/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load("@rules_java//java:defs.bzl", "java_binary", "java_library", "java_test") # copybara-use-repo-external-label 2 | load("@rules_java//toolchains:default_java_toolchain.bzl", "NONPREBUILT_TOOLCHAIN_CONFIGURATION", "default_java_toolchain") # copybara-use-repo-external-label 3 | load("@rules_shell//shell:sh_test.bzl", "sh_test") 4 | 5 | package(default_applicable_licenses = ["@rules_java//:license"]) 6 | 7 | java_library( 8 | name = "lib", 9 | srcs = ["src/Main.java"], 10 | ) 11 | 12 | java_binary( 13 | name = "bin", 14 | main_class = "Main", 15 | runtime_deps = [":lib"], 16 | ) 17 | 18 | java_test( 19 | name = "MyTest", 20 | srcs = ["src/MyTest.java"], 21 | data = [ 22 | "src/data.txt", 23 | ], 24 | deps = [ 25 | "@my_jar//jar", 26 | "@rules_java//java/runfiles", 27 | ], 28 | ) 29 | 30 | genrule( 31 | name = "MakeVarGenruleTest", 32 | outs = ["MakeVarGenruleTestSuccess"], 33 | cmd = "test -f $(JAVA) && test -d $(JAVABASE) && touch $@", 34 | toolchains = ["@rules_java//toolchains:current_java_runtime"], 35 | tools = ["@rules_java//toolchains:current_java_runtime"], 36 | ) 37 | 38 | sh_test( 39 | name = "MakeVarTest", 40 | srcs = ["src/MakeVarTest.sh"], 41 | data = [ 42 | "MakeVarGenruleTestSuccess", 43 | "@rules_java//toolchains:current_java_runtime", 44 | ], 45 | env = { 46 | "JAVA_ROOTPATH": "$(JAVA_ROOTPATH)", 47 | "JAVABASE_ROOTPATH": "$(JAVABASE_ROOTPATH)", 48 | }, 49 | toolchains = ["@rules_java//toolchains:current_java_runtime"], 50 | ) 51 | 52 | default_java_toolchain( 53 | name = "my_funky_toolchain", 54 | bootclasspath = ["@bazel_tools//tools/jdk:platformclasspath"], 55 | configuration = NONPREBUILT_TOOLCHAIN_CONFIGURATION, 56 | ) 57 | -------------------------------------------------------------------------------- /test/repo/MODULE.bazel: -------------------------------------------------------------------------------- 1 | module(name = "integration_test_repo") 2 | 3 | bazel_dep(name = "rules_java", version = "7.5.0") 4 | archive_override( 5 | module_name = "rules_java", 6 | urls = [ 7 | "file:///tmp/rules_java-HEAD.tar.gz", 8 | "file:///C:/b/rules_java-HEAD.tar.gz", 9 | ], 10 | ) 11 | 12 | http_jar = use_repo_rule("@rules_java//java:http_jar.bzl", "http_jar") 13 | 14 | http_jar( 15 | name = "my_jar", 16 | urls = [ 17 | "file:///tmp/my_jar.jar", 18 | "file:///C:/b/my_jar.jar", 19 | ], 20 | ) 21 | 22 | java_toolchains = use_extension("@rules_java//java:extensions.bzl", "toolchains") 23 | use_repo( 24 | java_toolchains, 25 | "local_jdk", 26 | "remote_java_tools", 27 | "remote_java_tools_darwin_arm64", 28 | "remote_java_tools_darwin_x86_64", 29 | "remote_java_tools_linux", 30 | "remote_java_tools_windows", 31 | "remotejdk11_linux", 32 | "remotejdk11_linux_aarch64", 33 | "remotejdk11_linux_ppc64le", 34 | "remotejdk11_linux_s390x", 35 | "remotejdk11_macos", 36 | "remotejdk11_macos_aarch64", 37 | "remotejdk11_win", 38 | "remotejdk11_win_arm64", 39 | "remotejdk17_linux", 40 | "remotejdk17_linux_s390x", 41 | "remotejdk17_macos", 42 | "remotejdk17_macos_aarch64", 43 | "remotejdk17_win", 44 | "remotejdk17_win_arm64", 45 | "remotejdk21_linux", 46 | "remotejdk21_linux_riscv64", 47 | "remotejdk21_macos", 48 | "remotejdk21_macos_aarch64", 49 | "remotejdk21_win", 50 | ) 51 | 52 | register_toolchains("//:all") 53 | 54 | bazel_dep(name = "rules_shell", version = "0.4.0", dev_dependency = True) 55 | -------------------------------------------------------------------------------- /test/repo/WORKSPACE: -------------------------------------------------------------------------------- 1 | workspace(name = "integration_test_repo") 2 | 3 | local_repository( 4 | name = "rules_java", 5 | path = "../../", 6 | ) 7 | 8 | load("@rules_java//java:rules_java_deps.bzl", "rules_java_dependencies") 9 | 10 | rules_java_dependencies() 11 | 12 | load("@bazel_features//:deps.bzl", "bazel_features_deps") 13 | 14 | bazel_features_deps() 15 | 16 | load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_bazel_features") # buildifier: disable=bzl-visibility 17 | 18 | proto_bazel_features(name = "proto_bazel_features") 19 | 20 | register_toolchains("//:all") 21 | 22 | load("@rules_java//java:repositories.bzl", "rules_java_toolchains") 23 | 24 | rules_java_toolchains() 25 | 26 | load("@rules_java//java:http_jar.bzl", "http_jar") 27 | 28 | http_jar( 29 | name = "my_jar", 30 | urls = [ 31 | "file:///tmp/my_jar.jar", 32 | "file:///C:/b/my_jar.jar", 33 | ], 34 | ) 35 | 36 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") 37 | 38 | http_archive( 39 | name = "rules_shell", 40 | sha256 = "3e114424a5c7e4fd43e0133cc6ecdfe54e45ae8affa14fadd839f29901424043", 41 | strip_prefix = "rules_shell-0.4.0", 42 | url = "https://github.com/bazelbuild/rules_shell/releases/download/v0.4.0/rules_shell-v0.4.0.tar.gz", 43 | ) 44 | 45 | load("@rules_shell//shell:repositories.bzl", "rules_shell_dependencies", "rules_shell_toolchains") 46 | 47 | rules_shell_dependencies() 48 | 49 | rules_shell_toolchains() 50 | -------------------------------------------------------------------------------- /test/repo/WORKSPACE.bzlmod: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bazelbuild/rules_java/fecb9fbe5e5417997bb8dda24c1873a130baf7d4/test/repo/WORKSPACE.bzlmod -------------------------------------------------------------------------------- /test/repo/setup.bat: -------------------------------------------------------------------------------- 1 | cd ../../ 2 | bazel build //distro:all //test/testdata:my_jar 3 | cp -f ./bazel-bin/distro/*.tar.gz C:/b/rules_java-HEAD.tar.gz 4 | cp -f bazel-bin/test/testdata/libmy_jar.jar C:/b/my_jar.jar 5 | -------------------------------------------------------------------------------- /test/repo/setup.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | cd ../../ 4 | bazel build //distro:all //test/testdata:my_jar 5 | cp -f bazel-bin/distro/rules_java-*.tar.gz /tmp/rules_java-HEAD.tar.gz 6 | cp -f bazel-bin/test/testdata/libmy_jar.jar /tmp/my_jar.jar 7 | 8 | -------------------------------------------------------------------------------- /test/repo/src/Main.java: -------------------------------------------------------------------------------- 1 | public class Main {} 2 | -------------------------------------------------------------------------------- /test/repo/src/MakeVarTest.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | if [ ! -x "$JAVABASE_ROOTPATH/bin/java" ]; then 4 | echo '$JAVABASE_RUNFILES does not point to a working JRE' && exit 1 5 | fi 6 | 7 | echo $JAVA_ROOTPATH 8 | if [ ! -x "$JAVA_ROOTPATH" ]; then 9 | echo '$JAVA_ROOTPATH does not exist' && exit 1 10 | fi -------------------------------------------------------------------------------- /test/repo/src/MyTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.assertEquals; 2 | import static org.junit.Assert.assertTrue; 3 | 4 | import com.google.devtools.build.runfiles.AutoBazelRepository; 5 | import com.google.devtools.build.runfiles.Runfiles; 6 | import java.io.IOException; 7 | import java.nio.file.Files; 8 | import java.nio.file.Path; 9 | import java.nio.file.Paths; 10 | import mypackage.MyLib; 11 | import org.junit.Test; 12 | import org.junit.runner.RunWith; 13 | import org.junit.runners.JUnit4; 14 | 15 | @RunWith(JUnit4.class) 16 | @AutoBazelRepository 17 | public class MyTest { 18 | @Test 19 | public void main() { 20 | assertEquals(MyLib.myStr(), "my_string"); 21 | } 22 | 23 | @Test 24 | public void runfiles() throws IOException { 25 | Runfiles runfiles = Runfiles.preload().withSourceRepository(AutoBazelRepository_MyTest.NAME); 26 | Path path = Paths.get(runfiles.rlocation("integration_test_repo/src/data.txt")); 27 | assertTrue(Files.exists(path)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/repo/src/data.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bazelbuild/rules_java/fecb9fbe5e5417997bb8dda24c1873a130baf7d4/test/repo/src/data.txt -------------------------------------------------------------------------------- /test/repositories.bzl: -------------------------------------------------------------------------------- 1 | """Test dependencies for rules_java.""" 2 | 3 | load("@bazel_skylib//lib:modules.bzl", "modules") 4 | 5 | # TODO: Use http_jar from //java:http_jar.bzl once it doesn't refert to cache.bzl from @bazel_tools 6 | # anymore, which isn't available in Bazel 6. 7 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") 8 | 9 | def test_repositories(): 10 | http_file( 11 | name = "guava", 12 | url = "https://repo1.maven.org/maven2/com/google/guava/guava/33.3.1-jre/guava-33.3.1-jre.jar", 13 | integrity = "sha256-S/Dixa+ORSXJbo/eF6T3MH+X+EePEcTI41oOMpiuTpA=", 14 | downloaded_file_path = "guava.jar", 15 | ) 16 | http_file( 17 | name = "truth", 18 | url = "https://repo1.maven.org/maven2/com/google/truth/truth/1.4.4/truth-1.4.4.jar", 19 | integrity = "sha256-Ushs3a3DG8hFfB4VaJ/Gt14ul84qg9i1S3ldVW1In4w=", 20 | downloaded_file_path = "truth.jar", 21 | ) 22 | 23 | test_repositories_ext = modules.as_extension(test_repositories) 24 | -------------------------------------------------------------------------------- /test/testdata/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load("//java:java_library.bzl", "java_library") 2 | 3 | package(default_applicable_licenses = ["@rules_java//:license"]) 4 | 5 | # Make a sample jar for the http_jar test. 6 | java_library( 7 | name = "my_jar", 8 | srcs = ["MyLib.java"], 9 | ) 10 | -------------------------------------------------------------------------------- /test/testdata/MyLib.java: -------------------------------------------------------------------------------- 1 | package mypackage; 2 | 3 | /** A simple library for the http_jar test. */ 4 | public class MyLib { 5 | public static String myStr() { 6 | return "my_string"; 7 | } 8 | } 9 | 10 | -------------------------------------------------------------------------------- /test/toolchains/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load(":bootclasspath_tests.bzl", "bootclasspath_tests") 2 | 3 | package(default_applicable_licenses = ["@rules_java//:license"]) 4 | 5 | bootclasspath_tests( 6 | name = "bootclasspath_tests", 7 | ) 8 | -------------------------------------------------------------------------------- /test/toolchains/bootclasspath_tests.bzl: -------------------------------------------------------------------------------- 1 | """Tests for the bootclasspath rule.""" 2 | 3 | load("@rules_testing//lib:analysis_test.bzl", "analysis_test", "test_suite") 4 | load("@rules_testing//lib:truth.bzl", "subjects") 5 | load("//java/common:java_common.bzl", "java_common") 6 | 7 | def _test_utf_8_environment(name): 8 | analysis_test( 9 | name = name, 10 | impl = _test_utf_8_environment_impl, 11 | target = Label("//toolchains:platformclasspath"), 12 | ) 13 | 14 | def _test_utf_8_environment_impl(env, target): 15 | for action in target.actions: 16 | env_subject = env.expect.where(action = action).that_dict(action.env) 17 | env_subject.keys().contains("LC_CTYPE") 18 | env_subject.get("LC_CTYPE", factory = subjects.str).contains("UTF-8") 19 | 20 | def _test_incompatible_language_version_bootclasspath_disabled(name): 21 | analysis_test( 22 | name = name, 23 | impl = _test_incompatible_language_version_bootclasspath_disabled_impl, 24 | target = Label("//toolchains:platformclasspath"), 25 | config_settings = { 26 | "//command_line_option:java_language_version": "11", 27 | "//command_line_option:java_runtime_version": "remotejdk_17", 28 | str(Label("//toolchains:incompatible_language_version_bootclasspath")): False, 29 | }, 30 | ) 31 | 32 | def _test_incompatible_language_version_bootclasspath_disabled_impl(env, target): 33 | system_path = target[java_common.BootClassPathInfo]._system_path 34 | env.expect.that_str(system_path).contains("remotejdk17_") 35 | 36 | def _test_incompatible_language_version_bootclasspath_enabled_versioned(name): 37 | analysis_test( 38 | name = name, 39 | impl = _test_incompatible_language_version_bootclasspath_enabled_versioned_impl, 40 | target = Label("//toolchains:platformclasspath"), 41 | config_settings = { 42 | "//command_line_option:java_language_version": "11", 43 | "//command_line_option:java_runtime_version": "remotejdk_17", 44 | str(Label("//toolchains:incompatible_language_version_bootclasspath")): True, 45 | }, 46 | ) 47 | 48 | def _test_incompatible_language_version_bootclasspath_enabled_versioned_impl(env, target): 49 | system_path = target[java_common.BootClassPathInfo]._system_path 50 | env.expect.that_str(system_path).contains("remotejdk11_") 51 | 52 | def _test_incompatible_language_version_bootclasspath_enabled_unversioned(name): 53 | analysis_test( 54 | name = name, 55 | impl = _test_incompatible_language_version_bootclasspath_enabled_unversioned_impl, 56 | target = Label("//toolchains:platformclasspath"), 57 | config_settings = { 58 | "//command_line_option:java_language_version": "11", 59 | "//command_line_option:java_runtime_version": "local_jdk", 60 | str(Label("//toolchains:incompatible_language_version_bootclasspath")): True, 61 | }, 62 | ) 63 | 64 | def _test_incompatible_language_version_bootclasspath_enabled_unversioned_impl(env, target): 65 | system_path = target[java_common.BootClassPathInfo]._system_path 66 | env.expect.that_str(system_path).contains("local_jdk") 67 | 68 | def bootclasspath_tests(name): 69 | test_suite( 70 | name = name, 71 | tests = [ 72 | _test_utf_8_environment, 73 | _test_incompatible_language_version_bootclasspath_disabled, 74 | _test_incompatible_language_version_bootclasspath_enabled_versioned, 75 | _test_incompatible_language_version_bootclasspath_enabled_unversioned, 76 | ], 77 | ) 78 | -------------------------------------------------------------------------------- /toolchains/fail_rule.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2020 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """A rule than fails during analysis.""" 16 | 17 | def _fail_rule_impl(ctx): 18 | if ctx.attr.header: 19 | fail("%s %s" % (ctx.attr.header, ctx.attr.message)) 20 | else: 21 | fail(ctx.attr.message) 22 | 23 | fail_rule = rule( 24 | doc = "A rule that fails during analysis.", 25 | implementation = _fail_rule_impl, 26 | attrs = { 27 | "header": attr.string( 28 | doc = "Header of the message.", 29 | ), 30 | "message": attr.string( 31 | mandatory = True, 32 | doc = "Message to display.", 33 | ), 34 | }, 35 | ) 36 | -------------------------------------------------------------------------------- /toolchains/java_toolchain_alias.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2019 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Experimental re-implementations of Java toolchain aliases using toolchain resolution.""" 16 | 17 | load("//java/common:java_common.bzl", "java_common") 18 | 19 | def _java_runtime_alias(ctx): 20 | """An experimental implementation of java_runtime_alias using toolchain resolution.""" 21 | toolchain_info = ctx.toolchains["@bazel_tools//tools/jdk:runtime_toolchain_type"] 22 | toolchain = toolchain_info.java_runtime 23 | return [ 24 | toolchain_info, 25 | toolchain, 26 | platform_common.TemplateVariableInfo({ 27 | "JAVA": str(toolchain.java_executable_exec_path), 28 | "JAVABASE": str(toolchain.java_home), 29 | "JAVA_ROOTPATH": str(toolchain.java_executable_runfiles_path), 30 | "JAVABASE_ROOTPATH": str(toolchain.java_home_runfiles_path), 31 | }), 32 | # See b/65239471 for related discussion of handling toolchain runfiles/data. 33 | DefaultInfo( 34 | runfiles = ctx.runfiles(transitive_files = toolchain.files), 35 | files = toolchain.files, 36 | ), 37 | ] 38 | 39 | java_runtime_alias = rule( 40 | implementation = _java_runtime_alias, 41 | toolchains = ["@bazel_tools//tools/jdk:runtime_toolchain_type"], 42 | ) 43 | 44 | def _java_host_runtime_alias(ctx): 45 | """An experimental implementation of java_host_runtime_alias using toolchain resolution.""" 46 | runtime = ctx.attr._runtime 47 | java_runtime = runtime[java_common.JavaRuntimeInfo] 48 | template_variable_info = runtime[platform_common.TemplateVariableInfo] 49 | toolchain_info = platform_common.ToolchainInfo(java_runtime = java_runtime) 50 | return [ 51 | java_runtime, 52 | template_variable_info, 53 | toolchain_info, 54 | runtime[DefaultInfo], 55 | ] 56 | 57 | java_host_runtime_alias = rule( 58 | implementation = _java_host_runtime_alias, 59 | attrs = { 60 | "_runtime": attr.label( 61 | default = Label("//toolchains:current_java_runtime"), 62 | providers = [ 63 | java_common.JavaRuntimeInfo, 64 | platform_common.TemplateVariableInfo, 65 | ], 66 | cfg = "exec", 67 | ), 68 | }, 69 | provides = [ 70 | java_common.JavaRuntimeInfo, 71 | platform_common.TemplateVariableInfo, 72 | platform_common.ToolchainInfo, 73 | ], 74 | ) 75 | 76 | def _java_runtime_transition_impl(_settings, attr): 77 | return {"//command_line_option:java_runtime_version": attr.runtime_version} 78 | 79 | _java_runtime_transition = transition( 80 | implementation = _java_runtime_transition_impl, 81 | inputs = [], 82 | outputs = ["//command_line_option:java_runtime_version"], 83 | ) 84 | 85 | java_runtime_version_alias = rule( 86 | implementation = _java_runtime_alias, 87 | toolchains = ["@bazel_tools//tools/jdk:runtime_toolchain_type"], 88 | attrs = { 89 | "runtime_version": attr.string(mandatory = True), 90 | "_allowlist_function_transition": attr.label( 91 | default = "@bazel_tools//tools/allowlists/function_transition_allowlist", 92 | ), 93 | }, 94 | cfg = _java_runtime_transition, 95 | ) 96 | 97 | def _java_toolchain_alias(ctx): 98 | """An experimental implementation of java_toolchain_alias using toolchain resolution.""" 99 | toolchain_info = ctx.toolchains["@bazel_tools//tools/jdk:toolchain_type"] 100 | toolchain = toolchain_info.java 101 | 102 | return [ 103 | toolchain_info, 104 | toolchain, 105 | ] 106 | 107 | java_toolchain_alias = rule( 108 | implementation = _java_toolchain_alias, 109 | toolchains = ["@bazel_tools//tools/jdk:toolchain_type"], 110 | ) 111 | -------------------------------------------------------------------------------- /toolchains/jdk_build_file.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2023 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """A templated BUILD file for Java repositories.""" 16 | 17 | JDK_BUILD_TEMPLATE = """load("@rules_java//java/toolchains:java_runtime.bzl", "java_runtime") 18 | 19 | package(default_visibility = ["//visibility:public"]) 20 | 21 | exports_files(["WORKSPACE", "BUILD.bazel"]) 22 | 23 | filegroup( 24 | name = "jre", 25 | srcs = glob( 26 | [ 27 | "jre/bin/**", 28 | "jre/lib/**", 29 | ], 30 | allow_empty = True, 31 | # In some configurations, Java browser plugin is considered harmful and 32 | # common antivirus software blocks access to npjp2.dll interfering with Bazel, 33 | # so do not include it in JRE on Windows. 34 | exclude = ["jre/bin/plugin2/**"], 35 | ), 36 | ) 37 | 38 | filegroup( 39 | name = "jdk-bin", 40 | srcs = glob( 41 | ["bin/**"], 42 | # The JDK on Windows sometimes contains a directory called 43 | # "%systemroot%", which is not a valid label. 44 | exclude = ["**/*%*/**"], 45 | ), 46 | ) 47 | 48 | # This folder holds security policies. 49 | filegroup( 50 | name = "jdk-conf", 51 | srcs = glob( 52 | ["conf/**"], 53 | allow_empty = True, 54 | ), 55 | ) 56 | 57 | filegroup( 58 | name = "jdk-include", 59 | srcs = glob( 60 | ["include/**"], 61 | allow_empty = True, 62 | ), 63 | ) 64 | 65 | filegroup( 66 | name = "jdk-lib", 67 | srcs = glob( 68 | ["lib/**", "release"], 69 | allow_empty = True, 70 | exclude = [ 71 | "lib/missioncontrol/**", 72 | "lib/visualvm/**", 73 | ], 74 | ), 75 | ) 76 | 77 | java_runtime( 78 | name = "jdk", 79 | srcs = [ 80 | ":jdk-bin", 81 | ":jdk-conf", 82 | ":jdk-include", 83 | ":jdk-lib", 84 | ":jre", 85 | ], 86 | # Provide the 'java` binary explicitly so that the correct path is used by 87 | # Bazel even when the host platform differs from the execution platform. 88 | # Exactly one of the two globs will be empty depending on the host platform. 89 | # When --incompatible_disallow_empty_glob is enabled, each individual empty 90 | # glob will fail without allow_empty = True, even if the overall result is 91 | # non-empty. 92 | java = glob(["bin/java.exe", "bin/java"], allow_empty = True)[0], 93 | version = {RUNTIME_VERSION}, 94 | ) 95 | 96 | filegroup( 97 | name = "jdk-jmods", 98 | srcs = glob( 99 | ["jmods/**"], 100 | allow_empty = True, 101 | ), 102 | ) 103 | 104 | java_runtime( 105 | name = "jdk-with-jmods", 106 | srcs = [ 107 | ":jdk-bin", 108 | ":jdk-conf", 109 | ":jdk-include", 110 | ":jdk-lib", 111 | ":jdk-jmods", 112 | ":jre", 113 | ], 114 | java = glob(["bin/java.exe", "bin/java"], allow_empty = True)[0], 115 | version = {RUNTIME_VERSION}, 116 | ) 117 | """ 118 | -------------------------------------------------------------------------------- /toolchains/remote_java_repository.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2020 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Rules for importing JDKs from http archive. 16 | 17 | Rule remote_java_repository imports a JDK and creates toolchain definitions for it. 18 | """ 19 | 20 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") 21 | load("//toolchains:jdk_build_file.bzl", "JDK_BUILD_TEMPLATE") 22 | 23 | def _toolchain_config_impl(ctx): 24 | ctx.file("WORKSPACE", "workspace(name = \"{name}\")\n".format(name = ctx.name)) 25 | ctx.file("BUILD.bazel", ctx.attr.build_file) 26 | 27 | _toolchain_config = repository_rule( 28 | local = True, 29 | implementation = _toolchain_config_impl, 30 | attrs = { 31 | "build_file": attr.string(), 32 | }, 33 | ) 34 | 35 | def remote_java_repository(name, version, target_compatible_with = None, prefix = "remotejdk", **kwargs): 36 | """Imports a JDK from a http archive and creates runtime toolchain definitions for it. 37 | 38 | Register the toolchains defined by this macro via `register_toolchains("@//:all")`, where 39 | `` is the value of the `name` parameter. 40 | 41 | Toolchain resolution is determined with target_compatible_with 42 | parameter and constrained with --java_runtime_version flag either having value 43 | of "version" or "{prefix}_{version}" parameters. 44 | 45 | Args: 46 | name: A unique name for this rule. 47 | version: Version of the JDK imported. 48 | target_compatible_with: Target platform constraints (CPU and OS) for this JDK. 49 | prefix: Optional alternative prefix for configuration flag value used to determine this JDK. 50 | **kwargs: Refer to http_archive documentation 51 | """ 52 | http_archive( 53 | name = name, 54 | build_file_content = JDK_BUILD_TEMPLATE.format(RUNTIME_VERSION = version), 55 | **kwargs 56 | ) 57 | _toolchain_config( 58 | name = name + "_toolchain_config_repo", 59 | build_file = """ 60 | config_setting( 61 | name = "prefix_version_setting", 62 | values = {{"java_runtime_version": "{prefix}_{version}"}}, 63 | visibility = ["//visibility:private"], 64 | ) 65 | config_setting( 66 | name = "version_setting", 67 | values = {{"java_runtime_version": "{version}"}}, 68 | visibility = ["//visibility:private"], 69 | ) 70 | alias( 71 | name = "version_or_prefix_version_setting", 72 | actual = select({{ 73 | ":version_setting": ":version_setting", 74 | "//conditions:default": ":prefix_version_setting", 75 | }}), 76 | visibility = ["//visibility:private"], 77 | ) 78 | toolchain( 79 | name = "toolchain", 80 | target_compatible_with = {target_compatible_with}, 81 | target_settings = [":version_or_prefix_version_setting"], 82 | toolchain_type = "@bazel_tools//tools/jdk:runtime_toolchain_type", 83 | toolchain = "{toolchain}", 84 | ) 85 | toolchain( 86 | name = "bootstrap_runtime_toolchain", 87 | # These constraints are not required for correctness, but prevent fetches of remote JDK for 88 | # different architectures. As every Java compilation toolchain depends on a bootstrap runtime in 89 | # the same configuration, this constraint will not result in toolchain resolution failures. 90 | exec_compatible_with = {target_compatible_with}, 91 | target_settings = [":version_or_prefix_version_setting"], 92 | toolchain_type = "@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type", 93 | toolchain = "{toolchain}", 94 | ) 95 | """.format( 96 | prefix = prefix, 97 | version = version, 98 | target_compatible_with = target_compatible_with, 99 | toolchain = "@{repo}//:jdk".format(repo = name), 100 | ), 101 | ) 102 | -------------------------------------------------------------------------------- /toolchains/toolchain_utils.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2019 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Finds the Java toolchain. 17 | 18 | Returns the toolchain if enabled, and falls back to a toolchain constructed from 19 | legacy toolchain selection. 20 | """ 21 | 22 | load("//java/common:java_common.bzl", "java_common") 23 | 24 | def find_java_toolchain(ctx, target): 25 | """ 26 | Finds the Java toolchain. 27 | 28 | If the Java toolchain is in use, returns it. Otherwise, returns a Java 29 | toolchain derived from legacy toolchain selection. 30 | 31 | Args: 32 | ctx: The rule context for which to find a toolchain. 33 | target: A java_toolchain target (for legacy toolchain resolution). 34 | 35 | Returns: 36 | A JavaToolchainInfo. 37 | """ 38 | 39 | _ignore = [ctx] # buildifier: disable=unused-variable 40 | 41 | return target[java_common.JavaToolchainInfo] 42 | 43 | def find_java_runtime_toolchain(ctx, target): 44 | """ 45 | Finds the Java runtime. 46 | 47 | If the Java toolchain is in use, returns it. Otherwise, returns a Java 48 | runtime derived from legacy toolchain selection. 49 | 50 | Args: 51 | ctx: The rule context for which to find a toolchain. 52 | target: A java_runtime target (for legacy toolchain resolution). 53 | 54 | Returns: 55 | A JavaRuntimeInfo. 56 | """ 57 | 58 | _ignore = [ctx] # buildifier: disable=unused-variable 59 | 60 | return target[java_common.JavaRuntimeInfo] 61 | -------------------------------------------------------------------------------- /toolchains/utf8_environment.bzl: -------------------------------------------------------------------------------- 1 | # Copyright 2024 The Bazel Authors. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Determines the environment required for Java actions to support UTF-8. 17 | """ 18 | 19 | visibility("private") 20 | 21 | Utf8EnvironmentInfo = provider( 22 | doc = "The environment required for Java actions to support UTF-8.", 23 | fields = { 24 | "environment": "The environment to use for Java actions to support UTF-8.", 25 | }, 26 | ) 27 | 28 | # The default UTF-8 locale on all recent Linux distributions. It is also available in Cygwin and 29 | # MSYS2, but doesn't matter for determining the JVM's platform encoding on Windows, which always 30 | # uses the active code page. 31 | _DEFAULT_UTF8_ENVIRONMENT = Utf8EnvironmentInfo(environment = {"LC_CTYPE": "C.UTF-8"}) 32 | 33 | # macOS doesn't have the C.UTF-8 locale, but en_US.UTF-8 is available and works the same way. 34 | _MACOS_UTF8_ENVIRONMENT = Utf8EnvironmentInfo(environment = {"LC_CTYPE": "en_US.UTF-8"}) 35 | 36 | def _utf8_environment_impl(ctx): 37 | if ctx.target_platform_has_constraint(ctx.attr._macos_constraint[platform_common.ConstraintValueInfo]): 38 | return _MACOS_UTF8_ENVIRONMENT 39 | else: 40 | return _DEFAULT_UTF8_ENVIRONMENT 41 | 42 | utf8_environment = rule( 43 | _utf8_environment_impl, 44 | attrs = { 45 | "_macos_constraint": attr.label(default = "@platforms//os:macos"), 46 | }, 47 | doc = "Returns a suitable environment for Java actions to support UTF-8.", 48 | ) 49 | --------------------------------------------------------------------------------