I'm building some custom C++ Bazel rules, and I need to add support for modifying the include paths of the C++ headers, the same way cc_library
headers can be modified with strip_include_prefix
.
My custom rule is implemented using ctx.actions.run
like this:
custom_cc_library = rule(
_impl,
attrs = {
...
"hdrs": attr.label_list(allow_files = [".h"]),
"strip_include_prefix": attr.string(),
...
},
)
Then within _impl
I call the following function to rewrite hdrs
:
def _strip_prefix(ctx, hdrs, prefix):
stripped = []
for hdr in hdrs:
stripped = hdr
if file.path.startswith(strip_prefix):
stripped_file = ctx.actions.declare_file(file.path[len(strip_prefix):])
ctx.actions.run_shell(
command = "mkdir -p {dest} && cp {src} {dest};".format(src=hdr.path, dest=stripped.path),
inputs = [hdr],
outputs = [stripped],
)
stripped.append(stripped_file)
return stripped
This doesn't work because Bazel won't copy files outside of their package directory, and besides it feels like the totally wrong approach to implementing this.
What is the best way to modify C++ header directories for dependencies to achieve the same functionality as cc_library
's parameter strip_include_prefix
?