|
| 1 | +load(":opa_library.bzl", "OpaInfo") |
| 2 | + |
| 3 | +def _opa_eval_impl(ctx): |
| 4 | + toolchain = ctx.toolchains["//tools:toolchain_type"].opacinfo |
| 5 | + out_file = ctx.actions.declare_file(ctx.attr.out) |
| 6 | + |
| 7 | + if len(ctx.attr.deps) != 1: |
| 8 | + fail("opa_eval only allow a single deps") |
| 9 | + |
| 10 | + bundle = ctx.attr.deps[0][OpaInfo].bundle |
| 11 | + additional_inputs = [] |
| 12 | + |
| 13 | + args = ctx.actions.args() |
| 14 | + |
| 15 | + args.add(toolchain.opa) |
| 16 | + args.add("eval") |
| 17 | + args.add("-b").add(bundle) |
| 18 | + |
| 19 | + if ctx.attr.partial: |
| 20 | + args.add("--partial") |
| 21 | + if ctx.file.input_file: |
| 22 | + additional_inputs.append(ctx.file.input_file) |
| 23 | + args.add("--input").add(ctx.file.input_file) |
| 24 | + if ctx.attr.input: |
| 25 | + input_file = ctx.actions.declare_file(ctx.label.name + "_input.txt") |
| 26 | + ctx.actions.write(output = input_file, content = ctx.attr.input) |
| 27 | + additional_inputs.append(input_file) |
| 28 | + args.add("--input").add(input_file) |
| 29 | + if ctx.attr.unknowns: |
| 30 | + args.add("--unknowns").add(",".join(ctx.attr.unknowns)) |
| 31 | + |
| 32 | + args.add("--format=%s" % (ctx.attr.format)) |
| 33 | + args.add(ctx.attr.query) |
| 34 | + |
| 35 | + ctx.actions.run_shell( |
| 36 | + tools = [toolchain.opa], |
| 37 | + inputs = [bundle] + additional_inputs, |
| 38 | + outputs = [out_file], |
| 39 | + arguments = [args], |
| 40 | + command = "$@ > " + out_file.path, |
| 41 | + ) |
| 42 | + |
| 43 | + return [ |
| 44 | + DefaultInfo( |
| 45 | + files = depset([out_file]), |
| 46 | + ), |
| 47 | + ] |
| 48 | + |
| 49 | +opa_eval = rule( |
| 50 | + implementation = _opa_eval_impl, |
| 51 | + attrs = { |
| 52 | + "deps": attr.label_list( |
| 53 | + providers = [OpaInfo], |
| 54 | + mandatory = True, |
| 55 | + doc = "The bundle to evaluate", |
| 56 | + ), |
| 57 | + "query": attr.string( |
| 58 | + mandatory = True, |
| 59 | + doc = "The query to evaluate", |
| 60 | + ), |
| 61 | + "out": attr.string( |
| 62 | + mandatory = True, |
| 63 | + doc = "Output file name", |
| 64 | + ), |
| 65 | + "format": attr.string( |
| 66 | + default = "json", |
| 67 | + values = ["json", "values", "bindings", "pretty", "source", "raw"], |
| 68 | + doc = "The output format (see https://www.openpolicyagent.org/docs/latest/cli/#output-formats)", |
| 69 | + ), |
| 70 | + "partial": attr.bool( |
| 71 | + default = False, |
| 72 | + doc = "perform partial evaluation", |
| 73 | + ), |
| 74 | + "unknowns": attr.string_list( |
| 75 | + doc = "set paths to treat as unknown during partial evaluation", |
| 76 | + ), |
| 77 | + "input": attr.string( |
| 78 | + doc = "input", |
| 79 | + ), |
| 80 | + "input_file": attr.label( |
| 81 | + allow_single_file = True, |
| 82 | + doc = "input", |
| 83 | + ), |
| 84 | + }, |
| 85 | + toolchains = ["//tools:toolchain_type"], |
| 86 | +) |
0 commit comments