Skip to content

Instantly share code, notes, and snippets.

@dflems
Created May 22, 2024 19:52
Show Gist options
  • Save dflems/ca077b868bf6113b52b13b8626e1b16b to your computer and use it in GitHub Desktop.
Save dflems/ca077b868bf6113b52b13b8626e1b16b to your computer and use it in GitHub Desktop.
load("@build_bazel_rules_apple//apple/internal:providers.bzl", "new_appleresourceinfo") # buildifier: disable=bzl-visibility
def apple_unprefixed_resources(name, strip_prefix, resources = [], **kwargs):
"""Like `structured_resources`, but chopping a common prefix off of each resource.
Args:
name: The name of the target.
strip_prefix: The prefix to strip from each resource.
resources: A list of files.
**kwargs: Forwarded to the underlying rule.
"""
if not strip_prefix.endswith("/"):
strip_prefix = strip_prefix + "/"
prefix_len = len(strip_prefix)
unprefixed = {}
for res in resources:
if not res.startswith(strip_prefix):
fail("`{}` does not begin with `{}`".format(res, strip_prefix))
unprefixed[res] = paths.dirname(res[prefix_len:])
apple_structured_resources(
name = name,
resources = unprefixed,
**kwargs
)
def _apple_structured_resources_impl(ctx):
all_files = []
parent_dir_to_files = {}
for tgt, parent_dir in ctx.attr.resources.items():
if not parent_dir or parent_dir == ".":
parent_dir = None
files = tgt.files.to_list()
all_files.extend(files)
parent_dir_to_files.setdefault(parent_dir, []).extend(files)
resources = []
for parent_dir, files in parent_dir_to_files.items():
resources.append((parent_dir, None, depset(files)))
owner = str(ctx.label)
result = new_appleresourceinfo(
owners = depset([(file.short_path, owner) for file in all_files]),
unprocessed = resources,
unowned_resources = depset(),
)
return [result]
apple_structured_resources = rule(
implementation = _apple_structured_resources_impl,
attrs = {
"resources": attr.label_keyed_string_dict(
allow_files = True,
allow_empty = False,
doc = """
A mapping from file labels to a string representing the subdirectory to which they should be added
in the bundle. These files are not processed or compiled in any way.
""",
),
},
doc = """
Like `structured_resources` on other apple resource rules, but with the ability to define a parent
directory per resource.
""",
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment