Debian Codegraph @

dump.go

raw
1 package check
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "reflect"
8 "strconv"
9 "strings"
10 "unicode/utf8"
11
12 "github.com/powerman/check/internal/difflib"
13 "github.com/powerman/check/internal/spew"
14 )
15
16 //nolint:gochecknoglobals // Const.
17 var spewCfg = spew.ConfigState{
18 Indent: " ",
19 DisablePointerAddresses: true,
20 DisableCapacities: true,
21 SortKeys: true,
22 SpewKeys: true,
23 }
24
25 type dump struct {
26 dump string
27 indirectType reflect.Type
28 }
29
30 // String returns dump of value given to newDump.
31 func (v dump) String() string {
32 return v.dump
33 }
34
35 func (v dump) diff(expected dump) string {
36 if v.indirectType != expected.indirectType {
37 return ""
38 }
39 if !strings.ContainsRune(v.dump[:len(v.dump)-1], '\n') &&
40 !strings.ContainsRune(expected.dump[:len(expected.dump)-1], '\n') {
41 return ""
42 }
43
44 diff, err := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
45 A: difflib.SplitLines(expected.dump),
46 B: difflib.SplitLines(v.dump),
47 FromFile: "Expected",
48 FromDate: "",
49 ToFile: "Actual",
50 ToDate: "",
51 Context: 1,
52 })
53 if err != nil {
54 return ""
55 }
56 return "Diff:\n" + diff
57 }
58
59 // newDump prepare i dump using spew.Sdump in most cases and custom
60 // improved dump for these cases:
61 // - nil: remove "(interface{})" prefix
62 // - byte: use 0xFF instead of decimal
63 // - rune: use quoted char instead of number for valid runes
64 // - string: use this instead of quoted single-line:
65 // - valid utf8: don't quote ", show multiline strings on separate lines
66 // - invalid utf8: use hexdump like for []byte
67 //
68 // - []byte: same as string instead of hexdump for valid utf8
69 // - []rune: use quoted char instead of number for valid runes in list
70 // - [json.RawMessage]: indent, then same as string.
71 func newDump(i any) (d dump) { //nolint:gocyclo,gocognit,funlen,cyclop // By design.
72 d.dump = spewCfg.Sdump(i)
73
74 if i == nil {
75 d.dump = "<nil>\n"
76 return d
77 }
78
79 val := reflect.ValueOf(i)
80 typ := reflect.TypeOf(i)
81 kind := typ.Kind()
82 if kind == reflect.Pointer {
83 if val.IsNil() {
84 return d
85 }
86 val = val.Elem()
87 typ = typ.Elem()
88 kind = typ.Kind()
89 }
90 d.indirectType = typ
91
92 switch {
93 case typ == reflect.TypeFor[json.RawMessage]():
94 v := val.Bytes()
95 var buf bytes.Buffer
96 if json.Indent(&buf, v, "", " ") == nil {
97 // Go 1.27 made json.RawMessage an alias for jsontext.Value, so %T
98 // would print "jsontext.Value" there instead of "json.RawMessage".
99 // Use a hardcoded name to keep dump output identical across Go versions
100 // (this also covers a directly used jsontext.Value, which is the exact
101 // same type as json.RawMessage on Go 1.27).
102 //
103 // Once support for Go 1.26 is dropped, it would make more sense to
104 // rename this to "jsontext.Value"/"*jsontext.Value", since that's the
105 // name Go itself now treats as canonical (encoding/json/jsontext only
106 // exists once GOEXPERIMENT=jsonv2 is the default, i.e. Go 1.27+).
107 name := "json.RawMessage"
108 if reflect.TypeOf(i).Kind() == reflect.Pointer {
109 name = "*json.RawMessage"
110 }
111 d.dump = fmt.Sprintf("(%s) (len=%d) '\n%s\n'\n", name, len(v), buf.String())
112 }
113
114 case kind == reflect.Uint8:
115 v := byte(val.Uint()) //nolint:gosec // False positive.
116 d.dump = fmt.Sprintf("(%T) 0x%02X\n", i, v)
117
118 case kind == reflect.Int32:
119 v := rune(val.Int()) //nolint:gosec // False positive.
120 if utf8.ValidRune(v) {
121 d.dump = fmt.Sprintf("(%T) %q\n", i, v)
122 }
123
124 case kind == reflect.Slice && typ.Elem().Kind() == reflect.Int32:
125 valid := true
126 for k := 0; k < val.Len() && valid; k++ {
127 valid = valid && utf8.ValidRune(rune(val.Index(k).Int())) //nolint:gosec // False positive.
128 }
129 if valid {
130 d.dump = fmt.Sprintf("(%T) %q\n", i, i)
131 }
132
133 case kind == reflect.String:
134 v := val.String()
135 if utf8.ValidString(v) {
136 d.dump = fmt.Sprintf("(%T) (len=%d) %s\n", i, len(v), quote(v))
137 } else {
138 d.dump = strings.Replace(spewCfg.Sdump([]byte(v)), "([]uint8)", fmt.Sprintf("(%T)", i), 1)
139 }
140
141 case kind == reflect.Slice && typ.Elem().Kind() == reflect.Uint8:
142 v := val.Bytes()
143 if len(v) > 0 && utf8.Valid(v) || len(v) == 0 && !val.IsNil() {
144 d.dump = fmt.Sprintf("(%T) (len=%d) %s\n", i, len(v), quote(string(v)))
145 }
146 }
147 return d
148 }
149
150 // quote like %#v, except keep \n and " unquoted for readability.
151 func quote(s string) string {
152 r := []rune(strconv.Quote(s))
153 q := r[:0]
154 var multiline, esc bool
155 for _, c := range r[1 : len(r)-1] {
156 if esc {
157 esc = false
158 switch c {
159 case 'n':
160 c = '\n'
161 multiline = true
162 case '"':
163 default:
164 q = append(q, '\\')
165 }
166 } else if c == '\\' {
167 esc = true
168 continue
169 }
170 q = append(q, c)
171 }
172 if multiline {
173 return fmt.Sprintf("'\n%s\n'", string(q))
174 }
175 return fmt.Sprintf("'%s'", string(q))
176 }