1# This Bazel rules file is derived from https://github.com/tensorflow/tensorflow/blob/master/third_party/common.bzl 2 3# Rule for simple expansion of template files. This performs a simple 4# search over the template file for the keys in substitutions, 5# and replaces them with the corresponding values. 6# 7# Typical usage: 8# load("/tools/build_rules/template_rule", "template_rule") 9# template_rule( 10# name = "ExpandMyTemplate", 11# src = "my.template", 12# out = "my.txt", 13# substitutions = { 14# "$VAR1": "foo", 15# "$VAR2": "bar", 16# } 17# ) 18# 19# Args: 20# name: The name of the rule. 21# template: The template file to expand 22# out: The destination of the expanded file 23# substitutions: A dictionary mapping strings to their substitutions 24 25def template_rule_impl(ctx): 26 ctx.actions.expand_template( 27 template = ctx.file.src, 28 output = ctx.outputs.out, 29 substitutions = ctx.attr.substitutions, 30 ) 31 32template_rule = rule( 33 attrs = { 34 "out": attr.output(mandatory = True), 35 "src": attr.label( 36 mandatory = True, 37 allow_single_file = True, 38 ), 39 "substitutions": attr.string_dict(mandatory = True), 40 }, 41 # output_to_genfiles is required for header files. 42 output_to_genfiles = True, 43 implementation = template_rule_impl, 44) 45 46# Header template rule is an extension of template substitution rule 47# That also makes this header a valid dependency for cc_library 48# From https://stackoverflow.com/a/55407399 49def header_template_rule_impl(ctx): 50 ctx.actions.expand_template( 51 template = ctx.file.src, 52 output = ctx.outputs.out, 53 substitutions = ctx.attr.substitutions, 54 ) 55 return [ 56 # create a provider which says that this 57 # out file should be made available as a header 58 CcInfo(compilation_context = cc_common.create_compilation_context( 59 60 # pass out the include path for finding this header 61 system_includes = depset([ctx.attr.include, ctx.outputs.out.dirname, ctx.bin_dir.path]), 62 63 # and the actual header here. 64 headers = depset([ctx.outputs.out]), 65 )), 66 ] 67 68header_template_rule = rule( 69 attrs = { 70 "include": attr.string(), 71 "out": attr.output(mandatory = True), 72 "src": attr.label( 73 mandatory = True, 74 allow_single_file = True, 75 ), 76 "substitutions": attr.string_dict(mandatory = True), 77 }, 78 # output_to_genfiles is required for header files. 79 output_to_genfiles = True, 80 implementation = header_template_rule_impl, 81) 82