|
| 1 | +def _golden_file_test_impl(ctx): |
| 2 | + outputs = [ctx.outputs.executable] |
| 3 | + |
| 4 | + content = "\n".join([ |
| 5 | + """ |
| 6 | +if diff -u {dst} {src}; then |
| 7 | + echo "files contents are identical" |
| 8 | +else |
| 9 | + echo "files differ" |
| 10 | + exit 1 |
| 11 | +fi |
| 12 | +""".format( |
| 13 | + src = src.short_path, |
| 14 | + dst = src.short_path + ".golden", |
| 15 | + ) |
| 16 | + for src in ctx.files.srcs |
| 17 | + ]) |
| 18 | + |
| 19 | + ctx.actions.write( |
| 20 | + ctx.outputs.executable, |
| 21 | + "set -x\n\n" + content, |
| 22 | + is_executable = True, |
| 23 | + ) |
| 24 | + return [ |
| 25 | + DefaultInfo( |
| 26 | + files = depset(outputs), |
| 27 | + runfiles = ctx.runfiles(files = ctx.files.srcs + ctx.files.goldens), |
| 28 | + ), |
| 29 | + ] |
| 30 | + |
| 31 | +_golden_file_test = rule( |
| 32 | + doc = "Asserts the two files are equal", |
| 33 | + implementation = _golden_file_test_impl, |
| 34 | + attrs = { |
| 35 | + "srcs": attr.label_list( |
| 36 | + doc = "the source files under test", |
| 37 | + allow_files = True, |
| 38 | + mandatory = True, |
| 39 | + ), |
| 40 | + "goldens": attr.label_list( |
| 41 | + doc = "the expected golden files", |
| 42 | + allow_files = True, |
| 43 | + mandatory = True, |
| 44 | + ), |
| 45 | + }, |
| 46 | + executable = True, |
| 47 | + test = True, |
| 48 | +) |
| 49 | + |
| 50 | +def _golden_file_update_impl(ctx): |
| 51 | + outputs = [ctx.outputs.executable] |
| 52 | + |
| 53 | + content = "\n".join([ |
| 54 | + """ |
| 55 | +cp -f {src} {dst} |
| 56 | +echo "Updated golden file: {dst}" |
| 57 | +""".format( |
| 58 | + src = src.short_path, |
| 59 | + dst = "$BUILD_WORKING_DIRECTORY/%s/%s.golden" % (ctx.label.package, src.basename), |
| 60 | + ) |
| 61 | + for src in ctx.files.srcs |
| 62 | + ]) |
| 63 | + |
| 64 | + ctx.actions.write( |
| 65 | + ctx.outputs.executable, |
| 66 | + "set -x\n\n" + content, |
| 67 | + is_executable = True, |
| 68 | + ) |
| 69 | + return [ |
| 70 | + DefaultInfo( |
| 71 | + files = depset(outputs), |
| 72 | + runfiles = ctx.runfiles(files = ctx.files.srcs), |
| 73 | + ), |
| 74 | + ] |
| 75 | + |
| 76 | +_golden_file_update = rule( |
| 77 | + doc = "Asserts the two files are equal", |
| 78 | + implementation = _golden_file_update_impl, |
| 79 | + attrs = { |
| 80 | + "srcs": attr.label_list( |
| 81 | + doc = "the source files to update", |
| 82 | + allow_files = True, |
| 83 | + mandatory = True, |
| 84 | + ), |
| 85 | + }, |
| 86 | + executable = True, |
| 87 | +) |
| 88 | + |
| 89 | +def golden_file_test(name, srcs, **kwargs): |
| 90 | + tags = kwargs.get("tags", []) |
| 91 | + _golden_file_test( |
| 92 | + name = name, |
| 93 | + srcs = srcs, |
| 94 | + goldens = native.glob(["*.golden"]), |
| 95 | + tags = tags, |
| 96 | + **kwargs |
| 97 | + ) |
| 98 | + _golden_file_update( |
| 99 | + name = name + ".update", |
| 100 | + srcs = srcs, |
| 101 | + tags = tags, |
| 102 | + ) |
0 commit comments