github.com/anchore/syft@v1.4.2-0.20240516191711-1bec1fc5d397/internal/cmptest/diff_reporter.go (about)

     1  package cmptest
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/google/go-cmp/cmp"
     8  )
     9  
    10  // DiffReporter is a simple custom reporter that only records differences detected during comparison.
    11  type DiffReporter struct {
    12  	path  cmp.Path
    13  	diffs []string
    14  }
    15  
    16  func NewDiffReporter() DiffReporter {
    17  	return DiffReporter{}
    18  }
    19  
    20  func (r *DiffReporter) PushStep(ps cmp.PathStep) {
    21  	r.path = append(r.path, ps)
    22  }
    23  
    24  func (r *DiffReporter) Report(rs cmp.Result) {
    25  	if !rs.Equal() {
    26  		vx, vy := r.path.Last().Values()
    27  		r.diffs = append(r.diffs, fmt.Sprintf("%#v:\n\t-: %+v\n\t+: %+v\n", r.path, vx, vy))
    28  	}
    29  }
    30  
    31  func (r *DiffReporter) PopStep() {
    32  	r.path = r.path[:len(r.path)-1]
    33  }
    34  
    35  func (r *DiffReporter) String() string {
    36  	return strings.Join(r.diffs, "\n")
    37  }