1# Copyright 2018 Google LLC 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Provides the golden_file_test() rule.""" 16 17GOLDEN_FILE_CHECKER_TEMPLATE = """ 18#!/bin/bash 19set -o nounset 20set -o errexit 21 22readonly EXPECTED={EXPECTED} 23readonly ACTUAL={ACTUAL} 24 25diff -u --label EXPECTED "$EXPECTED" --label ACTUAL "$ACTUAL" 26readonly r=$? 27 28if (( $r != 0 )); then 29 echo "***" >&2 30 echo "*** FAIL: Contents of $ACTUAL do not match $EXPECTED" >&2 31 echo "***" >&2 32fi 33 34exit $r 35""" 36 37def _golden_file_test_impl(ctx): 38 replacements = { 39 "{EXPECTED}": repr(ctx.file.expected.short_path), 40 "{ACTUAL}": repr(ctx.file.actual.short_path), 41 } 42 43 contents = GOLDEN_FILE_CHECKER_TEMPLATE 44 for k, v in replacements.items(): 45 contents = contents.replace(k, v) 46 47 ctx.actions.write( 48 ctx.outputs.sh, 49 contents, 50 is_executable = True, 51 ) 52 53 runfiles = ctx.runfiles(files = [ctx.file.expected, ctx.file.actual]) 54 return [DefaultInfo(executable = ctx.outputs.sh, runfiles = runfiles)] 55 56golden_file_test = rule( 57 implementation = _golden_file_test_impl, 58 outputs = {"sh": "%{name}.sh"}, 59 test = True, 60 attrs = { 61 "actual": attr.label(allow_single_file = True), 62 "expected": attr.label(allow_single_file = True), 63 }, 64) 65"""Checks that two files are equal; fails with a text diff otherwise.""" 66