Skip to content

Instantly share code, notes, and snippets.

@fzakaria
Created November 7, 2024 17:47
Show Gist options
  • Save fzakaria/4e98f65be96cf7f8b13081e75d7a2bf8 to your computer and use it in GitHub Desktop.
Save fzakaria/4e98f65be96cf7f8b13081e75d7a2bf8 to your computer and use it in GitHub Desktop.
Bazel Starlark rule to create a JarIndex
def _jar_index_impl(ctx):
java_info = ctx.attr.src[JavaInfo]
java_runtime = ctx.attr._java_runtime[java_common.JavaRuntimeInfo]
java_home = java_runtime.java_home
jar_bin = "%s/bin/jar" % java_home
runtime_jars = " "
for jar in java_info.transitive_runtime_jars.to_list():
runtime_jars += jar.path + " "
cmds = [
"%s -i %s %s" % (jar_bin, java_info.java_outputs[0].class_jar.path, runtime_jars),
"cp %s %s" % (java_info.java_outputs[0].class_jar.path, ctx.outputs.index.path),
]
ctx.actions.run_shell(
inputs = [ java_info.java_outputs[0].class_jar] + java_info.transitive_runtime_jars.to_list(),
outputs = [ctx.outputs.index],
tools = java_runtime.files,
command = ";\n".join(cmds),
)
return [
DefaultInfo(files = depset([ctx.outputs.index])),
]
jar_index = rule(
implementation = _jar_index_impl,
attrs = {
"src": attr.label(
mandatory = True,
providers = [JavaInfo],
),
"_java_runtime": attr.label(
default = "@bazel_tools//tools/jdk:current_java_runtime",
providers = [java_common.JavaRuntimeInfo],
),
},
outputs = {"index": "%{name}_index.jar"},
)
@fzakaria
Copy link
Author

fzakaria commented Nov 7, 2024

Produces a INDEX.LIST file like so:

load("//:jar_index.bzl", "jar_index")

java_library(
    name = "A",
    srcs = ["A.java"],
)

java_library(
    name = "B",
    srcs = ["B.java"],
)

java_library(
    name = "Main",
    srcs = ["Main.java"],
    deps = [
        ":A",
        ":B",
    ]
)

jar_index(
    name = "Main_optimized",
    src = ":Main",
)
> unzip -c bazel-bin/src/Main_optimized_index.jar
Archive:  bazel-bin/src/Main_optimized_index.jar
  inflating: META-INF/INDEX.LIST
JarIndex-Version: 1.0

bazel-out/darwin_arm64-fastbuild/bin/src/libMain.jar
Main.class

bazel-out/darwin_arm64-fastbuild/bin/src/libA.jar
A.class

bazel-out/darwin_arm64-fastbuild/bin/src/libB.jar
B.class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment