Skip to content

Commit

Permalink
feat(bazel): add a rule to filter the first matching output
Browse files Browse the repository at this point in the history
  • Loading branch information
kormide authored and devversion committed Sep 27, 2022
1 parent dbe78a5 commit 40aaf38
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions bazel/filter_outputs.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,39 @@ filter_outputs = rule(
This is useful when a target exposes multiple output files but a single output is only needed.
""",
)

def _filter_first_output_impl(ctx):
target_label = ctx.attr.target.label
target_workspace = target_label.workspace_name if target_label.workspace_name else ctx.workspace_name
target_package_manifest_path = "%s/%s" % (target_workspace, target_label.package)

outputs = ctx.attr.target[DefaultInfo].files.to_list()
for filter in ctx.attr.filters:
for output in outputs:
manifest_path = get_manifest_path(ctx, output)
relative_path = manifest_path[len(target_package_manifest_path) + 1:]
if filter == relative_path:
return [DefaultInfo(files = depset([output]))]

fail("Could not find output matching any filters in `%s`." % ctx.label)

filter_first_output = rule(
implementation = _filter_first_output_impl,
attrs = {
"target": attr.label(
mandatory = True,
doc = "Target for which an output should be filtered",
providers = [DefaultInfo],
),
"filters": attr.string_list(
mandatory = True,
doc = """Filters to apply to the target. The first output matching a filter will be included
in DefaultInfo, with filters earlier in the list taking precedence. Filter paths are expected
to be relative to the package owning the target.
""",
),
},
doc = """Rule that can be used to filter a single output from a given target.
This is useful when a target exposes multiple output files but a single output is only needed.
""",
)

0 comments on commit 40aaf38

Please sign in to comment.