Matt Passell
Matt Passell

Reputation: 4749

How can I use the JAR tool with Bazel v0.19+?

Starting with Bazel v0.19, if you have Starlark (formerly known as "Skylark") code that references @bazel_tools//tools/jdk:jar, you see messages like this at build time:

WARNING: <trimmed-path>/external/bazel_tools/tools/jdk/BUILD:79:1: in alias rule @bazel_tools//tools/jdk:jar: target '@bazel_tools//tools/jdk:jar' depends on deprecated target '@local_jdk//:jar': Don't depend on targets in the JDK workspace; use @bazel_tools//tools/jdk:current_java_runtime instead (see https://github.com/bazelbuild/bazel/issues/5594)

I think I could make things work with @bazel_tools//tools/jdk:current_java_runtime if I wanted access to the java command, but I'm not sure what I'd need to do to get the jar tool to work. The contents of the linked GitHub issue didn't seem to address this particular problem.

Upvotes: 2

Views: 1309

Answers (2)

Matt Passell
Matt Passell

Reputation: 4749

Because my reference to the jar tool is inside a genrule within top-level macro, rather than a rule, I was unable to use the approach from Rodrigo's answer. I instead explicitly referenced the current_java_runtime toolchain and was then able to use the JAVABASE make variable as the base path for the jar tool.

native.genrule(
    name = genjar_rule,
    srcs = [<rules that create files being jar'd>],
    cmd = "some_script.sh $(JAVABASE)/bin/jar $@ $(SRCS)",
    tools = ["some_script.sh", "@bazel_tools//tools/jdk:current_java_runtime"],
    toolchains = ["@bazel_tools//tools/jdk:current_java_runtime"],
    outs = [<some outputs>]
)

Upvotes: 2

Rodrigo Queiro
Rodrigo Queiro

Reputation: 1336

I stumbled across a commit to Bazel that makes a similar adjustment to the Starlark java rules. It uses the following pattern: (I've edited the code somewhat)

# in the rule attrs:
    "_jdk": attr.label(
        default = Label("//tools/jdk:current_java_runtime"),
        providers = [java_common.JavaRuntimeInfo],
    ),

# then in the rule implementation:
    java_runtime = ctx.attr._jdk[java_common.JavaRuntimeInfo]
    jar_path = "%s/bin/jar" % java_runtime.java_home
     ctx.action(
         inputs = ctx.files._jdk + other inputs,
         outputs = [deploy_jar],
         command = "%s cmf %s" % (jar_path, input_files),
     )

Additionally, java is available at str(java_runtime.java_executable_exec_path) and javac at "%s/bin/javac" % java_runtime.java_home.

See also, a pull request with a simpler example.

Upvotes: 4

Related Questions