Read Bazel config from Java code

42 views
Skip to first unread message

Rafal Orlowski

unread,
Jun 11, 2024, 5:05:27 AMJun 11
to bazel-discuss
Hi,

I have java project that is built with Bazel. Now I want to add compilation flag which I can read from java code and do some conditional work upon it. How can I achieve it?

Best regards
Rafal Orlowski

Allan Clark

unread,
Jun 12, 2024, 12:04:16 AMJun 12
to bazel-discuss
This is a really open-ended question, but many here like a challenge.

To be a bit more precise, can you create a github project/repo that demonstrates what you’d like to do, where the config would be held, what parts would be changed by reading it?

Chances are, it’s easier to control both your Java code and the conditional work, and you may find yourself defining all possible targets, but conditionally selecting one as a dependency to get one of a few possible conditionals compiled.

Please share a repo showing the problem, and let us suggest a fix?  Mark it up with comments or however to describe what’s not quite what you need.

Allan

Prasanna Swaminathan

unread,
Jun 14, 2024, 7:38:14 PM (13 days ago) Jun 14
to bazel-discuss
This sounds analogous to Gradle's BuildConfig for Android. There is some prior art for that here, though you'll have to adapt it for your needs. A trivial example like

genrule(
    name = "build_config_base",
    outs = ["BuildConfig.java"],
    cmd = """
cat << EOF > $@
package com.example.app;

public class BuildConfig {
    public static final String TARGET = "$(TARGET)";
}
EOF
""",
)

java_library(
    name = "build_config",
    srcs = [":build_config_base"],
)

java_binary(
    name = "app",
    srcs = ["Main.java"],
    deps = [":build_config"],
    main_class = "com.example.app.Main",
)

Would allow you to set it/use it with, e.g. bazel build --define=TARGET=myapp. If you wanted to use it more broadly, you could wrap the genrule + java library in a macro.
Reply all
Reply to author
Forward
0 new messages