可以添加一个唯一的后缀来防止重复输出文件。例如,使用Bazel-defined的$(location)`和
$(execpath)```标签,这些标签可以为每个宏实例生成唯一的文件名。
示例代码:
def my_macro(name, srcs):
unique_id = str(hash((name, srcs))) # 生成一个唯一的ID
output_file = "generated_file_%s" % unique_id # 添加唯一后缀
output = ctx.actions.declare_file(output_file)
inputs = [ctx.actions.declare_file(x) for x in srcs]
ctx.actions.run_shell(
inputs=inputs,
outputs=[output],
command="my_command %s %s" % (inputs[0].path, output.path))
return [output]
my_macro(name = "foo", srcs = ["input.txt"])
my_macro(name = "bar", srcs = ["input.txt"])
在上面的示例中,每个宏实例在生成文件名时都添加了唯一的后缀,以防止输出文件重复。