xref: /aosp_15_r20/external/tink/java_src/template_rule.bzl (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1# Copyright 2022 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Rule for simple expansion of template files."""
16
17def _template_rule_impl(ctx):
18    """Modifies ctx.file.src keys in ctx.attr.substitutions with corresponding values."""
19    ctx.actions.expand_template(
20        template = ctx.file.src,
21        output = ctx.outputs.out,
22        substitutions = ctx.attr.substitutions,
23    )
24
25# Rule for simple expansion of template files. Modifies the templates in src substituting the keys
26# in substitutions with the corresponding values; the result is output to out.
27#
28# Borrowed from TensorFlow (https://github.com/tensorflow/tensorflow)
29#
30# Typical usage:
31#   template_rule(
32#       name = "ExpandMyTemplate",
33#       src = "my.template",
34#       out = "my.txt",
35#       substitutions = {
36#         "$VAR1": "foo",
37#         "$VAR2": "bar",
38#       }
39#   )
40#
41# Args:
42#   name: The name of the rule.
43#   src: The template file to expand
44#   out: The destination of the expanded file
45#   substitutions: A dictionary mapping strings to their substitutions
46template_rule = rule(
47    attrs = {
48        "src": attr.label(
49            mandatory = True,
50            allow_single_file = True,
51        ),
52        "substitutions": attr.string_dict(mandatory = True),
53        "out": attr.output(mandatory = True),
54    },
55    # output_to_genfiles is required for header files.
56    output_to_genfiles = True,
57    implementation = _template_rule_impl,
58)
59