kythe.io@v0.0.68-0.20240422202219-7225dbc01741/tools/build_rules/expand_template.bzl (about) 1 def _expand_template_impl(ctx): 2 ctx.actions.expand_template( 3 template = ctx.file.template, 4 output = ctx.outputs.out, 5 substitutions = ctx.attr.substitutions, 6 ) 7 8 expand_template = rule( 9 attrs = { 10 "out": attr.output(mandatory = True), 11 "substitutions": attr.string_dict(mandatory = True), 12 "template": attr.label( 13 mandatory = True, 14 allow_single_file = True, 15 ), 16 }, 17 output_to_genfiles = True, 18 implementation = _expand_template_impl, 19 ) 20 21 def cmake_substitutions(vars, defines = {}): 22 """Returns a dict of template substitutions combining `vars` and `defines`. 23 24 `vars` will be turned into a dict replacing `${key}` and `@key@` with `value`. 25 `defines` will be turned into a dict replacing `#cmakedefine` with `#define {value}` 26 if present is true, otherwise `/* #undef %s /*`. 27 """ 28 subs = {} 29 for key, value in vars.items(): 30 subs["${%s}" % (key,)] = str(value) if value != None else "" 31 subs["@%s@" % (key,)] = str(value) if value != None else "" 32 33 # TODO(shahms): Better handling of #cmakedefine delimiters and line endings to 34 # avoid the prefix-substitution problem. 35 # Potentially allow value to be: True, False, None or string. 36 # True/False => Same as current 37 # None => assume no suffix value, include \n in sub and replacement 38 # string => use string to lookup in vars and assume ${} or @@ tail? 39 for macro, present in defines.items(): 40 if present: 41 subs["#cmakedefine %s" % macro] = "#define %s" % macro 42 else: 43 subs["#cmakedefine %s" % macro] = "/* #undef %s */" % macro 44 return subs