xref: /aosp_15_r20/external/bazel-skylib/rules/expand_template.bzl (revision bcb5dc7965af6ee42bf2f21341a2ec00233a8c8a)
1*bcb5dc79SHONG Yifan# Copyright 2022 The Bazel Authors. All rights reserved.
2*bcb5dc79SHONG Yifan#
3*bcb5dc79SHONG Yifan# Licensed under the Apache License, Version 2.0 (the "License");
4*bcb5dc79SHONG Yifan# you may not use this file except in compliance with the License.
5*bcb5dc79SHONG Yifan# You may obtain a copy of the License at
6*bcb5dc79SHONG Yifan#
7*bcb5dc79SHONG Yifan#    http://www.apache.org/licenses/LICENSE-2.0
8*bcb5dc79SHONG Yifan#
9*bcb5dc79SHONG Yifan# Unless required by applicable law or agreed to in writing, software
10*bcb5dc79SHONG Yifan# distributed under the License is distributed on an "AS IS" BASIS,
11*bcb5dc79SHONG Yifan# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12*bcb5dc79SHONG Yifan# See the License for the specific language governing permissions and
13*bcb5dc79SHONG Yifan# limitations under the License.
14*bcb5dc79SHONG Yifan
15*bcb5dc79SHONG Yifan"""A rule that performs template expansion.
16*bcb5dc79SHONG Yifan"""
17*bcb5dc79SHONG Yifan
18*bcb5dc79SHONG Yifandef _expand_template_impl(ctx):
19*bcb5dc79SHONG Yifan    ctx.actions.expand_template(
20*bcb5dc79SHONG Yifan        template = ctx.file.template,
21*bcb5dc79SHONG Yifan        output = ctx.outputs.out,
22*bcb5dc79SHONG Yifan        substitutions = ctx.attr.substitutions,
23*bcb5dc79SHONG Yifan    )
24*bcb5dc79SHONG Yifan
25*bcb5dc79SHONG Yifanexpand_template = rule(
26*bcb5dc79SHONG Yifan    implementation = _expand_template_impl,
27*bcb5dc79SHONG Yifan    doc = """Template expansion
28*bcb5dc79SHONG Yifan
29*bcb5dc79SHONG YifanThis performs a simple search over the template file for the keys in
30*bcb5dc79SHONG Yifansubstitutions, and replaces them with the corresponding values.
31*bcb5dc79SHONG Yifan
32*bcb5dc79SHONG YifanThere is no special syntax for the keys. To avoid conflicts, you would need to
33*bcb5dc79SHONG Yifanexplicitly add delimiters to the key strings, for example "{KEY}" or "@KEY@".""",
34*bcb5dc79SHONG Yifan    attrs = {
35*bcb5dc79SHONG Yifan        "template": attr.label(
36*bcb5dc79SHONG Yifan            mandatory = True,
37*bcb5dc79SHONG Yifan            allow_single_file = True,
38*bcb5dc79SHONG Yifan            doc = "The template file to expand.",
39*bcb5dc79SHONG Yifan        ),
40*bcb5dc79SHONG Yifan        "substitutions": attr.string_dict(
41*bcb5dc79SHONG Yifan            mandatory = True,
42*bcb5dc79SHONG Yifan            doc = "A dictionary mapping strings to their substitutions.",
43*bcb5dc79SHONG Yifan        ),
44*bcb5dc79SHONG Yifan        "out": attr.output(
45*bcb5dc79SHONG Yifan            mandatory = True,
46*bcb5dc79SHONG Yifan            doc = "The destination of the expanded file.",
47*bcb5dc79SHONG Yifan        ),
48*bcb5dc79SHONG Yifan    },
49*bcb5dc79SHONG Yifan)
50