簡體   English   中英

如何在另一個 bazel 規則中獲取構建目錄中的文件

[英]How do I get the files in the build directory in another bazel rule

  1. 使用python工具生成.cpp/ .hpp代碼的時候像protobuf工具一樣,但是不知道會生成多少個文件,所以和protbuf工具有點不一樣。
In one genrule:
def __generate_core_ifce_impl(ctx):
    ...
    output_file = ctx.actions.declare_directory(out)
    cmd = """
        mkdir -p {path};
    """.format(path = output_file.path)
    cmd += """
        {tools} -i {src} -o {output_dir}
    """.format(tools = tools, src = ctx.files.srcs, output_dir = output_file.path)

    ctx.actions.run_shell(
        command = cmd,
        inputs = ctx.files.srcs,
        outputs = [output_file]
        )
    return [DefaultInfo(files = depset([output_file])),]

_generate_core_ifce = rule (
    implementation = __generate_core_ifce_impl,
    attrs = {
        "srcs": attr.label_list(mandatory = False, allow_files = True),
        "tools": attr.label_list(mandatory = True, allow_files = True),
        "out": attr.sting(mandatory = True),
    },
)

在 output_file 目錄中,會生成一些 *.cpp && *.hpp,但我不知道它們的名字

  1. 然后在另一個規則中,cc_library 將使用 output_file 目錄中的 *.cpp && *.hpp 問題是:如何編寫此規則? 獲取不到output_file目錄中的文件,所以無法寫cc_library?

您應該能夠使用目標的名稱,並且 cc_library 將使用 DefaultInfo 中給出的文件,例如:

_generate_core_ifce(
  name = "my_generate_core_ifce_target",
  ...
)

cc_library(
  name = "my_cc_library_target",
  srcs = [":my_generate_core_ifce_target"],
  ...
)

編輯:添加一個例子:

BUILD

load(":defs.bzl", "my_rule")

my_rule(
  name = "my_target",
)

cc_binary(
  name = "cc",
  srcs = [":my_target"],
)

defs.bzl

def _impl(ctx):
    output_dir = ctx.actions.declare_directory("my_outputs")
    command = """
mkdir -p {output_dir}
cat > {output_dir}/main.c <<EOF
#include "stdio.h"
#include "mylib.h"
int main() {
  printf("hello world %d\\n", get_num());
  return 0;
}
EOF

cat > {output_dir}/mylib.c <<EOF
int get_num() {
  return 42;
}
EOF

cat > {output_dir}/mylib.h <<EOF
int get_num();
EOF
""".replace("{output_dir}", output_dir.path)

    ctx.actions.run_shell(
        command = command,
        outputs = [output_dir]
    )
    return [DefaultInfo(files = depset([output_dir])),]

my_rule = rule(
    implementation = _impl,
)

用法:

$ bazel run cc
Starting local Bazel server and connecting to it...
INFO: Analyzed target //:cc (15 packages loaded, 57 targets configured).
INFO: Found 1 target...
Target //:cc up-to-date:
  bazel-bin/cc
INFO: Elapsed time: 3.626s, Critical Path: 0.06s
INFO: 8 processes: 4 internal, 4 linux-sandbox.
INFO: Build completed successfully, 8 total actions
INFO: Build completed successfully, 8 total actions
hello world 42

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM