packages feed

cabal-buck2-0.6.0.0: buck2/prelude/decls/java_rules.bzl

# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is dual-licensed under either the MIT license found in the
# LICENSE-MIT file in the root directory of this source tree or the Apache
# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
# of this source tree. You may select, at your option, one of the
# above-listed licenses.

# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
# but should be manually edited going forward. There may be some errors in
# the generated docs, and so those should be verified to be accurate and
# well-formatted (and then delete this TODO)

load("@prelude//:attrs_validators.bzl", "validation_common")
load("@prelude//:genrule.bzl", "genrule_attributes")
load("@prelude//:validation_deps.bzl", "VALIDATION_DEPS_ATTR_NAME")
load("@prelude//android:build_only_native_code.bzl", "is_build_only_native_code")
load("@prelude//android:configuration.bzl", "is_building_android_binary_attr")
load("@prelude//android:min_sdk_version.bzl", "get_min_sdk_version_constraint_value_name", "get_min_sdk_version_range")
load("@prelude//decls:test_common.bzl", "test_common")
load("@prelude//transitions:constraint_overrides.bzl", "constraint_overrides")
load(":common.bzl", "TestType", "buck", "prelude_rule")
load(":jvm_common.bzl", "jvm_common")
load(":re_test_common.bzl", "re_test_common")
load(":toolchains_common.bzl", "toolchains_common")

Style = ["obf", "pretty", "detailed"]

def dex_min_sdk_version():
    min_sdk_version_dict = {"DEFAULT": None}
    for min_sdk in get_min_sdk_version_range():
        constraint = "prelude//android/constraints:{}".format(get_min_sdk_version_constraint_value_name(min_sdk))
        min_sdk_version_dict[constraint] = min_sdk

    return select(min_sdk_version_dict)

gwt_binary = prelude_rule(
    name = "gwt_binary",
    docs = """
        A `gwt_binary()` rule produces a GWT (Google Web Toolkit) application
        by invoking the GWT compiler against the listed `modules`. The
        resulting output can be served as part of a web app.
    """,
    examples = None,
    further = None,
    attrs = (
        # @unsorted-dict-items
        {
            "deps": attrs.list(attrs.dep(), default = []),
            "draft_compile": attrs.bool(default = False),
            "experimental_args": attrs.list(attrs.string(), default = []),
            "local_workers": attrs.int(default = 2),
            "module_deps": attrs.list(attrs.dep(), default = []),
            "modules": attrs.list(attrs.string(), default = []),
            "optimize": attrs.int(default = 9),
            "strict": attrs.bool(default = False),
            "style": attrs.enum(Style, default = "obf"),
            "vm_args": attrs.list(attrs.string(), default = []),
            "_exec_os_type": buck.exec_os_type_arg(),
            "_java_toolchain": toolchains_common.java(),
        }
        | buck.licenses_arg()
        | buck.labels_arg()
        | buck.contacts_arg()
    ),
)

jar_genrule = prelude_rule(
    name = "jar_genrule",
    docs = """
        A `jar_genrule()` is a variant of `genrule()` whose output is
        packaged into a JAR file. Use it to produce a JAR from arbitrary
        commands (`bash`/`cmd`/`cmd_exe`) that operate on `srcs`.
    """,
    examples = None,
    further = None,
    attrs = (
        # @unsorted-dict-items
        {
            "bash": attrs.option(attrs.arg(), default = None),
            "cacheable": attrs.option(attrs.bool(), default = None),
            "cmd": attrs.option(attrs.arg(), default = None),
            "cmd_exe": attrs.option(attrs.arg(), default = None),
            "enable_sandbox": attrs.option(attrs.bool(), default = None),
            "environment_expansion_separator": attrs.option(attrs.string(), default = None),
            "weight": attrs.option(attrs.int(), default = None),
            "remote": attrs.option(attrs.bool(), default = None),
            "srcs": attrs.named_set(attrs.source(), sorted = False, default = []),
            "type": attrs.option(attrs.string(), default = None),
        }
        | genrule_attributes()
        | {
            "_java_toolchain": toolchains_common.java(),
        }
        | buck.licenses_arg()
        | buck.labels_arg()
        | buck.contacts_arg()
    ),
)

java_annotation_processor = prelude_rule(
    name = "java_annotation_processor",
    docs = """
        A `java_annotation_processor()` rule declares a Java annotation
        processor (identified by `processor_class`) that can be referenced
        from `java_library()` and `kotlin_library()` rules to run during
        compilation.
    """,
    examples = None,
    further = None,
    attrs = (
        # @unsorted-dict-items
        {
            "deps": attrs.list(attrs.dep(), default = []),
            "does_not_affect_abi": attrs.bool(default = False),
            "isolate_class_loader": attrs.bool(default = False),
            "processor_class": attrs.string(default = ""),
            "supports_abi_generation_from_source": attrs.bool(default = False),
            "runs_on_java_only": attrs.bool(default = False),
            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
        }
        | buck.licenses_arg()
        | buck.labels_arg()
        | buck.contacts_arg()
    ),
)

java_binary = prelude_rule(
    name = "java_binary",
    docs = """
        A `java_binary()` rule is used to create a JAR file of the
        compiled .class files and resources of the `java_library()`
         rules on which it depends.
    """,
    examples = None,
    further = None,
    attrs = (
        # @unsorted-dict-items
        {
            "base_dep": attrs.option(
                attrs.dep(),
                default = None,
                doc = """
                Rule (normally of type `java_library`) that should be
                 compiled and used as a base JAR to receive all dependencies through an append operation.
            """,
            ),
            "build_manifest": attrs.option(
                attrs.source(),
                default = None,
                doc = """
                MANIFEST containing stamped build attributes, that should be merged into the main jar manifest
            """,
            ),
            "deps": attrs.list(
                attrs.dep(),
                default = [],
                doc = """
                Rules (normally of type `java_library`) that should be
                 compiled and whose `.class` files and resources should be
                 included in the generated JAR file.
            """,
            ),
            "main_class": attrs.option(
                attrs.string(),
                default = None,
                doc = """
                If provided, this will be the value specified as the
                 `Main-Class` attribute of the `META-INF/MANIFEST.MF`
                 file in the generated JAR file. Also, when this rule is used as
                 an executable in a `genrule()`,
                 `main_class` will indicate the class whose `main()` method will be invoked to process the command-line arguments. This
                 is consistent with the expected usage of `java -jar
                 *<name.jar>* *<args>*`.
            """,
            ),
            "manifest_file": attrs.option(
                attrs.source(),
                default = None,
                doc = """
                If provided, this manifest will be used when generating the JAR
                 file. If combined with `main_class`, the specified manifest
                 file will be used but the `main_class` will override the main
                 class in the manifest.
            """,
            ),
            "java_args_for_run_info": attrs.list(attrs.string(), default = []),
            "meta_inf_directory": attrs.option(
                attrs.source(allow_directory = True),
                default = None,
                doc = """
                Note: This has beta support currently.
                 If provided, the contents in this directory will end up in the
                 `META-INF` directory inside the generated JAR file.
            """,
            ),
            "blocklist": attrs.list(
                attrs.regex(),
                default = [],
                doc = """
                A list of patterns that identify files to exclude from the final generated JAR
                 file. Example:

                ```
                java_binary(
                  name = 'example',
                  blocklist = [
                    # Excludes com.example.A and com.example.Alligator,
                    # as well as their inner classes and any non-class files that happen to match
                    # the pattern
                    'com.example.A',

                    # Excludes all files from org/slf4j/**/*.
                    'org.slf4j',
                  ],
                  deps = [
                    ':example1',
                    ':third-party-stuff',
                  ],
                )
                ```
            """,
            ),
            "concat_deps": attrs.bool(default = False, doc = "Use zip concatenation instead of repacking all dependency jars, which is faster"),
            "default_cxx_platform": attrs.option(attrs.string(), default = None),
            "generate_wrapper": attrs.bool(default = False),
            "do_not_create_inner_jar": attrs.bool(default = False),
            "incremental_target_prefix": attrs.option(attrs.string(), default = None),
            "java_version": attrs.option(attrs.string(), default = None, doc = "Expected java version used at compile time"),
            "java_runtime": attrs.option(attrs.string(), default = None, doc = "Expected java version used at runtime"),
            "proguard_config": attrs.option(attrs.source(), default = None),
            "proguard_jvm_args": attrs.list(attrs.string(), default = []),
            "proguard_library_jars": attrs.list(attrs.source(), default = []),
            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
            "_exec_os_type": buck.exec_os_type_arg(),
            "_is_building_android_binary": is_building_android_binary_attr(),
            "_java_toolchain": toolchains_common.java(),
        }
        | constraint_overrides.attributes
        | buck.licenses_arg()
        | buck.labels_arg()
        | buck.contacts_arg()
    ),
    cfg = constraint_overrides.transition,
)

java_library = prelude_rule(
    name = "java_library",
    docs = """
        A `java_library()` rule defines a set of Java
        files that can be compiled together. The main output of a
         `java_library()` rule is a single JAR file containing all
        of the compiled class files, as well as the static files specified in
        the `resources` argument.
    """,
    examples = """
        ```
        # A rule that compiles a single .java file.
        java_library(
          name = 'JsonUtil',
          srcs = ['JsonUtil.java'],
          deps = [
            '//third_party/guava:guava',
            '//third_party/jackson:jackson',
          ],
        )

        # A rule that compiles all of the .java files under the directory in
        # which the rule is defined using glob(). It also excludes an
        # individual file that may have additional dependencies, so it is
        # compiled by a separate rule.
        java_library(
          name = 'messenger',
          srcs = glob(['**/*.java'], excludes = ['MessengerModule.java']),
          deps = [
            '//src/com/facebook/base:base',
            '//third_party/guava:guava',
          ],
        )

        java_library(
          name = 'MessengerModule',
          srcs = ['MessengerModule.java'],
          deps = [
            '//src/com/facebook/base:base',
            '//src/com/google/inject:inject',
            '//third_party/guava:guava',
            '//third_party/jsr-330:jsr-330',
          ],
        )

        # A rule that builds a library with both relative and
        # fully-qualified deps.
        java_library(
          name = 'testutil',
          srcs = glob(['tests/**/*.java'], excludes = 'tests/**/*Test.java'),
          deps = [
            ':lib-fb4a',
            '//java/com/facebook/base:base',
          ],
        )
        ```
    """,
    further = None,
    attrs = (
        # @unsorted-dict-items
        {
            "srcs": attrs.list(
                attrs.source(),
                default = [],
                doc = """
                The set of `.java` files to compile for this rule.
                 If any of the files in this list end in `.src.zip`,
                 then the entries in the ZIP file that end in `.java` will be
                 included as ordinary inputs to compilation. This is common when using
                 a `genrule()` to auto-generate some Java source code that
                 needs to be compiled with some hand-written Java code.
            """,
            ),
        }
        | jvm_common.resources_arg()
        | {
            "concat_resources": attrs.bool(
                default = False,
                doc = """
                Use parallel compression and concatenation of intermediary jars to speed up jar time generation.
            """,
            ),
            "deps": attrs.list(
                attrs.dep(),
                default = [],
                doc = """
                Rules (usually other `java_library` rules) that are used to
                 generate the classpath required to compile this `java_library`.
            """,
            ),
            "extra_arguments": attrs.list(
                attrs.string(),
                default = [],
                doc = """
                List of additional arguments to pass into the Java compiler. These
                 arguments follow the ones specified in `.buckconfig`.
            """,
            ),
            "java_version": attrs.option(
                attrs.string(),
                default = None,
                doc = """
                Equivalent to setting both `source` and `target`  to the given value. Setting this and `source` or `target` (or both!) is an error.
            """,
            ),
            "source": attrs.option(
                attrs.string(),
                default = None,
                doc = """
                Specifies the version of Java (as a string) to interpret source
                 files as.
                 Overrides the value in "source\\_level" in the "java" section
                 of `.buckconfig`.
            """,
            ),
            "target": attrs.option(
                attrs.string(),
                default = None,
                doc = """
                Specifies the version of Java (as a string) for which to
                 generate code.
                 Overrides the value in "target\\_level" in the "java" section
                 of `.buckconfig`.
            """,
            ),
        }
        | jvm_common.annotation_processors()
        | jvm_common.remove_classes_arg()
        | jvm_common.exported_deps()
        | jvm_common.provided_deps()
        | jvm_common.exported_provided_deps()
        | jvm_common.abi_generation_mode()
        | jvm_common.source_only_abi_deps()
        | jvm_common.required_for_source_only_abi()
        | jvm_common.plugins()
        | jvm_common.multi_release_jar()
        | jvm_common.javac()
        | jvm_common.classic_java_content_based_paths()
        | {
            "class_to_src_map_deps": attrs.list(attrs.dep(), default = []),
            "jar_postprocessor": attrs.option(attrs.exec_dep(), default = None),
            "manifest_file": attrs.option(attrs.source(), default = None),
            "maven_coords": attrs.option(attrs.string(), default = None),
            "proguard_config": attrs.option(attrs.source(), default = None),
            "resources_root": attrs.option(attrs.string(), default = None),
            "runtime_deps": attrs.list(attrs.dep(), default = []),
            VALIDATION_DEPS_ATTR_NAME: attrs.set(attrs.dep(), sorted = True, default = []),
            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
            "_dex_min_sdk_version": attrs.option(attrs.int(), default = dex_min_sdk_version()),
            "_dex_toolchain": toolchains_common.dex(),
            "_exec_os_type": buck.exec_os_type_arg(),
            "_is_building_android_binary": is_building_android_binary_attr(),
            "_java_toolchain": toolchains_common.java(),
        }
        | buck.licenses_arg()
        | buck.labels_arg()
        | buck.contacts_arg()
        | validation_common.attrs_validators_arg()
    ),
)

java_plugin = prelude_rule(
    name = "java_plugin",
    docs = """
        A `java_plugin()` rule declares a `javac` plugin (identified by
        `plugin_name`) that can be referenced from `java_library()` and
        `kotlin_library()` rules to run during compilation.
    """,
    examples = None,
    further = None,
    attrs = (
        # @unsorted-dict-items
        {
            "deps": attrs.list(attrs.dep(), default = []),
            "does_not_affect_abi": attrs.bool(default = False),
            "isolate_class_loader": attrs.bool(default = False),
            "plugin_name": attrs.string(default = ""),
            "supports_abi_generation_from_source": attrs.bool(default = False),
            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
        }
        | buck.licenses_arg()
        | buck.labels_arg()
        | buck.contacts_arg()
    ),
)

java_test = prelude_rule(
    name = "java_test",
    docs = """
        A `java_test()` rule is used to define a set of
         `.java` files that contain tests to run via JUnit.
    """,
    examples = None,
    further = None,
    attrs = (
        # @unsorted-dict-items
        buck.inject_test_env_arg()
        | {
            "resources": attrs.list(
                attrs.source(),
                default = [],
                doc = """
                Same as `java_library()`.
            """,
            ),
            "srcs": attrs.list(
                attrs.source(),
                default = [],
                doc = """
                Like `java_library()`,
                 all of the `.java` files specified by the
                 `srcs` argument will be compiled when this rule is
                 built. In addition, all of the corresponding `.class` files that are built by this rule will be passed as arguments to
                 JUnit when this rule is run as a test. `.class` files
                 that are passed to JUnit that do not have any methods annotated with
                 `@Test` are considered failed tests, so make sure that
                 only test case classes are specified as `srcs`. This is
                 frequently done by specifying `srcs` as
                 `glob(['**/*Test.java'])`.
            """,
            ),
        }
        | buck.test_label_arg()
        | {
            "deps": attrs.list(
                attrs.dep(),
                default = [],
                doc = """
                Same as `java_library()`.
                 // org.junit.rules.Timeout was not introduced until 4.7.
                 Must include JUnit (version 4.7 or later) as a dependency for JUnit tests.
                 Must include TestNG (version 6.2 or later) and hamcrest as a dependencies for TestNG tests.
            """,
            ),
            "source": attrs.option(
                attrs.string(),
                default = None,
                doc = """
                Java language level for compiling. Corresponds to the
                 `-source` argument for `javac`.
            """,
            ),
            "target": attrs.option(
                attrs.string(),
                default = None,
                doc = """
                Bytecode target level for compiling. Corresponds to the
                 `-target` argument for `javac`.
            """,
            ),
            "test_type": attrs.option(
                attrs.enum(TestType),
                default = None,
                doc = """
                Specifies which test framework to use.
                 The currently supported options are 'junit' and 'testng'.
            """,
            ),
        }
        | buck.run_test_separately_arg(
            run_test_separately_type = attrs.bool(
                default = False,
                doc = """
            If set to True, the test(s) in this rule are run separately from
             all other tests. This is useful for integration tests which
             access a physical device or other limited resource. If unset,
             the test(s) in this rule run in parallel with all other tests.
        """,
            )
        )
        | re_test_common.test_args()
        | buck.test_rule_timeout_ms()
        | {
            "cxx_library_allowlist": attrs.list(
                attrs.dep(),
                default = [],
                doc = """
                 List of cxx_library targets to build, if use_cxx_libraries is true.
                 This can be useful if some dependencies are Android-only and won't build for the test host platform.
            """,
            ),
            "use_cxx_libraries": attrs.option(
                attrs.bool(),
                default = None,
                doc = """
                Whether or not to build and link against `cxx_library()` dependencies when testing.
            """,
            ),
            "vm_args": attrs.list(
                attrs.arg(),
                default = [],
                doc = """
                Runtime arguments to the JVM running the tests.
            """,
            ),
        }
        | jvm_common.test_env()
        | jvm_common.abi_generation_mode()
        | {
            "deps_query": attrs.option(attrs.query(), default = None),
            "discover_all_test_classes": attrs.bool(default = False),
            "exported_deps": attrs.list(attrs.dep(), default = []),
            "exported_provided_deps": attrs.list(attrs.dep(), default = []),
            "extra_arguments": attrs.list(attrs.string(), default = []),
            "jar_postprocessor": attrs.option(attrs.exec_dep(), default = None),
            "java": attrs.option(attrs.dep(), default = None),
            "java_agents": attrs.list(attrs.source(), default = []),
            "java_version": attrs.option(attrs.string(), default = None),
            "manifest_file": attrs.option(attrs.source(), default = None),
            "maven_coords": attrs.option(attrs.string(), default = None),
            "proguard_config": attrs.option(attrs.source(), default = None),
            "provided_deps": attrs.list(attrs.dep(), default = []),
            "remove_classes": attrs.list(attrs.regex(), default = []),
            "required_for_source_only_abi": attrs.bool(default = False),
            "resources_root": attrs.option(attrs.string(), default = None),
            "runner": attrs.option(attrs.dep(), default = None),
            "runtime_deps": attrs.list(attrs.dep(), default = []),
            "source_only_abi_deps": attrs.list(attrs.dep(), default = []),
            "supports_test_execution_caching": attrs.bool(default = False),
            "test_case_timeout_ms": attrs.option(attrs.int(), default = None),
            "test_class_names_file": attrs.option(attrs.source(), default = None),
            "unbundled_resources_root": attrs.option(attrs.source(allow_directory = True), default = None),
            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
            "_exec_os_type": buck.exec_os_type_arg(),
            "_is_building_android_binary": attrs.default_only(attrs.bool(default = False)),
            "_java_test_toolchain": toolchains_common.java_test(),
            "_java_toolchain": toolchains_common.java(),
        }
        | constraint_overrides.attributes
        | buck.licenses_arg()
        | buck.contacts_arg()
        | validation_common.attrs_validators_arg()
    )
    | jvm_common.annotation_processors()
    | jvm_common.plugins()
    | jvm_common.javac()
    | test_common.attributes()
    | jvm_common.classic_java_content_based_paths(),
    cfg = constraint_overrides.transition,
)

prebuilt_jar = prelude_rule(
    name = "prebuilt_jar",
    docs = """
        A `prebuilt_jar()` rule is used to identify a JAR file that
        is checked into our repository as a precompiled binary rather than one
        that is built from source by Buck. Frequently, these are used to
        reference third-party JAR files (such as junit.jar) and
        are used as dependencies of `java_library()` rules.
    """,
    examples = """
        ```
        prebuilt_jar(
          name = 'junit',
          binary_jar = 'junit-4.8.2.jar',
          source_jar = 'junit-4.8.2-sources.jar',
          javadoc_url = 'http://kentbeck.github.com/junit/javadoc/4.8/',
        )

        java_library(
          name = 'tests',
          srcs = glob(['tests/**/*Test.java']),
          deps = [
            ':junit',
          ],
        )
        ```
    """,
    further = None,
    attrs = (
        # @unsorted-dict-items
        {
            "binary_jar": attrs.source(
                doc = """
                Path to the pre-built JAR file.
            """
            ),
            "source_jar": attrs.option(
                attrs.source(),
                default = None,
                doc = """
                Path to a JAR file that contains the `.java` files to create
                 the `.class` in the `binary_jar`. This is frequently
                 provided for debugging purposes.
            """,
            ),
            "javadoc_url": attrs.option(
                attrs.string(),
                default = None,
                doc = """
                URL to the Javadoc for the `.class` files in the
                 `binary_jar`.
            """,
            ),
            "deps": attrs.list(
                attrs.dep(),
                default = [],
                doc = """
                 Rules that must be built before this rule. Because the
                 `binary_jar` is already built, there should be nothing to
                 build, so this should be empty.
            """,
            ),
            "desugar_deps": attrs.list(attrs.dep(), default = []),
            "generate_abi": attrs.bool(default = True),
            "is_executable": attrs.bool(default = False),
            "maven_coords": attrs.option(attrs.string(), default = None),
            # Prebuilt jars are quick to build, and often contain third-party code, which in turn is
            # often a source of annotations and constants. To ease migration to ABI generation from
            # source without deps, we have them present during ABI gen by default.
            "required_for_source_only_abi": attrs.bool(default = True),
            "uses_content_based_paths": jvm_common.content_based_path_attr(),
            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
            "_dex_min_sdk_version": attrs.option(attrs.int(), default = dex_min_sdk_version()),
            "_dex_toolchain": toolchains_common.dex(),
            "_exec_os_type": buck.exec_os_type_arg(),
            "_prebuilt_jar_toolchain": toolchains_common.prebuilt_jar(),
        }
        | buck.licenses_arg()
        | buck.labels_arg()
        | buck.contacts_arg()
    ),
)

java_rules = struct(
    gwt_binary = gwt_binary,
    jar_genrule = jar_genrule,
    java_annotation_processor = java_annotation_processor,
    java_binary = java_binary,
    java_library = java_library,
    java_plugin = java_plugin,
    java_test = java_test,
    prebuilt_jar = prebuilt_jar,
)