1"""
2Copyright (C) 2023 The Android Open Source Project
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15"""
16
17load("@bazel_skylib//lib:paths.bzl", "paths")
18
19def _java_resources_impl(ctx):
20    java_runtime = ctx.attr._runtime[java_common.JavaRuntimeInfo]
21
22    output_file = ctx.actions.declare_file(ctx.attr.name + "_java_resources.jar")
23
24    ctx.actions.run_shell(
25        outputs = [output_file],
26        inputs = ctx.files.resources,
27        tools = java_runtime.files,
28        command = "{} cvf {} -C {} .".format(
29            paths.join(java_runtime.java_home, "bin", "jar"),
30            output_file.path,
31            ctx.attr.resource_strip_prefix,
32        ),
33    )
34
35    compile_jar = ctx.actions.declare_file(ctx.attr.name + "_java_resources-ijar.jar")
36    java_common.run_ijar(
37        actions = ctx.actions,
38        jar = output_file,
39        java_toolchain = ctx.toolchains["@bazel_tools//tools/jdk:toolchain_type"].java,
40    )
41
42    return [
43        JavaInfo(
44            output_jar = output_file,
45            compile_jar = compile_jar,
46        ),
47        DefaultInfo(files = depset([output_file])),
48    ]
49
50java_resources = rule(
51    doc = """
52    Package srcs into a jar, with the option of stripping a path prefix
53    """,
54    implementation = _java_resources_impl,
55    attrs = {
56        "resources": attr.label_list(allow_files = True),
57        "resource_strip_prefix": attr.string(
58            doc = """The path prefix to strip from resources.
59                   If specified, this path prefix is stripped from every fil
60                   in the resources attribute. It is an error for a resource
61                   file not to be under this directory. If not specified
62                   (the default), the path of resource file is determined
63                   according to the same logic as the Java package of source
64                   files. For example, a source file at stuff/java/foo/bar/a.txt
65                    will be located at foo/bar/a.txt.""",
66        ),
67        "_runtime": attr.label(
68            default = Label("@bazel_tools//tools/jdk:current_java_runtime"),
69            cfg = "exec",
70            providers = [java_common.JavaRuntimeInfo],
71        ),
72    },
73    toolchains = ["@bazel_tools//tools/jdk:toolchain_type"],
74    provides = [JavaInfo],
75)
76