0

Bazel 最近对我来说一直很好,但我偶然发现了一个我还没有找到满意答案的问题:

如何从工作区收集所有带有特定扩展名的文件?

表达问题的另一种方式:如何获得与在glob()整个 Bazel 工作区中进行操作等效的功能?

背景

在这种特殊情况下,目标是收集所有降价文件以运行一些检查并从中生成静态站点。

乍一看,glob()这听起来是个好主意,但一旦遇到 BUILD 文件就会停止。

目前的方法

当前的方法是在沙箱之外运行收集/生成逻辑,但这有点脏,我想知道是否有一种既“正确”又简单的方法(即,不需要每个 BUILD 文件显式公开其降价文件。

有没有办法在工作区中指定一些将添加到所有 BUILD 文件中的默认规则?

4

1 回答 1

2

You could write an aspect for this to aggregate markdown files in a bottom-up manner and create actions on those files. There is an example of a file_collector aspect here. I modified the aspect's extensions for your use case. This aspect aggregates all .md and .markdown files across targets on the deps attribute edges.

FileCollector = provider(
    fields = {"files": "collected files"},
)

def _file_collector_aspect_impl(target, ctx):
    # This function is executed for each dependency the aspect visits.

    # Collect files from the srcs
    direct = [
        f
        for f in ctx.rule.files.srcs
        if ctx.attr.extension == f.extension
    ]

    # Combine direct files with the files from the dependencies.
    files = depset(
        direct = direct,
        transitive = [dep[FileCollector].files for dep in ctx.rule.attr.deps],
    )

    return [FileCollector(files = files)]

markdown_file_collector_aspect = aspect(
    implementation = _file_collector_aspect_impl,
    attr_aspects = ["deps"],
    attrs = {
        "extension": attr.string(values = ["md", "markdown"]),
    },
)

Another way is to do a query on file targets (input and output files known to the Bazel action graph), and process these files separately. Here's an example querying for .bzl files in the rules_jvm_external repo:

$ bazel query //...:* | grep -e ".bzl$"
//migration:maven_jar_migrator_deps.bzl
//third_party/bazel_json/lib:json_parser.bzl
//settings:stamp_manifest.bzl
//private/rules:jvm_import.bzl
//private/rules:jetifier_maven_map.bzl
//private/rules:jetifier.bzl
//:specs.bzl
//:private/versions.bzl
//:private/proxy.bzl
//:private/dependency_tree_parser.bzl
//:private/coursier_utilities.bzl
//:coursier.bzl
//:defs.bzl
于 2020-05-07T07:18:48.433 回答