go-hep.org/x/hep@v0.38.1/internal/diff/diff.go (about)

     1  // Copyright ©2022 The go-hep Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package diff provides basic text comparison (like Unix's diff(1)).
     6  package diff // import "go-hep.org/x/hep/internal/diff"
     7  
     8  import (
     9  	"fmt"
    10  	"os"
    11  	"strings"
    12  
    13  	"github.com/pkg/diff"
    14  )
    15  
    16  // Format returns a formatted diff of the two texts,
    17  // showing the entire text and the minimum line-level
    18  // additions and removals to turn got into want.
    19  // (That is, lines only in got appear with a leading -,
    20  // and lines only in want appear with a leading +.)
    21  func Format(got, want string) string {
    22  	o := new(strings.Builder)
    23  	err := diff.Text("a/got", "b/want", got, want, o)
    24  	if err != nil {
    25  		panic(err)
    26  	}
    27  	return o.String()
    28  }
    29  
    30  // Files returns a formatted diff of the two texts from the provided
    31  // two file names.
    32  // Files returns nil if they compare equal.
    33  func Files(got, want string) error {
    34  	g, err := os.ReadFile(got)
    35  	if err != nil {
    36  		return fmt.Errorf("diff: could not read chk file %q: %w", got, err)
    37  	}
    38  	w, err := os.ReadFile(want)
    39  	if err != nil {
    40  		return fmt.Errorf("diff: could not read ref file %q: %w", want, err)
    41  	}
    42  
    43  	if got, want := string(g), string(w); got != want {
    44  		return fmt.Errorf("diff: files differ:\n%s", Format(got, want))
    45  	}
    46  
    47  	return nil
    48  }