pax_global_header00006660000000000000000000000064137573036560014531gustar00rootroot0000000000000052 comment=a883a8422cd235c67c6c4fdcb7bbb022143e10b1 pretty-0.3.0/000077500000000000000000000000001375730365600130605ustar00rootroot00000000000000pretty-0.3.0/.github/000077500000000000000000000000001375730365600144205ustar00rootroot00000000000000pretty-0.3.0/.github/workflows/000077500000000000000000000000001375730365600164555ustar00rootroot00000000000000pretty-0.3.0/.github/workflows/build-test.yml000066400000000000000000000004521375730365600212550ustar00rootroot00000000000000name: build-test on: push: pull_request: jobs: test: runs-on: ubuntu-latest steps: - uses: actions/setup-go@v1 with: go-version: 1.13.x - uses: actions/checkout@v2 - name: Build run: go build . - name: Test run: go test -v . pretty-0.3.0/.gitignore000066400000000000000000000000331375730365600150440ustar00rootroot00000000000000[568].out _go* _test* _obj pretty-0.3.0/License000066400000000000000000000020341375730365600143640ustar00rootroot00000000000000Copyright 2012 Keith Rarick Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pretty-0.3.0/Readme000066400000000000000000000002501375730365600141750ustar00rootroot00000000000000package pretty import "github.com/kr/pretty" Package pretty provides pretty-printing for Go values. Documentation http://godoc.org/github.com/kr/pretty pretty-0.3.0/diff.go000066400000000000000000000162621375730365600143260ustar00rootroot00000000000000package pretty import ( "fmt" "io" "reflect" ) type sbuf []string func (p *sbuf) Printf(format string, a ...interface{}) { s := fmt.Sprintf(format, a...) *p = append(*p, s) } // Diff returns a slice where each element describes // a difference between a and b. func Diff(a, b interface{}) (desc []string) { Pdiff((*sbuf)(&desc), a, b) return desc } // wprintfer calls Fprintf on w for each Printf call // with a trailing newline. type wprintfer struct{ w io.Writer } func (p *wprintfer) Printf(format string, a ...interface{}) { fmt.Fprintf(p.w, format+"\n", a...) } // Fdiff writes to w a description of the differences between a and b. func Fdiff(w io.Writer, a, b interface{}) { Pdiff(&wprintfer{w}, a, b) } type Printfer interface { Printf(format string, a ...interface{}) } // Pdiff prints to p a description of the differences between a and b. // It calls Printf once for each difference, with no trailing newline. // The standard library log.Logger is a Printfer. func Pdiff(p Printfer, a, b interface{}) { d := diffPrinter{ w: p, aVisited: make(map[visit]visit), bVisited: make(map[visit]visit), } d.diff(reflect.ValueOf(a), reflect.ValueOf(b)) } type Logfer interface { Logf(format string, a ...interface{}) } // logprintfer calls Fprintf on w for each Printf call // with a trailing newline. type logprintfer struct{ l Logfer } func (p *logprintfer) Printf(format string, a ...interface{}) { p.l.Logf(format, a...) } // Ldiff prints to l a description of the differences between a and b. // It calls Logf once for each difference, with no trailing newline. // The standard library testing.T and testing.B are Logfers. func Ldiff(l Logfer, a, b interface{}) { Pdiff(&logprintfer{l}, a, b) } type diffPrinter struct { w Printfer l string // label aVisited map[visit]visit bVisited map[visit]visit } func (w diffPrinter) printf(f string, a ...interface{}) { var l string if w.l != "" { l = w.l + ": " } w.w.Printf(l+f, a...) } func (w diffPrinter) diff(av, bv reflect.Value) { if !av.IsValid() && bv.IsValid() { w.printf("nil != %# v", formatter{v: bv, quote: true}) return } if av.IsValid() && !bv.IsValid() { w.printf("%# v != nil", formatter{v: av, quote: true}) return } if !av.IsValid() && !bv.IsValid() { return } at := av.Type() bt := bv.Type() if at != bt { w.printf("%v != %v", at, bt) return } if av.CanAddr() && bv.CanAddr() { avis := visit{av.UnsafeAddr(), at} bvis := visit{bv.UnsafeAddr(), bt} var cycle bool // Have we seen this value before? if vis, ok := w.aVisited[avis]; ok { cycle = true if vis != bvis { w.printf("%# v (previously visited) != %# v", formatter{v: av, quote: true}, formatter{v: bv, quote: true}) } } else if _, ok := w.bVisited[bvis]; ok { cycle = true w.printf("%# v != %# v (previously visited)", formatter{v: av, quote: true}, formatter{v: bv, quote: true}) } w.aVisited[avis] = bvis w.bVisited[bvis] = avis if cycle { return } } switch kind := at.Kind(); kind { case reflect.Bool: if a, b := av.Bool(), bv.Bool(); a != b { w.printf("%v != %v", a, b) } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if a, b := av.Int(), bv.Int(); a != b { w.printf("%d != %d", a, b) } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: if a, b := av.Uint(), bv.Uint(); a != b { w.printf("%d != %d", a, b) } case reflect.Float32, reflect.Float64: if a, b := av.Float(), bv.Float(); a != b { w.printf("%v != %v", a, b) } case reflect.Complex64, reflect.Complex128: if a, b := av.Complex(), bv.Complex(); a != b { w.printf("%v != %v", a, b) } case reflect.Array: n := av.Len() for i := 0; i < n; i++ { w.relabel(fmt.Sprintf("[%d]", i)).diff(av.Index(i), bv.Index(i)) } case reflect.Chan, reflect.Func, reflect.UnsafePointer: if a, b := av.Pointer(), bv.Pointer(); a != b { w.printf("%#x != %#x", a, b) } case reflect.Interface: w.diff(av.Elem(), bv.Elem()) case reflect.Map: ak, both, bk := keyDiff(av.MapKeys(), bv.MapKeys()) for _, k := range ak { w := w.relabel(fmt.Sprintf("[%#v]", k)) w.printf("%q != (missing)", av.MapIndex(k)) } for _, k := range both { w := w.relabel(fmt.Sprintf("[%#v]", k)) w.diff(av.MapIndex(k), bv.MapIndex(k)) } for _, k := range bk { w := w.relabel(fmt.Sprintf("[%#v]", k)) w.printf("(missing) != %q", bv.MapIndex(k)) } case reflect.Ptr: switch { case av.IsNil() && !bv.IsNil(): w.printf("nil != %# v", formatter{v: bv, quote: true}) case !av.IsNil() && bv.IsNil(): w.printf("%# v != nil", formatter{v: av, quote: true}) case !av.IsNil() && !bv.IsNil(): w.diff(av.Elem(), bv.Elem()) } case reflect.Slice: lenA := av.Len() lenB := bv.Len() if lenA != lenB { w.printf("%s[%d] != %s[%d]", av.Type(), lenA, bv.Type(), lenB) break } for i := 0; i < lenA; i++ { w.relabel(fmt.Sprintf("[%d]", i)).diff(av.Index(i), bv.Index(i)) } case reflect.String: if a, b := av.String(), bv.String(); a != b { w.printf("%q != %q", a, b) } case reflect.Struct: for i := 0; i < av.NumField(); i++ { w.relabel(at.Field(i).Name).diff(av.Field(i), bv.Field(i)) } default: panic("unknown reflect Kind: " + kind.String()) } } func (d diffPrinter) relabel(name string) (d1 diffPrinter) { d1 = d if d.l != "" && name[0] != '[' { d1.l += "." } d1.l += name return d1 } // keyEqual compares a and b for equality. // Both a and b must be valid map keys. func keyEqual(av, bv reflect.Value) bool { if !av.IsValid() && !bv.IsValid() { return true } if !av.IsValid() || !bv.IsValid() || av.Type() != bv.Type() { return false } switch kind := av.Kind(); kind { case reflect.Bool: a, b := av.Bool(), bv.Bool() return a == b case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: a, b := av.Int(), bv.Int() return a == b case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: a, b := av.Uint(), bv.Uint() return a == b case reflect.Float32, reflect.Float64: a, b := av.Float(), bv.Float() return a == b case reflect.Complex64, reflect.Complex128: a, b := av.Complex(), bv.Complex() return a == b case reflect.Array: for i := 0; i < av.Len(); i++ { if !keyEqual(av.Index(i), bv.Index(i)) { return false } } return true case reflect.Chan, reflect.UnsafePointer, reflect.Ptr: a, b := av.Pointer(), bv.Pointer() return a == b case reflect.Interface: return keyEqual(av.Elem(), bv.Elem()) case reflect.String: a, b := av.String(), bv.String() return a == b case reflect.Struct: for i := 0; i < av.NumField(); i++ { if !keyEqual(av.Field(i), bv.Field(i)) { return false } } return true default: panic("invalid map key type " + av.Type().String()) } } func keyDiff(a, b []reflect.Value) (ak, both, bk []reflect.Value) { for _, av := range a { inBoth := false for _, bv := range b { if keyEqual(av, bv) { inBoth = true both = append(both, av) break } } if !inBoth { ak = append(ak, av) } } for _, bv := range b { inBoth := false for _, av := range a { if keyEqual(av, bv) { inBoth = true break } } if !inBoth { bk = append(bk, bv) } } return } pretty-0.3.0/diff_test.go000066400000000000000000000172671375730365600153730ustar00rootroot00000000000000package pretty import ( "bytes" "fmt" "log" "reflect" "testing" "unsafe" ) var ( _ Logfer = (*testing.T)(nil) _ Logfer = (*testing.B)(nil) _ Printfer = (*log.Logger)(nil) ) type difftest struct { a interface{} b interface{} exp []string } type S struct { A int S *S I interface{} C []int } type ( N struct{ N int } E interface{} ) var ( c0 = make(chan int) c1 = make(chan int) f0 = func() {} f1 = func() {} i0 = 0 i1 = 1 ) var diffs = []difftest{ {a: nil, b: nil}, {a: S{A: 1}, b: S{A: 1}}, {0, "", []string{`int != string`}}, {0, 1, []string{`0 != 1`}}, {S{}, new(S), []string{`pretty.S != *pretty.S`}}, {"a", "b", []string{`"a" != "b"`}}, {S{}, S{A: 1}, []string{`A: 0 != 1`}}, {new(S), &S{A: 1}, []string{`A: 0 != 1`}}, {S{S: new(S)}, S{S: &S{A: 1}}, []string{`S.A: 0 != 1`}}, {S{}, S{I: 0}, []string{`I: nil != int(0)`}}, {S{I: 1}, S{I: "x"}, []string{`I: int != string`}}, {S{}, S{C: []int{1}}, []string{`C: []int[0] != []int[1]`}}, {S{C: []int{}}, S{C: []int{1}}, []string{`C: []int[0] != []int[1]`}}, {S{C: []int{1, 2, 3}}, S{C: []int{1, 2, 4}}, []string{`C[2]: 3 != 4`}}, {S{}, S{A: 1, S: new(S)}, []string{`A: 0 != 1`, `S: nil != &pretty.S{}`}}, // unexported fields of every reflect.Kind (both equal and unequal) {struct{ x bool }{false}, struct{ x bool }{false}, nil}, {struct{ x bool }{false}, struct{ x bool }{true}, []string{`x: false != true`}}, {struct{ x int }{0}, struct{ x int }{0}, nil}, {struct{ x int }{0}, struct{ x int }{1}, []string{`x: 0 != 1`}}, {struct{ x int8 }{0}, struct{ x int8 }{0}, nil}, {struct{ x int8 }{0}, struct{ x int8 }{1}, []string{`x: 0 != 1`}}, {struct{ x int16 }{0}, struct{ x int16 }{0}, nil}, {struct{ x int16 }{0}, struct{ x int16 }{1}, []string{`x: 0 != 1`}}, {struct{ x int32 }{0}, struct{ x int32 }{0}, nil}, {struct{ x int32 }{0}, struct{ x int32 }{1}, []string{`x: 0 != 1`}}, {struct{ x int64 }{0}, struct{ x int64 }{0}, nil}, {struct{ x int64 }{0}, struct{ x int64 }{1}, []string{`x: 0 != 1`}}, {struct{ x uint }{0}, struct{ x uint }{0}, nil}, {struct{ x uint }{0}, struct{ x uint }{1}, []string{`x: 0 != 1`}}, {struct{ x uint8 }{0}, struct{ x uint8 }{0}, nil}, {struct{ x uint8 }{0}, struct{ x uint8 }{1}, []string{`x: 0 != 1`}}, {struct{ x uint16 }{0}, struct{ x uint16 }{0}, nil}, {struct{ x uint16 }{0}, struct{ x uint16 }{1}, []string{`x: 0 != 1`}}, {struct{ x uint32 }{0}, struct{ x uint32 }{0}, nil}, {struct{ x uint32 }{0}, struct{ x uint32 }{1}, []string{`x: 0 != 1`}}, {struct{ x uint64 }{0}, struct{ x uint64 }{0}, nil}, {struct{ x uint64 }{0}, struct{ x uint64 }{1}, []string{`x: 0 != 1`}}, {struct{ x uintptr }{0}, struct{ x uintptr }{0}, nil}, {struct{ x uintptr }{0}, struct{ x uintptr }{1}, []string{`x: 0 != 1`}}, {struct{ x float32 }{0}, struct{ x float32 }{0}, nil}, {struct{ x float32 }{0}, struct{ x float32 }{1}, []string{`x: 0 != 1`}}, {struct{ x float64 }{0}, struct{ x float64 }{0}, nil}, {struct{ x float64 }{0}, struct{ x float64 }{1}, []string{`x: 0 != 1`}}, {struct{ x complex64 }{0}, struct{ x complex64 }{0}, nil}, {struct{ x complex64 }{0}, struct{ x complex64 }{1}, []string{`x: (0+0i) != (1+0i)`}}, {struct{ x complex128 }{0}, struct{ x complex128 }{0}, nil}, {struct{ x complex128 }{0}, struct{ x complex128 }{1}, []string{`x: (0+0i) != (1+0i)`}}, {struct{ x [1]int }{[1]int{0}}, struct{ x [1]int }{[1]int{0}}, nil}, {struct{ x [1]int }{[1]int{0}}, struct{ x [1]int }{[1]int{1}}, []string{`x[0]: 0 != 1`}}, {struct{ x chan int }{c0}, struct{ x chan int }{c0}, nil}, {struct{ x chan int }{c0}, struct{ x chan int }{c1}, []string{fmt.Sprintf("x: %p != %p", c0, c1)}}, {struct{ x func() }{f0}, struct{ x func() }{f0}, nil}, {struct{ x func() }{f0}, struct{ x func() }{f1}, []string{fmt.Sprintf("x: %p != %p", f0, f1)}}, {struct{ x interface{} }{0}, struct{ x interface{} }{0}, nil}, {struct{ x interface{} }{0}, struct{ x interface{} }{1}, []string{`x: 0 != 1`}}, {struct{ x interface{} }{0}, struct{ x interface{} }{""}, []string{`x: int != string`}}, {struct{ x interface{} }{0}, struct{ x interface{} }{nil}, []string{`x: int(0) != nil`}}, {struct{ x interface{} }{nil}, struct{ x interface{} }{0}, []string{`x: nil != int(0)`}}, {struct{ x map[int]int }{map[int]int{0: 0}}, struct{ x map[int]int }{map[int]int{0: 0}}, nil}, {struct{ x map[int]int }{map[int]int{0: 0}}, struct{ x map[int]int }{map[int]int{0: 1}}, []string{`x[0]: 0 != 1`}}, {struct{ x *int }{new(int)}, struct{ x *int }{new(int)}, nil}, {struct{ x *int }{&i0}, struct{ x *int }{&i1}, []string{`x: 0 != 1`}}, {struct{ x *int }{nil}, struct{ x *int }{&i0}, []string{`x: nil != &int(0)`}}, {struct{ x *int }{&i0}, struct{ x *int }{nil}, []string{`x: &int(0) != nil`}}, {struct{ x []int }{[]int{0}}, struct{ x []int }{[]int{0}}, nil}, {struct{ x []int }{[]int{0}}, struct{ x []int }{[]int{1}}, []string{`x[0]: 0 != 1`}}, {struct{ x string }{"a"}, struct{ x string }{"a"}, nil}, {struct{ x string }{"a"}, struct{ x string }{"b"}, []string{`x: "a" != "b"`}}, {struct{ x N }{N{0}}, struct{ x N }{N{0}}, nil}, {struct{ x N }{N{0}}, struct{ x N }{N{1}}, []string{`x.N: 0 != 1`}}, { struct{ x unsafe.Pointer }{unsafe.Pointer(uintptr(0))}, struct{ x unsafe.Pointer }{unsafe.Pointer(uintptr(0))}, nil, }, { struct{ x unsafe.Pointer }{unsafe.Pointer(uintptr(0))}, struct{ x unsafe.Pointer }{unsafe.Pointer(uintptr(1))}, []string{`x: 0x0 != 0x1`}, }, } func TestDiff(t *testing.T) { for _, tt := range diffs { expectDiffOutput(t, tt.a, tt.b, tt.exp) } } func expectDiffOutput(t *testing.T, a, b interface{}, exp []string) { got := Diff(a, b) eq := len(got) == len(exp) if eq { for i := range got { eq = eq && got[i] == exp[i] } } if !eq { t.Errorf("diffing % #v", a) t.Errorf("with % #v", b) diffdiff(t, got, exp) } } func TestKeyEqual(t *testing.T) { var emptyInterfaceZero interface{} = 0 cases := []interface{}{ new(bool), new(int), new(int8), new(int16), new(int32), new(int64), new(uint), new(uint8), new(uint16), new(uint32), new(uint64), new(uintptr), new(float32), new(float64), new(complex64), new(complex128), new([1]int), new(chan int), new(unsafe.Pointer), new(interface{}), &emptyInterfaceZero, new(*int), new(string), new(struct{ int }), } for _, test := range cases { rv := reflect.ValueOf(test).Elem() if !keyEqual(rv, rv) { t.Errorf("keyEqual(%s, %s) = false want true", rv.Type(), rv.Type()) } } } func TestFdiff(t *testing.T) { var buf bytes.Buffer Fdiff(&buf, 0, 1) want := "0 != 1\n" if got := buf.String(); got != want { t.Errorf("Fdiff(0, 1) = %q want %q", got, want) } } func TestDiffCycle(t *testing.T) { // Diff two cyclic structs a := &I{i: 1, R: nil} a.R = a b := &I{i: 2, R: nil} b.R = b expectDiffOutput(t, a, b, []string{ `i: 1 != 2`, }) // Diff two equal cyclic structs b.i = 1 expectDiffOutput(t, a, b, []string{}) // Diff two structs with different cycles b2 := &I{i: 1, R: b} b.R = b2 expectDiffOutput(t, a, b, []string{`R: pretty.I{ i: 1, R: &pretty.I{(CYCLIC REFERENCE)}, } (previously visited) != pretty.I{ i: 1, R: &pretty.I{ i: 1, R: &pretty.I{(CYCLIC REFERENCE)}, }, }`}) // ... and the same in the other direction expectDiffOutput(t, b, a, []string{`R: pretty.I{ i: 1, R: &pretty.I{ i: 1, R: &pretty.I{(CYCLIC REFERENCE)}, }, } != pretty.I{ i: 1, R: &pretty.I{(CYCLIC REFERENCE)}, } (previously visited)`}) } func diffdiff(t *testing.T, got, exp []string) { minus(t, "unexpected:", got, exp) minus(t, "missing:", exp, got) } func minus(t *testing.T, s string, a, b []string) { var i, j int for i = 0; i < len(a); i++ { for j = 0; j < len(b); j++ { if a[i] == b[j] { break } } if j == len(b) { t.Error(s, a[i]) } } } pretty-0.3.0/example_test.go000066400000000000000000000004621375730365600161030ustar00rootroot00000000000000package pretty_test import ( "fmt" "github.com/kr/pretty" ) func Example() { type myType struct { a, b int } var x = []myType{{1, 2}, {3, 4}, {5, 6}} fmt.Printf("%# v", pretty.Formatter(x)) // output: // []pretty_test.myType{ // {a:1, b:2}, // {a:3, b:4}, // {a:5, b:6}, // } } pretty-0.3.0/formatter.go000066400000000000000000000165161375730365600154230ustar00rootroot00000000000000package pretty import ( "fmt" "io" "reflect" "strconv" "text/tabwriter" "github.com/kr/text" "github.com/rogpeppe/go-internal/fmtsort" ) type formatter struct { v reflect.Value force bool quote bool } // Formatter makes a wrapper, f, that will format x as go source with line // breaks and tabs. Object f responds to the "%v" formatting verb when both the // "#" and " " (space) flags are set, for example: // // fmt.Sprintf("%# v", Formatter(x)) // // If one of these two flags is not set, or any other verb is used, f will // format x according to the usual rules of package fmt. // In particular, if x satisfies fmt.Formatter, then x.Format will be called. func Formatter(x interface{}) (f fmt.Formatter) { return formatter{v: reflect.ValueOf(x), quote: true} } func (fo formatter) String() string { return fmt.Sprint(fo.v.Interface()) // unwrap it } func (fo formatter) passThrough(f fmt.State, c rune) { s := "%" for i := 0; i < 128; i++ { if f.Flag(i) { s += string(rune(i)) } } if w, ok := f.Width(); ok { s += fmt.Sprintf("%d", w) } if p, ok := f.Precision(); ok { s += fmt.Sprintf(".%d", p) } s += string(c) fmt.Fprintf(f, s, fo.v.Interface()) } func (fo formatter) Format(f fmt.State, c rune) { if fo.force || c == 'v' && f.Flag('#') && f.Flag(' ') { w := tabwriter.NewWriter(f, 4, 4, 1, ' ', 0) p := &printer{tw: w, Writer: w, visited: make(map[visit]int)} p.printValue(fo.v, true, fo.quote) w.Flush() return } fo.passThrough(f, c) } type printer struct { io.Writer tw *tabwriter.Writer visited map[visit]int depth int } func (p *printer) indent() *printer { q := *p q.tw = tabwriter.NewWriter(p.Writer, 4, 4, 1, ' ', 0) q.Writer = text.NewIndentWriter(q.tw, []byte{'\t'}) return &q } func (p *printer) printInline(v reflect.Value, x interface{}, showType bool) { if showType { io.WriteString(p, v.Type().String()) fmt.Fprintf(p, "(%#v)", x) } else { fmt.Fprintf(p, "%#v", x) } } // printValue must keep track of already-printed pointer values to avoid // infinite recursion. type visit struct { v uintptr typ reflect.Type } func (p *printer) printValue(v reflect.Value, showType, quote bool) { if p.depth > 10 { io.WriteString(p, "!%v(DEPTH EXCEEDED)") return } if v.IsValid() && v.CanInterface() { i := v.Interface() if goStringer, ok := i.(fmt.GoStringer); ok { io.WriteString(p, goStringer.GoString()) return } } switch v.Kind() { case reflect.Bool: p.printInline(v, v.Bool(), showType) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: p.printInline(v, v.Int(), showType) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: p.printInline(v, v.Uint(), showType) case reflect.Float32, reflect.Float64: p.printInline(v, v.Float(), showType) case reflect.Complex64, reflect.Complex128: fmt.Fprintf(p, "%#v", v.Complex()) case reflect.String: p.fmtString(v.String(), quote) case reflect.Map: t := v.Type() if showType { io.WriteString(p, t.String()) } writeByte(p, '{') if nonzero(v) { expand := !canInline(v.Type()) pp := p if expand { writeByte(p, '\n') pp = p.indent() } sm := fmtsort.Sort(v) for i := 0; i < v.Len(); i++ { k := sm.Key[i] mv := sm.Value[i] pp.printValue(k, false, true) writeByte(pp, ':') if expand { writeByte(pp, '\t') } showTypeInStruct := t.Elem().Kind() == reflect.Interface pp.printValue(mv, showTypeInStruct, true) if expand { io.WriteString(pp, ",\n") } else if i < v.Len()-1 { io.WriteString(pp, ", ") } } if expand { pp.tw.Flush() } } writeByte(p, '}') case reflect.Struct: t := v.Type() if v.CanAddr() { addr := v.UnsafeAddr() vis := visit{addr, t} if vd, ok := p.visited[vis]; ok && vd < p.depth { p.fmtString(t.String()+"{(CYCLIC REFERENCE)}", false) break // don't print v again } p.visited[vis] = p.depth } if showType { io.WriteString(p, t.String()) } writeByte(p, '{') if nonzero(v) { expand := !canInline(v.Type()) pp := p if expand { writeByte(p, '\n') pp = p.indent() } for i := 0; i < v.NumField(); i++ { showTypeInStruct := true if f := t.Field(i); f.Name != "" { io.WriteString(pp, f.Name) writeByte(pp, ':') if expand { writeByte(pp, '\t') } showTypeInStruct = labelType(f.Type) } pp.printValue(getField(v, i), showTypeInStruct, true) if expand { io.WriteString(pp, ",\n") } else if i < v.NumField()-1 { io.WriteString(pp, ", ") } } if expand { pp.tw.Flush() } } writeByte(p, '}') case reflect.Interface: switch e := v.Elem(); { case e.Kind() == reflect.Invalid: io.WriteString(p, "nil") case e.IsValid(): pp := *p pp.depth++ pp.printValue(e, showType, true) default: io.WriteString(p, v.Type().String()) io.WriteString(p, "(nil)") } case reflect.Array, reflect.Slice: t := v.Type() if showType { io.WriteString(p, t.String()) } if v.Kind() == reflect.Slice && v.IsNil() && showType { io.WriteString(p, "(nil)") break } if v.Kind() == reflect.Slice && v.IsNil() { io.WriteString(p, "nil") break } writeByte(p, '{') expand := !canInline(v.Type()) pp := p if expand { writeByte(p, '\n') pp = p.indent() } for i := 0; i < v.Len(); i++ { showTypeInSlice := t.Elem().Kind() == reflect.Interface pp.printValue(v.Index(i), showTypeInSlice, true) if expand { io.WriteString(pp, ",\n") } else if i < v.Len()-1 { io.WriteString(pp, ", ") } } if expand { pp.tw.Flush() } writeByte(p, '}') case reflect.Ptr: e := v.Elem() if !e.IsValid() { writeByte(p, '(') io.WriteString(p, v.Type().String()) io.WriteString(p, ")(nil)") } else { pp := *p pp.depth++ writeByte(pp, '&') pp.printValue(e, true, true) } case reflect.Chan: x := v.Pointer() if showType { writeByte(p, '(') io.WriteString(p, v.Type().String()) fmt.Fprintf(p, ")(%#v)", x) } else { fmt.Fprintf(p, "%#v", x) } case reflect.Func: io.WriteString(p, v.Type().String()) io.WriteString(p, " {...}") case reflect.UnsafePointer: p.printInline(v, v.Pointer(), showType) case reflect.Invalid: io.WriteString(p, "nil") } } func canInline(t reflect.Type) bool { switch t.Kind() { case reflect.Map: return !canExpand(t.Elem()) case reflect.Struct: for i := 0; i < t.NumField(); i++ { if canExpand(t.Field(i).Type) { return false } } return true case reflect.Interface: return false case reflect.Array, reflect.Slice: return !canExpand(t.Elem()) case reflect.Ptr: return false case reflect.Chan, reflect.Func, reflect.UnsafePointer: return false } return true } func canExpand(t reflect.Type) bool { switch t.Kind() { case reflect.Map, reflect.Struct, reflect.Interface, reflect.Array, reflect.Slice, reflect.Ptr: return true } return false } func labelType(t reflect.Type) bool { switch t.Kind() { case reflect.Interface, reflect.Struct: return true } return false } func (p *printer) fmtString(s string, quote bool) { if quote { s = strconv.Quote(s) } io.WriteString(p, s) } func writeByte(w io.Writer, b byte) { w.Write([]byte{b}) } func getField(v reflect.Value, i int) reflect.Value { val := v.Field(i) if val.Kind() == reflect.Interface && !val.IsNil() { val = val.Elem() } return val } pretty-0.3.0/formatter_test.go000066400000000000000000000126741375730365600164630ustar00rootroot00000000000000package pretty import ( "fmt" "io" "strings" "testing" "unsafe" ) type test struct { v interface{} s string } type passtest struct { v interface{} f, s string } type LongStructTypeName struct { longFieldName interface{} otherLongFieldName interface{} } type SA struct { t *T v T } type T struct { x, y int } type F int func (f F) Format(s fmt.State, c rune) { fmt.Fprintf(s, "F(%d)", int(f)) } type Stringer struct{ i int } func (s *Stringer) String() string { return "foo" } var long = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" var passthrough = []passtest{ {1, "%d", "1"}, {"a", "%s", "a"}, {&Stringer{}, "%s", "foo"}, } func TestPassthrough(t *testing.T) { for _, tt := range passthrough { s := fmt.Sprintf(tt.f, Formatter(tt.v)) if tt.s != s { t.Errorf("expected %q", tt.s) t.Errorf("got %q", s) t.Errorf("expraw\n%s", tt.s) t.Errorf("gotraw\n%s", s) } } } type StructWithPrivateFields struct { A string b string } func NewStructWithPrivateFields(a string) StructWithPrivateFields { return StructWithPrivateFields{a, "fixedb"} } func (s StructWithPrivateFields) GoString() string { return fmt.Sprintf("NewStructWithPrivateFields(%q)", s.A) } var gosyntax = []test{ {nil, `nil`}, {"", `""`}, {"a", `"a"`}, {1, "int(1)"}, {1.0, "float64(1)"}, {[]int(nil), "[]int(nil)"}, {[0]int{}, "[0]int{}"}, {complex(1, 0), "(1+0i)"}, //{make(chan int), "(chan int)(0x1234)"}, {unsafe.Pointer(uintptr(unsafe.Pointer(&long))), fmt.Sprintf("unsafe.Pointer(0x%02x)", uintptr(unsafe.Pointer(&long)))}, {func(int) {}, "func(int) {...}"}, {map[string]string{"a": "a", "b": "b"}, "map[string]string{\"a\":\"a\", \"b\":\"b\"}"}, {map[int]int{1: 1}, "map[int]int{1:1}"}, {int32(1), "int32(1)"}, {io.EOF, `&errors.errorString{s:"EOF"}`}, {[]string{"a"}, `[]string{"a"}`}, { []string{long}, `[]string{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"}`, }, {F(5), "pretty.F(5)"}, { NewStructWithPrivateFields("foo"), `NewStructWithPrivateFields("foo")`}, { SA{&T{1, 2}, T{3, 4}}, `pretty.SA{ t: &pretty.T{x:1, y:2}, v: pretty.T{x:3, y:4}, }`, }, { map[int][]byte{1: {}}, `map[int][]uint8{ 1: {}, }`, }, { map[int]T{1: {}}, `map[int]pretty.T{ 1: {}, }`, }, { long, `"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"`, }, { LongStructTypeName{ longFieldName: LongStructTypeName{}, otherLongFieldName: long, }, `pretty.LongStructTypeName{ longFieldName: pretty.LongStructTypeName{}, otherLongFieldName: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", }`, }, { &LongStructTypeName{ longFieldName: &LongStructTypeName{}, otherLongFieldName: (*LongStructTypeName)(nil), }, `&pretty.LongStructTypeName{ longFieldName: &pretty.LongStructTypeName{}, otherLongFieldName: (*pretty.LongStructTypeName)(nil), }`, }, { []LongStructTypeName{ {nil, nil}, {3, 3}, {long, nil}, }, `[]pretty.LongStructTypeName{ {}, { longFieldName: int(3), otherLongFieldName: int(3), }, { longFieldName: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", otherLongFieldName: nil, }, }`, }, { []interface{}{ LongStructTypeName{nil, nil}, []byte{1, 2, 3}, T{3, 4}, LongStructTypeName{long, nil}, }, `[]interface {}{ pretty.LongStructTypeName{}, []uint8{0x1, 0x2, 0x3}, pretty.T{x:3, y:4}, pretty.LongStructTypeName{ longFieldName: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", otherLongFieldName: nil, }, }`, }, } func TestGoSyntax(t *testing.T) { for _, tt := range gosyntax { s := fmt.Sprintf("%# v", Formatter(tt.v)) if tt.s != s { t.Errorf("expected %q", tt.s) t.Errorf("got %q", s) t.Errorf("expraw\n%s", tt.s) t.Errorf("gotraw\n%s", s) } } } type I struct { i int R interface{} } func (i *I) I() *I { return i.R.(*I) } func TestCycle(t *testing.T) { type A struct{ *A } v := &A{} v.A = v // panics from stack overflow without cycle detection t.Logf("Example cycle:\n%# v", Formatter(v)) p := &A{} s := fmt.Sprintf("%# v", Formatter([]*A{p, p})) if strings.Contains(s, "CYCLIC") { t.Errorf("Repeated address detected as cyclic reference:\n%s", s) } type R struct { i int *R } r := &R{ i: 1, R: &R{ i: 2, R: &R{ i: 3, }, }, } r.R.R.R = r t.Logf("Example longer cycle:\n%# v", Formatter(r)) r = &R{ i: 1, R: &R{ i: 2, R: &R{ i: 3, R: &R{ i: 4, R: &R{ i: 5, R: &R{ i: 6, R: &R{ i: 7, R: &R{ i: 8, R: &R{ i: 9, R: &R{ i: 10, R: &R{ i: 11, }, }, }, }, }, }, }, }, }, }, } // here be pirates r.R.R.R.R.R.R.R.R.R.R.R = r t.Logf("Example very long cycle:\n%# v", Formatter(r)) i := &I{ i: 1, R: &I{ i: 2, R: &I{ i: 3, R: &I{ i: 4, R: &I{ i: 5, R: &I{ i: 6, R: &I{ i: 7, R: &I{ i: 8, R: &I{ i: 9, R: &I{ i: 10, R: &I{ i: 11, }, }, }, }, }, }, }, }, }, }, } iv := i.I().I().I().I().I().I().I().I().I().I() *iv = *i t.Logf("Example long interface cycle:\n%# v", Formatter(i)) } pretty-0.3.0/go.mod000066400000000000000000000001651375730365600141700ustar00rootroot00000000000000module github.com/kr/pretty go 1.12 require ( github.com/kr/text v0.2.0 github.com/rogpeppe/go-internal v1.6.1 ) pretty-0.3.0/go.sum000066400000000000000000000016361375730365600142210ustar00rootroot00000000000000github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= pretty-0.3.0/pretty.go000066400000000000000000000061731375730365600147450ustar00rootroot00000000000000// Package pretty provides pretty-printing for Go values. This is // useful during debugging, to avoid wrapping long output lines in // the terminal. // // It provides a function, Formatter, that can be used with any // function that accepts a format string. It also provides // convenience wrappers for functions in packages fmt and log. package pretty import ( "fmt" "io" "log" "reflect" ) // Errorf is a convenience wrapper for fmt.Errorf. // // Calling Errorf(f, x, y) is equivalent to // fmt.Errorf(f, Formatter(x), Formatter(y)). func Errorf(format string, a ...interface{}) error { return fmt.Errorf(format, wrap(a, false)...) } // Fprintf is a convenience wrapper for fmt.Fprintf. // // Calling Fprintf(w, f, x, y) is equivalent to // fmt.Fprintf(w, f, Formatter(x), Formatter(y)). func Fprintf(w io.Writer, format string, a ...interface{}) (n int, error error) { return fmt.Fprintf(w, format, wrap(a, false)...) } // Log is a convenience wrapper for log.Printf. // // Calling Log(x, y) is equivalent to // log.Print(Formatter(x), Formatter(y)), but each operand is // formatted with "%# v". func Log(a ...interface{}) { log.Print(wrap(a, true)...) } // Logf is a convenience wrapper for log.Printf. // // Calling Logf(f, x, y) is equivalent to // log.Printf(f, Formatter(x), Formatter(y)). func Logf(format string, a ...interface{}) { log.Printf(format, wrap(a, false)...) } // Logln is a convenience wrapper for log.Printf. // // Calling Logln(x, y) is equivalent to // log.Println(Formatter(x), Formatter(y)), but each operand is // formatted with "%# v". func Logln(a ...interface{}) { log.Println(wrap(a, true)...) } // Print pretty-prints its operands and writes to standard output. // // Calling Print(x, y) is equivalent to // fmt.Print(Formatter(x), Formatter(y)), but each operand is // formatted with "%# v". func Print(a ...interface{}) (n int, errno error) { return fmt.Print(wrap(a, true)...) } // Printf is a convenience wrapper for fmt.Printf. // // Calling Printf(f, x, y) is equivalent to // fmt.Printf(f, Formatter(x), Formatter(y)). func Printf(format string, a ...interface{}) (n int, errno error) { return fmt.Printf(format, wrap(a, false)...) } // Println pretty-prints its operands and writes to standard output. // // Calling Println(x, y) is equivalent to // fmt.Println(Formatter(x), Formatter(y)), but each operand is // formatted with "%# v". func Println(a ...interface{}) (n int, errno error) { return fmt.Println(wrap(a, true)...) } // Sprint is a convenience wrapper for fmt.Sprintf. // // Calling Sprint(x, y) is equivalent to // fmt.Sprint(Formatter(x), Formatter(y)), but each operand is // formatted with "%# v". func Sprint(a ...interface{}) string { return fmt.Sprint(wrap(a, true)...) } // Sprintf is a convenience wrapper for fmt.Sprintf. // // Calling Sprintf(f, x, y) is equivalent to // fmt.Sprintf(f, Formatter(x), Formatter(y)). func Sprintf(format string, a ...interface{}) string { return fmt.Sprintf(format, wrap(a, false)...) } func wrap(a []interface{}, force bool) []interface{} { w := make([]interface{}, len(a)) for i, x := range a { w[i] = formatter{v: reflect.ValueOf(x), force: force} } return w } pretty-0.3.0/zero.go000066400000000000000000000017401375730365600143700ustar00rootroot00000000000000package pretty import ( "reflect" ) func nonzero(v reflect.Value) bool { switch v.Kind() { case reflect.Bool: return v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() != 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() != 0 case reflect.Float32, reflect.Float64: return v.Float() != 0 case reflect.Complex64, reflect.Complex128: return v.Complex() != complex(0, 0) case reflect.String: return v.String() != "" case reflect.Struct: for i := 0; i < v.NumField(); i++ { if nonzero(getField(v, i)) { return true } } return false case reflect.Array: for i := 0; i < v.Len(); i++ { if nonzero(v.Index(i)) { return true } } return false case reflect.Map, reflect.Interface, reflect.Slice, reflect.Ptr, reflect.Chan, reflect.Func: return !v.IsNil() case reflect.UnsafePointer: return v.Pointer() != 0 } return true }