...

Source file src/cloud.google.com/go/internal/pretty/diff.go

Documentation: cloud.google.com/go/internal/pretty

     1  // Copyright 2016 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  //go:build linux
    16  // +build linux
    17  
    18  package pretty
    19  
    20  import (
    21  	"fmt"
    22  	"os"
    23  	"os/exec"
    24  	"syscall"
    25  )
    26  
    27  // Diff compares the pretty-printed representation of two values. The second
    28  // return value reports whether the two values' representations are identical.
    29  // If it is false, the first return value contains the diffs.
    30  //
    31  // The output labels the first value "want" and the second "got".
    32  //
    33  // Diff works by invoking the "diff" command. It will only succeed in
    34  // environments where "diff" is on the shell path.
    35  func Diff(want, got interface{}) (string, bool, error) {
    36  	fname1, err := writeToTemp(want)
    37  	if err != nil {
    38  		return "", false, err
    39  	}
    40  	defer os.Remove(fname1)
    41  
    42  	fname2, err := writeToTemp(got)
    43  	if err != nil {
    44  		return "", false, err
    45  	}
    46  	defer os.Remove(fname2)
    47  
    48  	cmd := exec.Command("diff", "-u", "--label=want", "--label=got", fname1, fname2)
    49  	out, err := cmd.Output()
    50  	if err == nil {
    51  		return string(out), true, nil
    52  	}
    53  	eerr, ok := err.(*exec.ExitError)
    54  	if !ok {
    55  		return "", false, err
    56  	}
    57  	ws, ok := eerr.Sys().(syscall.WaitStatus)
    58  	if !ok {
    59  		return "", false, err
    60  	}
    61  	if ws.ExitStatus() != 1 {
    62  		return "", false, err
    63  	}
    64  	// Exit status of 1 means no error, but diffs were found.
    65  	return string(out), false, nil
    66  }
    67  
    68  func writeToTemp(v interface{}) (string, error) {
    69  	f, err := os.CreateTemp("", "prettyDiff")
    70  	if err != nil {
    71  		return "", err
    72  	}
    73  	if _, err := fmt.Fprintf(f, "%+v\n", Value(v)); err != nil {
    74  		return "", err
    75  	}
    76  	if err := f.Close(); err != nil {
    77  		return "", err
    78  	}
    79  	return f.Name(), nil
    80  }
    81  

View as plain text