go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/diff/pretty_text.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package diff
     9  
    10  import (
    11  	"bytes"
    12  )
    13  
    14  // PrettyText converts a []Diff into a colored text report.
    15  func PrettyText(diffs []Diff) string {
    16  	var buff bytes.Buffer
    17  	for _, diff := range diffs {
    18  		text := diff.Text
    19  
    20  		switch diff.Type {
    21  		case DiffInsert:
    22  			_, _ = buff.WriteString("\x1b[32m")
    23  			_, _ = buff.WriteString(text)
    24  			_, _ = buff.WriteString("\x1b[0m")
    25  		case DiffDelete:
    26  			_, _ = buff.WriteString("\x1b[31m")
    27  			_, _ = buff.WriteString(text)
    28  			_, _ = buff.WriteString("\x1b[0m")
    29  		case DiffEqual:
    30  			_, _ = buff.WriteString(text)
    31  		}
    32  	}
    33  
    34  	return buff.String()
    35  }