Skip to content

Instantly share code, notes, and snippets.

@pamaury
Created May 22, 2026 13:45
Show Gist options
  • Select an option

  • Save pamaury/ecc08666eca7c901d530509e3629d384 to your computer and use it in GitHub Desktop.

Select an option

Save pamaury/ecc08666eca7c901d530509e3629d384 to your computer and use it in GitHub Desktop.
load(
"test.bzl",
"test_declare_directory",
"test_use_directory",
"extract_file_from_directory",
)
test_declare_directory(
name = "test_directory",
)
test_use_directory(
name = "mytest",
input_dir = ":test_directory"
)
extract_file_from_directory(
name = "mytest_a",
input_dir = ":test_directory",
which_file = "a.txt",
)
extract_file_from_directory(
name = "mytest_b",
input_dir = ":test_directory",
which_file = "b.txt",
)
def _declare_directory_impl(ctx):
test_files = ctx.actions.declare_directory(ctx.label.name + ".files")
path = test_files.path
ctx.actions.run_shell(
outputs = [test_files],
command = "mkdir -p %s && echo aaa > %s && echo bbb > %s" %
(path, path + "/a.txt", path + "/b.txt"),
)
return [DefaultInfo(files = depset([test_files]))]
test_declare_directory = rule(
implementation = _declare_directory_impl,
)
def _use_directory_impl(ctx):
print(ctx.files.input_dir)
list_file = ctx.actions.declare_file(ctx.label.name + ".files")
input_dir = ctx.files.input_dir
ctx.actions.run_shell(
outputs = [list_file],
inputs = input_dir,
command = "ls \"$1\" > \"$2\"",
arguments = [input_dir[0].path, list_file.path],
)
return [DefaultInfo(files = depset([list_file]))]
test_use_directory = rule(
implementation = _use_directory_impl,
attrs = {
"input_dir": attr.label(mandatory = True, allow_files = True),
},
)
def _extract_file_from_directory_impl(ctx):
input_dir = ctx.files.input_dir
# Two possible options.
if False:
# Copy file
out_file = ctx.actions.declare_file(ctx.attr.which_file)
ctx.actions.run_shell(
outputs = [out_file],
inputs = input_dir,
command = "cp \"$1\" \"$2\"",
arguments = [input_dir[0].path + "/" + ctx.attr.which_file, out_file.path],
)
return [DefaultInfo(files = depset([out_file]))]
else:
# Symlink file: does not work unless the user of this target knows to use default_runfiles.
out_file = ctx.actions.declare_symlink(ctx.attr.which_file)
ctx.actions.symlink(
output = out_file,
target_path = input_dir[0].path + "/" + ctx.attr.which_file,
)
return [DefaultInfo(files = depset([out_file]), runfiles = ctx.runfiles(files = input_dir))]
extract_file_from_directory = rule(
implementation = _extract_file_from_directory_impl,
attrs = {
"input_dir": attr.label(mandatory = True, allow_files = True),
"which_file": attr.string(mandatory = True),
},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment