简体   繁体   English

Bazel:使genrule输出可用于其他规则

[英]Bazel: Make genrule outputs available to another rule

I need the outputs of a genrule to be available next to another rule. 我需要某个genrule的输出另一个规则旁边可用。 (ie a py_binary ). (即py_binary )。

Suppose we have these files: 假设我们有以下文件:

# root/gen/BUILD:
genrule(
  name = "gen",
  outs = ["a.txt", "a2.txt"],
  cmd = "cd $(RULEDIR) && echo salam > a.txt && echo hello > a2.txt",
)

# root/BUILD:
py_binary(
  name = "use",
  srcs = ["use.py"],
  data = ["gen:a.txt", "gen:a2.txt"],
)

# use.py:
f = open("a.txt", "r")
f2 = open("a2.txt", "r")
print(f.read())
print(f2.read())

At a glance: 乍看上去:

project
├── root
│   ├── BUILD
│   ├── gen
│   │   └── BUILD  << This can generate required 'a.txt' and 'a2.txt' 
|   |                 files.
│   └── use.py  << This script needs to access a.txt file as './a.txt',
|                  but with 'bazel run root:use' it should access files
|                  like 'root/gen/a.txt'.
└── WORKSPACE

When I run bazel run :use , it doesn't find the file: 当我运行bazel run :use ,找不到文件:

FileNotFoundError: [Errno 2] No such file or directory: 'a.txt'

It needs to have a.txt and a2.txt files nearby , but they are in bazel-bin/gen directory. 它需要在附近具有a.txta2.txt文件,但它们位于bazel-bin/gen目录中。

You could set output_to_bindir in your genrule so that the output files will be written into the bazel-bin directory instead of the bazel-genfiles directory and then reference them in use.py using their relative path in the workspace, eg: 您可以在genrule设置output_to_bindir ,以便将输出文件写入bazel-bin目录而不是bazel-genfiles目录,然后使用工作空间中的相对路径在use.py引用它们,例如:

# root/gen/BUILD
genrule(
  name = "gen",
  ...
  output_to_bindir = True,
)

# use.py:
f = open("root/gen/a.txt", "r")
f2 = open("root/gen/a2.txt", "r")
print(f.read())
print(f2.read())

This should allow the application to load the files when running through bazel run . 当通过bazel run时,这应该允许应用程序加载文件。

If you cannot modify the code in the py_binary, you could write a genrule that creates a link to the other file, eg: 如果您无法修改py_binary中的代码,则可以编写一个genrule来创建到另一个文件的链接,例如:

genrule(
  name = "link_a.txt",
  srcs = ["//gen/a.txt"]
  outs = ["a.txt"],
  cmd = "ln $< $@"
)

genrule(
  name = "link_a2.txt",
  srcs = ["//gen/a2.txt"]
  outs = ["a2.txt"],
  cmd = "ln $< $@"
)

( $< is a shortcut for "the path to the input file if there is only one", and similarly $@ is a shortcut for "the path to the output file if there is only one") $<是“只有一个输入文件的路径的快捷方式”,类似地, $@是“只有一个输入文件的路径的快捷方式”)

It's also possible to wrap the genrule in a reusable macro, or do fancier things in Starlark, if needed. 如果需要,也可以将类型规则包装在可重用的宏中,或者在Starlark中执行更奇特的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM