github.com/joelanford/operator-sdk@v0.8.2/internal/util/diffutil/diff_util.go (about)

     1  // Copyright 2018 The Operator-SDK Authors
     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 diffutil
    16  
    17  import (
    18  	"bytes"
    19  	"regexp"
    20  	"strings"
    21  
    22  	"github.com/sergi/go-diff/diffmatchpatch"
    23  )
    24  
    25  func Diff(a, b string) string {
    26  	dmp := diffmatchpatch.New()
    27  
    28  	wSrc, wDst, warray := dmp.DiffLinesToRunes(a, b)
    29  	diffs := dmp.DiffMainRunes(wSrc, wDst, false)
    30  	diffs = dmp.DiffCharsToLines(diffs, warray)
    31  	var buff bytes.Buffer
    32  	for _, diff := range diffs {
    33  		text := diff.Text
    34  
    35  		switch diff.Type {
    36  		case diffmatchpatch.DiffInsert:
    37  			_, _ = buff.WriteString("\x1b[32m")
    38  			_, _ = buff.WriteString(prefixLines(text, "+"))
    39  			_, _ = buff.WriteString("\x1b[0m")
    40  		case diffmatchpatch.DiffDelete:
    41  			_, _ = buff.WriteString("\x1b[31m")
    42  			_, _ = buff.WriteString(prefixLines(text, "-"))
    43  			_, _ = buff.WriteString("\x1b[0m")
    44  		case diffmatchpatch.DiffEqual:
    45  			_, _ = buff.WriteString(prefixLines(text, " "))
    46  		}
    47  	}
    48  	return buff.String()
    49  }
    50  
    51  func prefixLines(s, prefix string) string {
    52  	var buf bytes.Buffer
    53  	lines := strings.Split(s, "\n")
    54  	ls := regexp.MustCompile("^")
    55  	for _, line := range lines[:len(lines)-1] {
    56  		buf.WriteString(ls.ReplaceAllString(line, prefix))
    57  		buf.WriteString("\n")
    58  	}
    59  	return buf.String()
    60  }