github.com/Aoi-hosizora/ahlib-more@v1.5.1-0.20230404072844-256112befaf6/xdiff/xdiff.go (about) 1 package main 2 3 import ( 4 "github.com/Aoi-hosizora/ahlib/xcolor" 5 "github.com/pmezard/go-difflib/difflib" 6 "strings" 7 ) 8 9 // UnifiedDiffString aligns and colorizes the difflib.UnifiedDiff's compare result string returned from difflib.GetUnifiedDiffString. 10 func UnifiedDiffString(ud *difflib.UnifiedDiff) string { 11 s, _ := difflib.GetUnifiedDiffString(*ud) // ignore error, actually it will not return error 12 return colorize(s, ud.Eol, true) 13 } 14 15 // ContextDiffString aligns and colorizes the difflib.ContextDiff's compare result string returned from difflib.GetContextDiffString. 16 func ContextDiffString(cd *difflib.ContextDiff) string { 17 s, _ := difflib.GetContextDiffString(*cd) // ignore error 18 return colorize(s, cd.Eol, false) 19 } 20 21 // colorize aligns and colorizes given string. Note that alignment is only for unified diff, that is to add a space between prefix and content. 22 func colorize(s, eol string, unified bool) string { 23 if len(eol) == 0 { 24 eol = "\n" 25 } 26 lines := strings.Split(s, eol) 27 out := make([]string, 0, len(lines)) 28 29 for _, line := range lines { 30 minusColor := xcolor.BrightRed 31 plusColor := xcolor.BrightGreen 32 exclamationColor := xcolor.BrightYellow 33 normalColor := xcolor.BrightWhite 34 35 // 1. skip 36 if len(line) == 0 || strings.HasPrefix(line, "*** ") || strings.HasPrefix(line, "--- ") || strings.HasPrefix(line, "+++ ") || 37 strings.HasPrefix(line, "***************") || strings.HasPrefix(line, "@@ -") { 38 out = append(out, line) 39 continue 40 } 41 42 // 2. colorize 43 switch { 44 case strings.HasPrefix(line, "-"): 45 if len(line) == 1 { 46 line = "- " 47 } else if !unified { 48 line = "-" + line[1:] 49 } else { 50 line = "- " + line[1:] 51 } 52 line = minusColor.Sprint(line) 53 case strings.HasPrefix(line, "+"): 54 if len(line) == 1 { 55 line = "+ " 56 } else if !unified { 57 line = "+" + line[1:] 58 } else { 59 line = "+ " + line[1:] 60 } 61 line = plusColor.Sprint(line) 62 case strings.HasPrefix(line, "!"): 63 line = "!" + line[1:] 64 line = exclamationColor.Sprint(line) 65 case strings.HasPrefix(line, " "): 66 if len(line) == 1 { 67 line = " " 68 } else if !unified { 69 line = " " + line[1:] 70 } else { 71 line = " " + line[1:] 72 } 73 line = normalColor.Sprint(line) 74 } 75 out = append(out, line) 76 } 77 78 return strings.Join(out, eol) 79 }