0

Sometimes in my bazel rules I need to run a tool which produces bunch of files but writes them into output directory and directory path should be used as argument. So I ended up with following pattern:

out_dir = "{}_out".format(ctx.label)
out_files = []
for file in ctx.files.srcs:
  file_path = # ... construct file path 
  o = ctx.actions.declare_file("{}/{}".format(out_dir, file_path))
  out_files.append(o)

# Now we need to fetch first file and strip out file path part
out = out_files[0].path
out = out[0:(out.find(out_dir) + len(out_dir)]

But it feels very verbose and ugly and I can't find any good way to construct this path with rule attributes or something available at analysis phase. Is there any easy way to achieve this?

  • How is it ugly? What would a less verbose, cleaner API look like? Asking because nothing jumps at me from the code snippet, it looks all right to me. – László Oct 14 '19 at 09:49
  • @László I'd prefer to have function like `declare_directory` without making it required as output action and then use in sibling argument for `declare_file`. That's what I was looking from the begining. So the idea is to **construct** this path but now I need to **deconstruct** values back. Needles to say you also need to check if `out_files` is not empty list. I understand that in other hand it may be confusing to have `declare_directory` and `declare_directory'` in API. – dziedmaroz Oct 14 '19 at 15:44
  • Yes, I think the API designers aimed for simplicity. FYI you can simplify the last two lines like so: `out = out_files[0].path.dirname` (you have to handle `ctx.files.srcs` being empty earlier). If you always want to generate the directory, even if there are no input files, then you must use `ctx.actions.declare_directory`. – László Oct 15 '19 at 09:51
  • Unfortunately I can’t because generated file has own path under output directory. For example if I want to generate java class with own package. – dziedmaroz Oct 16 '19 at 10:25
  • I see. Then I have no better idea than your current approach. – László Oct 16 '19 at 10:46

0 Answers0