简体   繁体   English

在构建文件中使用 `bazel query`

[英]Use `bazel query` inside a build file

I am using Bazel with Golang, but the question is no Go-specific.我将 Bazel 与 Golang 一起使用,但问题不是 Go 特定的。 I have a common go directory structure:我有一个常见的 go 目录结构:

cmd/
├── mycommand/
│   ├── BUILD.bazel
│   ├── main.go
│   └── somefolder
│       └── other.go
├── othercommand/
│   ├── BUILD.bazel
│   └── main.go
pkg/
└── mypackage/
    ├── BUILD.bazel
    └── init.go
BUILD.bazel
WORKSPACE

... and I'd like to reference targets under the cmd folder. ...我想参考cmd文件夹下的目标。 I have a bazel query that will give me the list of those targets:我有一个 bazel 查询,它会给我这些目标的列表:

bazel query 'kind("go_binary", deps(//cmd/...))'
  • //cmd/mycommand:mycommand
  • //cmd/othercommand:othercommand

The question: How can I include this query in a BUILD.bazel file, something like the following:问题:如何在 BUILD.bazel 文件中包含此查询,如下所示:

pkg_tar(
    name = "release",
    srcs = kind("go_binary", deps(//cmd/...)),
    mode = "0644",
)

...which gives ...这使

ERROR: /some/path/BUILD.bazel:10:12: name 'kind' is not defined
ERROR: /some/path/BUILD.bazel:10:30: name 'deps' is not defined

Build targets need to be statically referenced in BUILD files, so embedding queries as inputs to rule attributes does not work.构建目标需要在 BUILD 文件中静态引用,因此将查询作为输入嵌入到规则属性中不起作用。

However, there are a couple of ways to dynamically generate targets to be used statically in the BUILD files:但是,有几种方法可以动态生成要在 BUILD 文件中静态使用的目标:

1) Run a tool that generates a BUILD file before running Bazel. 1) 在运行 Bazel 之前运行一个生成 BUILD 文件的工具。 rules_go's Gazelle is a good example. rules_go 的 Gazelle 就是一个很好的例子。

2) Write a repository rule that invokes non-hermetic tools to dynamically generate targets that your BUILD files can depend on. 2) 编写一个存储库规则,调用非封闭工具来动态生成 BUILD 文件可以依赖的目标。

Note that you may come across the genquery rule, which does let you perform a query on targets, but the rule outputs to a file during Bazel's execution phase, and not a Starlark list that can ingested into other rules' attributes during the analysis phase, which happens before the execution phase.请注意,您可能会遇到genquery规则,它确实允许您对目标执行查询,但该规则在 Bazel 的执行阶段输出到文件,而不是在分析阶段可以摄取到其他规则属性中的 Starlark 列表,这发生执行阶段之前。

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

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