github.phpd.cn/cilium/cilium@v1.6.12/pkg/comparator/comparator.go (about)

     1  // Copyright 2017-2018 Authors of Cilium
     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  package comparator
    16  
    17  import (
    18  	"github.com/kr/pretty"
    19  	"github.com/pmezard/go-difflib/difflib"
    20  )
    21  
    22  // Compare compares two interfaces and emits a unified diff as string
    23  func Compare(a, b interface{}) string {
    24  	return CompareWithNames(a, b, "a", "b")
    25  }
    26  
    27  // CompareWithNames compares two interfaces and emits a unified diff as string
    28  func CompareWithNames(a, b interface{}, nameA, nameB string) string {
    29  	stringA := pretty.Sprintf("%# v", a)
    30  	stringB := pretty.Sprintf("%# v", b)
    31  	diff := difflib.UnifiedDiff{
    32  		A:        difflib.SplitLines(stringA),
    33  		B:        difflib.SplitLines(stringB),
    34  		FromFile: nameA,
    35  		ToFile:   nameB,
    36  		Context:  32,
    37  	}
    38  
    39  	out, err := difflib.GetUnifiedDiffString(diff)
    40  	if err != nil {
    41  		return err.Error()
    42  	}
    43  	return "Unified diff:\n" + out
    44  }
    45  
    46  // MapStringEquals returns true if both maps are equal.
    47  func MapStringEquals(m1, m2 map[string]string) bool {
    48  	switch {
    49  	case m1 == nil && m2 == nil:
    50  		return true
    51  	case m1 == nil && m2 != nil,
    52  		m1 != nil && m2 == nil,
    53  		len(m1) != len(m2):
    54  		return false
    55  	}
    56  	for k1, v1 := range m1 {
    57  		if v2, ok := m2[k1]; !ok || v2 != v1 {
    58  			return false
    59  		}
    60  	}
    61  	return true
    62  }
    63  
    64  // MapBoolEquals returns true if both maps are equal.
    65  func MapBoolEquals(m1, m2 map[string]bool) bool {
    66  	switch {
    67  	case m1 == nil && m2 == nil:
    68  		return true
    69  	case m1 == nil && m2 != nil,
    70  		m1 != nil && m2 == nil,
    71  		len(m1) != len(m2):
    72  		return false
    73  	}
    74  	for k1, v1 := range m1 {
    75  		if v2, ok := m2[k1]; !ok || v2 != v1 {
    76  			return false
    77  		}
    78  	}
    79  	return true
    80  }