vorburger
vorburger

Reputation: 3928

How to query Bazel for the (absolute) `JAVE_HOME` like path to the remote JDK of whatever Java Toolchain the workspace is configured to use?

How can one query Bazel to obtain the absolute path to the JDK which its Java Rules use? I'm aware that there can be several, and would like to obtain "the one it uses to run tests under".

In my project that's a remotejdk_21, and I gathered (with Bazel 7.0.2) it's in ~/.cache/bazel/_bazel_$USER/<hash>/external/remotejdk21_linux/, but due to that hash it's not fixed - so I'm looking for some bazel cquery (or whatever works) which returns that.

The point of this is that I would like to write a few lines of shell script which sets JAVA_HOME to that, and prepends it to PATH. This could help avoid some confusion in my project.

PS: This is a slightly different question than Query for Java toolchain details in Bazel, which was about obtaining the Java source level of a specific target; whereas this is for the absolute path to the workspaces's toolchain - which I don't see in the output of bazelisk cquery "@bazel_tools//tools/jdk:current_java_toolchain" --output starlark --starlark:expr "providers(target)['@@_builtins//:common/java/java_toolchain.bzl%JavaToolchainInfo']" - but there may be a way to somehow coax it out of that?

Upvotes: 0

Views: 258

Answers (1)

vorburger
vorburger

Reputation: 3928

I've been able to do this like this:

With this in e.g. bazel-java-tool-chain.bzl:

def format(target):
    runtime_infos = {k: v for k, v in providers(target).items() if k.endswith("JavaRuntimeInfo")}

    if len(runtime_infos) == 1:
        java_runtime_info = runtime_infos.values()[0]

        # https://bazel.build/rules/lib/providers/JavaRuntimeInfo
        return java_runtime_info.java_home

    fail("Unable to obtain JavaRuntimeInfo.")

and then:

$ bazel info output_base

$ bazelisk cquery @bazel_tools//tools/jdk:current_java_runtime \
    --output starlark --starlark:file tools/bazel-java-tool-chain/bazel-java-tool-chain.bzl

You have to concat the output of both above of above, and voilà that's where the JDK is.

Upvotes: 0

Related Questions