package godumpimport ()// Diff prints a diff between two values to stdout.// @group Diff//// Example: print diff//// a := map[string]int{"a": 1}// b := map[string]int{"a": 2}// godump.Diff(a, b)// // <#diff // path:line// // - #map[string]int {// // - a => 1 #int// // - }// // + #map[string]int {// // + a => 2 #int// // + }func (, any) {defaultDumper.Diff(, )}// Diff prints a diff between two values to the configured writer.// @group Diff//// Example: print diff with a custom dumper//// d := godump.NewDumper()// a := map[string]int{"a": 1}// b := map[string]int{"a": 2}// d.Diff(a, b)// // <#diff // path:line// // - #map[string]int {// // - a => 1 #int// // - }// // + #map[string]int {// // + a => 2 #int// // + }func ( *Dumper) (, any) {fmt.Fprint(.writer, .DiffStr(, ))}// DiffStr returns a string diff between two values.// @group Diff//// Example: diff string//// a := map[string]int{"a": 1}// b := map[string]int{"a": 2}// out := godump.DiffStr(a, b)// _ = out// // <#diff // path:line// // - #map[string]int {// // - a => 1 #int// // - }// // + #map[string]int {// // + a => 2 #int// // + }func (, any) string {returndefaultDumper.DiffStr(, )}// DiffStr returns a string diff between two values.// @group Diff//// Example: diff string with a custom dumper//// d := godump.NewDumper()// a := map[string]int{"a": 1}// b := map[string]int{"a": 2}// out := d.DiffStr(a, b)// _ = out// // <#diff // path:line// // - #map[string]int {// // - a => 1 #int// // - }// // + #map[string]int {// // + a => 2 #int// // + }func ( *Dumper) (, any) string {varstrings.Builder .printDiffHeader(&) .ensureColorizer() := .diffDumps(, ) := splitLines(.left) := splitLines(.right) := diffLines(, )for , := range { .WriteString(.diffPrefix(.kind)) .WriteString(.diffTintLine(.text, .kind)) .WriteString("\n") }return .String()}// DiffHTML returns an HTML diff between two values.// @group Diff//// Example: HTML diff//// a := map[string]int{"a": 1}// b := map[string]int{"a": 2}// html := godump.DiffHTML(a, b)// _ = html// // (html diff)func (, any) string {returndefaultDumper.DiffHTML(, )}// DiffHTML returns an HTML diff between two values.// @group Diff//// Example: HTML diff with a custom dumper//// d := godump.NewDumper()// a := map[string]int{"a": 1}// b := map[string]int{"a": 2}// html := d.DiffHTML(a, b)// _ = html// // (html diff)func ( *Dumper) (, any) string {varstrings.Builder .WriteString(`<div style='background-color:black;'><pre style="background-color:black; color:white; padding:5px; border-radius: 5px">` + "\n") := .clone()if !.disableColor { .colorizer = colorizeHTML } .WriteString(.DiffStr(, )) .WriteString("</pre></div>")return .String()}type diffDumpPair struct { left string right string}// diffDumps builds the left and right dump strings, aligning reference ids.func ( *Dumper) (, any) diffDumpPair { := .dumpStrNoHeader() := .dumpStrNoHeader()ifreflect.TypeOf() != reflect.TypeOf() { := fmt.Sprintf("type: %s", .typeStringForAny()) := fmt.Sprintf("type: %s", .typeStringForAny()) = + "\n" + = + "\n" + }returndiffDumpPair{left: , right: }}// dumpStrNoHeader renders a dump without the header line.func ( *Dumper) ( ...any) string { .ensureColorizer() := newDumpState()varstrings.Builder := tabwriter.NewWriter(&, 0, 0, 1, ' ', 0) .writeDump(, , ...) .Flush()return .String()}// printDiffHeader writes the diff header line when a caller frame is available.func ( *Dumper) ( io.Writer) { , := .findFirstNonInternalFrame(.skippedStackFrames)if == "" {return } := if , := os.Getwd(); == nil {if , := filepath.Rel(, ); == nil { = } } := fmt.Sprintf("<#diff // %s:%d", , )fmt.Fprintln(, .colorize(colorGray, ))}// typeStringForAny returns a displayable type for a value.func ( *Dumper) ( any) string {if == nil {return"<nil>" }return .getTypeString(reflect.TypeOf())}type diffKind intconst ( diffEqual diffKind = iota diffDelete diffInsert)type diffLine struct { kind diffKind text string}// diffLines computes a line-level diff with insert/delete operations.func diffLines(, []string) []diffLine {iflen() == 0 && len() == 0 {returnnil } , := len(), len() := make([][]int, +1)for := 0; <= ; ++ { [] = make([]int, +1) }for := - 1; >= 0; -- {for := - 1; >= 0; -- {switch {case [] == []: [][] = [+1][+1] + 1case [+1][] >= [][+1]: [][] = [+1][]default: [][] = [][+1] } } } := make([]diffLine, 0, +) , := 0, 0for < && < {switch {case [] == []: = append(, diffLine{kind: diffEqual, text: []}) ++ ++continuecase [+1][] >= [][+1]: = append(, diffLine{kind: diffDelete, text: []}) ++default: = append(, diffLine{kind: diffInsert, text: []}) ++ } }for < { = append(, diffLine{kind: diffDelete, text: []}) ++ }for < { = append(, diffLine{kind: diffInsert, text: []}) ++ }return}// diffPrefix returns the colored diff marker prefix.func ( *Dumper) ( diffKind) string {switch {casediffDelete:return .colorize(colorRed, "-") + " "casediffInsert:return .colorize(colorGreen, "+") + " "default:return" " }}// diffTintLine tints a full diff line based on change type.func ( *Dumper) ( string, diffKind) string {if .disableColor {return }switch {casediffDelete:return .tintBackgroundLine(, colorRedBg, "#221010")casediffInsert:return .tintBackgroundLine(, colorGreenBg, "#102216")default:return }}// tintBackgroundLine applies a full-line background while preserving text colors.func ( *Dumper) (, , string) string {ifisHTMLLine() {return`<span style="background-color:` + + `; display:block; width:100%;">` + + `</span>` }ifstrings.Contains(, string(ansiEscape)+"[") {return + strings.ReplaceAll(, colorReset, colorReset+) + ansiEraseLine + colorReset }return + + ansiEraseLine + colorReset}const ansiEscape = '\x1b'const ansiEraseLine = "\x1b[K"// stripANSI removes ANSI escape sequences from a string.func stripANSI( string) string {varstrings.Builder .Grow(len())for := 0; < len(); {if [] != ansiEscape { .WriteByte([]) ++continue }// Skip ANSI CSI sequences like "\x1b[31m" or "\x1b[K".if +1 < len() && [+1] == '[' { += 2for < len() && ([] < '@' || [] > '~') { ++ }if < len() { ++ // consume final byte }continue }// Drop lone escape byte. ++ }return .String()}// stripHTMLSpans removes color span tags while preserving content.func stripHTMLSpans( string) string {const = `<span style="color:`const = `">`for { := strings.Index(, )if == -1 {break } := [+len():] , , := strings.Cut(, )if ! {break } := + len() + len() + len() = [:] + [:] }returnstrings.ReplaceAll(, "</span>", "")}// isHTMLLine reports whether the line contains HTML color spans.func isHTMLLine( string) bool {returnstrings.Contains(, `<span style="color:`)}// splitLines splits a string into lines while normalizing CRLF and trimming a trailing newline.func splitLines( string) []string { = strings.ReplaceAll(, "\r\n", "\n") = strings.ReplaceAll(, "\r", "\n") = strings.TrimSuffix(, "\n")if == "" {returnnil }returnstrings.Split(, "\n")}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.