在bazel宏中创建模板文件的最佳方法

问题描述 投票:1回答:1

我正在尝试编写一个宏,以抽象出我需要几个不同目标的一堆规则。我需要做的一件事是创建一个小文件,在以后的规则中将其视为源文件。如果这是一条规则,我将只使用expand_template。我目前能想到的最好的方法是native.genrule,并确保我正确地转义了所有内容并将其传递给echo。

我希望有一个更简单的方法。

相关代码:

  racket_contents = """
#lang racket/base
(require
  "bootstrap-compiler.rkt"
  racket/runtime-path)
(define-runtime-path library-compiler-list-file "%s")
(run-bootstrap-compiler library-compiler-list-file #"%s_main")
""" % (source_file_list, short_name)

  native.genrule(
      name = "racketize_" + name,
      outs = [racket_src_name],
      cmd = "echo >>$@ '%s'" % racket_contents,
  )
bazel
1个回答
0
投票

您可以具有用于扩展模板的通用规则。

genfile.bzl

def _genfile_impl(ctx):
    ctx.actions.expand_template(
        template = ctx.file.template,
        output = ctx.file.output,
        substitutions = substitutions,
    )
    return [
        DefaultInfo(files = depset([ctx.file.output])),
    ]

genfile = rule(
    implementation = _genfile_impl,
    attrs = {
        "template": attr.label(
            mandatory = True,
            allow_single_file = True,
        ),
        "output": attr.output(
            mandatory = True,
        ),
        "substitutions": attr.string_dict(),
    },
)

racket.tpl

#lang racket/base
(require
  "bootstrap-compiler.rkt"
  racket/runtime-path)
(define-runtime-path library-compiler-list-file "TMPL_SOURCE_FILES")
(run-bootstrap-compiler library-compiler-list-file #"TMPL_SHORTNAME_main")

BUILD

load("//:genfile.bzl", "genfile")

genfile(
  name = "racket",
  output = "racket.out",
  template = "racket.tpl",
  substitutions = {
    "TMPL_SOURCE_FILES": ",",join(["n1","n2"]),
    "TMPL_SHORTNAME": "shortname",
  },
)
© www.soinside.com 2019 - 2024. All rights reserved.