-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathgodump.go
More file actions
1296 lines (1182 loc) · 31.6 KB
/
godump.go
File metadata and controls
1296 lines (1182 loc) · 31.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package godump
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"text/tabwriter"
"unicode/utf8"
"unsafe"
)
const (
colorReset = "\033[0m"
colorGray = "\033[90m"
colorYellow = "\033[33m"
colorRed = "\033[31m"
colorGreen = "\033[32m"
colorRedBg = "\033[48;2;34;16;16m"
colorGreenBg = "\033[48;2;16;34;22m"
colorLime = "\033[1;38;5;113m"
colorCyan = "\033[38;5;38m"
colorNote = "\033[38;5;38m"
colorRef = "\033[38;5;247m"
colorMeta = "\033[38;5;170m"
colorDefault = "\033[38;5;208m"
indentWidth = 2
)
// Default configuration values for the Dumper.
const (
defaultDisableStringer = false
defaultMaxDepth = 15
defaultMaxItems = 100
defaultMaxStringLen = 100000
defaultMaxStackDepth = 10
initialCallerSkip = 2
)
const (
// FieldMatchExact matches field names exactly (case-insensitive).
FieldMatchExact FieldMatchMode = iota
// FieldMatchContains matches if the field name contains a substring (case-insensitive).
FieldMatchContains
// FieldMatchPrefix matches if the field name starts with a substring (case-insensitive).
FieldMatchPrefix
// FieldMatchSuffix matches if the field name ends with a substring (case-insensitive).
FieldMatchSuffix
)
// FieldMatchMode controls how field names are matched.
type FieldMatchMode int
var defaultRedactedFields = []string{
"password",
"passwd",
"pwd",
"secret",
"token",
"api_key",
"apikey",
"access_key",
"accesskey",
"private_key",
"privatekey",
"client_secret",
"clientsecret",
"refresh_token",
"session",
"cookie",
"jwt",
"bearer",
"authorization",
"signature",
"signing_key",
}
// defaultDumper is the default Dumper instance used by Dump and DumpStr functions.
var defaultDumper = NewDumper()
// exitFunc is a function that can be overridden for testing purposes.
var exitFunc = os.Exit
// Colorizer is a function type that takes a color code and a string, returning the colorized string.
type Colorizer func(code, str string) string
// colorizeUnstyled returns the string without any colorization.
//
// It satisfies the [Colorizer] interface.
func colorizeUnstyled(code, str string) string {
return str // No colorization
}
// colorizeANSI colorizes the string using ANSI escape codes.
//
// It satisfies the [Colorizer] interface.
func colorizeANSI(code, str string) string {
return code + str + colorReset
}
// htmlColorMap maps color codes to HTML colors.
var htmlColorMap = map[string]string{
colorGray: "#999",
colorYellow: "#ffb400",
colorRed: "#ff5f5f",
colorGreen: "#55d655",
colorLime: "#80ff80",
colorNote: "#40c0ff",
colorRef: "#aaa",
colorMeta: "#d087d0",
colorDefault: "#ff7f00",
}
// colorizeHTML colorizes the string using HTML span tags.
//
// It satisfies the [Colorizer] interface.
func colorizeHTML(code, str string) string {
return fmt.Sprintf(`<span style="color:%s">%s</span>`, htmlColorMap[code], str)
}
// Dumper holds configuration for dumping structured data.
// It controls depth, item count, and string length limits.
type Dumper struct {
maxDepth int
maxItems int
maxStringLen int
writer io.Writer
skippedStackFrames int
disableStringer bool
disableColor bool
disableHeader bool
includeFields []string
excludeFields []string
redactFields []string
fieldMatchMode FieldMatchMode
redactMatchMode FieldMatchMode
// callerFn is used to get the caller information.
// It defaults to [runtime.Caller], it is here to be overridden for testing purposes.
callerFn func(skip int) (uintptr, string, int, bool)
// colorizer is used to apply color formatting to the output.
colorizer Colorizer
}
// Option defines a functional option for configuring a Dumper.
type Option func(*Dumper) *Dumper
// dumpState tracks reference ids for a single dump call.
type dumpState struct {
nextRefID int
refs map[uintptr]int
}
// newDumpState initializes per-dump reference tracking.
func newDumpState() *dumpState {
return &dumpState{
nextRefID: 1,
refs: map[uintptr]int{},
}
}
// WithMaxDepth limits how deep the structure will be dumped.
// Param n must be 0 or greater or this will be ignored, and default MaxDepth will be 15.
// @group Options
//
// Example: limit depth
//
// // Default: 15
// v := map[string]map[string]int{"a": {"b": 1}}
// d := godump.NewDumper(godump.WithMaxDepth(1))
// d.Dump(v)
// // #map[string]map[string]int {
// // a => #map[string]int {
// // b => 1 #int
// // }
// // }
func WithMaxDepth(n int) Option {
return func(d *Dumper) *Dumper {
if n >= 0 {
d.maxDepth = n
}
return d
}
}
// WithMaxItems limits how many items from an array, slice, or map can be printed.
// Param n must be 0 or greater or this will be ignored, and default MaxItems will be 100.
// @group Options
//
// Example: limit items
//
// // Default: 100
// v := []int{1, 2, 3}
// d := godump.NewDumper(godump.WithMaxItems(2))
// d.Dump(v)
// // #[]int [
// // 0 => 1 #int
// // 1 => 2 #int
// // ... (truncated)
// // ]
func WithMaxItems(n int) Option {
return func(d *Dumper) *Dumper {
if n >= 0 {
d.maxItems = n
}
return d
}
}
// WithMaxStringLen limits how long printed strings can be.
// Param n must be 0 or greater or this will be ignored, and default MaxStringLen will be 100000.
// @group Options
//
// Example: limit string length
//
// // Default: 100000
// v := "hello world"
// d := godump.NewDumper(godump.WithMaxStringLen(5))
// d.Dump(v)
// // "hello…" #string
func WithMaxStringLen(n int) Option {
return func(d *Dumper) *Dumper {
if n >= 0 {
d.maxStringLen = n
}
return d
}
}
// WithWriter routes output to the provided writer.
// @group Options
//
// Example: write to buffer
//
// // Default: stdout
// var b strings.Builder
// v := map[string]int{"a": 1}
// d := godump.NewDumper(godump.WithWriter(&b))
// d.Dump(v)
// // #map[string]int {
// // a => 1 #int
// // }
func WithWriter(w io.Writer) Option {
return func(d *Dumper) *Dumper {
d.writer = w
return d
}
}
// WithSkipStackFrames skips additional stack frames for header reporting.
// This is useful when godump is wrapped and the actual call site is deeper.
// @group Options
//
// Example: skip wrapper frames
//
// // Default: 0
// v := map[string]int{"a": 1}
// d := godump.NewDumper(godump.WithSkipStackFrames(2))
// d.Dump(v)
// // <#dump // ../../../../usr/local/go/src/runtime/asm_arm64.s:1223
// // #map[string]int {
// // a => 1 #int
// // }
func WithSkipStackFrames(n int) Option {
return func(d *Dumper) *Dumper {
if n >= 0 {
d.skippedStackFrames = n
}
return d
}
}
// WithDisableStringer disables using the fmt.Stringer output.
// When enabled, the underlying type is rendered instead of String().
// @group Options
//
// Example: show raw types
//
// // Default: false
// v := time.Duration(3)
// d := godump.NewDumper(godump.WithDisableStringer(true))
// d.Dump(v)
// // 3 #time.Duration
func WithDisableStringer(b bool) Option {
return func(d *Dumper) *Dumper {
d.disableStringer = b
return d
}
}
// WithoutColor disables colorized output for the dumper.
// @group Options
//
// Example: disable colors
//
// // Default: false
// v := map[string]int{"a": 1}
// d := godump.NewDumper(godump.WithoutColor())
// d.Dump(v)
// // (prints without color)
// // #map[string]int {
// // a => 1 #int
// // }
func WithoutColor() Option {
return func(d *Dumper) *Dumper {
d.disableColor = true
d.colorizer = colorizeUnstyled
return d
}
}
// WithoutHeader disables printing the source location header.
// @group Options
//
// Example: disable header
//
// // Default: false
// d := godump.NewDumper(godump.WithoutHeader())
// d.Dump("hello")
// // "hello" #string
func WithoutHeader() Option {
return func(d *Dumper) *Dumper {
d.disableHeader = true
return d
}
}
// WithOnlyFields limits struct output to fields that match the provided names.
// @group Options
//
// Example: include-only fields
//
// // Default: none
// type User struct {
// ID int
// Email string
// Password string
// }
// d := godump.NewDumper(
// godump.WithOnlyFields("ID", "Email"),
// )
// d.Dump(User{ID: 1, Email: "user@example.com", Password: "secret"})
// // #godump.User {
// // +ID => 1 #int
// // +Email => "user@example.com" #string
// // }
func WithOnlyFields(names ...string) Option {
return func(d *Dumper) *Dumper {
d.includeFields = append(d.includeFields, names...)
return d
}
}
// WithExcludeFields omits struct fields that match the provided names.
// @group Options
//
// Example: exclude fields
//
// // Default: none
// type User struct {
// ID int
// Email string
// Password string
// }
// d := godump.NewDumper(
// godump.WithExcludeFields("Password"),
// )
// d.Dump(User{ID: 1, Email: "user@example.com", Password: "secret"})
// // #godump.User {
// // +ID => 1 #int
// // +Email => "user@example.com" #string
// // }
func WithExcludeFields(names ...string) Option {
return func(d *Dumper) *Dumper {
d.excludeFields = append(d.excludeFields, names...)
return d
}
}
// WithFieldMatchMode sets how field names are matched for WithExcludeFields.
// @group Options
//
// Example: use substring matching
//
// // Default: FieldMatchExact
// type User struct {
// UserID int
// }
// d := godump.NewDumper(
// godump.WithExcludeFields("id"),
// godump.WithFieldMatchMode(godump.FieldMatchContains),
// )
// d.Dump(User{UserID: 10})
// // #godump.User {
// // }
func WithFieldMatchMode(mode FieldMatchMode) Option {
return func(d *Dumper) *Dumper {
d.fieldMatchMode = mode
return d
}
}
// WithRedactFields replaces matching struct fields with a redacted placeholder.
// @group Options
//
// Example: redact fields
//
// // Default: none
// type User struct {
// ID int
// Password string
// }
// d := godump.NewDumper(
// godump.WithRedactFields("Password"),
// )
// d.Dump(User{ID: 1, Password: "secret"})
// // #godump.User {
// // +ID => 1 #int
// // +Password => <redacted> #string
// // }
func WithRedactFields(names ...string) Option {
return func(d *Dumper) *Dumper {
d.redactFields = append(d.redactFields, names...)
return d
}
}
// WithRedactSensitive enables default redaction for common sensitive fields.
// @group Options
//
// Example: redact common sensitive fields
//
// // Default: disabled
// type User struct {
// Password string
// Token string
// }
// d := godump.NewDumper(
// godump.WithRedactSensitive(),
// )
// d.Dump(User{Password: "secret", Token: "abc"})
// // #godump.User {
// // +Password => <redacted> #string
// // +Token => <redacted> #string
// // }
func WithRedactSensitive() Option {
return func(d *Dumper) *Dumper {
d.redactFields = append(d.redactFields, defaultRedactedFields...)
d.redactMatchMode = FieldMatchContains
return d
}
}
// WithRedactMatchMode sets how field names are matched for WithRedactFields.
// @group Options
//
// Example: use substring matching
//
// // Default: FieldMatchExact
// type User struct {
// APIKey string
// }
// d := godump.NewDumper(
// godump.WithRedactFields("key"),
// godump.WithRedactMatchMode(godump.FieldMatchContains),
// )
// d.Dump(User{APIKey: "abc"})
// // #godump.User {
// // +APIKey => <redacted> #string
// // }
func WithRedactMatchMode(mode FieldMatchMode) Option {
return func(d *Dumper) *Dumper {
d.redactMatchMode = mode
return d
}
}
// NewDumper creates a new Dumper with the given options applied.
// Defaults are used for any setting not overridden.
// @group Builder
//
// Example: build a custom dumper
//
// v := map[string]int{"a": 1}
// d := godump.NewDumper(
// godump.WithMaxDepth(10),
// godump.WithWriter(os.Stdout),
// )
// d.Dump(v)
// // #map[string]int {
// // a => 1 #int
// // }
func NewDumper(opts ...Option) *Dumper {
d := &Dumper{
maxDepth: defaultMaxDepth,
maxItems: defaultMaxItems,
maxStringLen: defaultMaxStringLen,
disableStringer: defaultDisableStringer,
writer: os.Stdout,
colorizer: nil, // ensure no detection is made if we don't need it
callerFn: runtime.Caller,
fieldMatchMode: FieldMatchExact,
redactMatchMode: FieldMatchExact,
}
for _, opt := range opts {
d = opt(d)
}
return d
}
// Dump prints the values to stdout with colorized output.
// @group Dump
//
// Example: print to stdout
//
// v := map[string]int{"a": 1}
// godump.Dump(v)
// // #map[string]int {
// // a => 1 #int
// // }
func Dump(vs ...any) {
defaultDumper.Dump(vs...)
}
// Dump prints the values to stdout with colorized output.
// @group Dump
//
// Example: print with a custom dumper
//
// d := godump.NewDumper()
// v := map[string]int{"a": 1}
// d.Dump(v)
// // #map[string]int {
// // a => 1 #int
// // }
func (d *Dumper) Dump(vs ...any) {
fmt.Fprint(d.writer, d.DumpStr(vs...))
}
// Fdump writes the formatted dump of values to the given io.Writer.
// @group Dump
//
// Example: dump to writer
//
// var b strings.Builder
// v := map[string]int{"a": 1}
// godump.Fdump(&b, v)
// // outputs to strings builder
func Fdump(w io.Writer, vs ...any) {
NewDumper(WithWriter(w)).Dump(vs...)
}
// DumpStr returns a string representation of the values with colorized output.
// @group Dump
//
// Example: get a string dump
//
// v := map[string]int{"a": 1}
// out := godump.DumpStr(v)
// godump.Dump(out)
// // "#map[string]int {\n a => 1 #int\n}" #string
func DumpStr(vs ...any) string {
return defaultDumper.DumpStr(vs...)
}
// DumpStr returns a string representation of the values with colorized output.
// @group Dump
//
// Example: get a string dump with a custom dumper
//
// d := godump.NewDumper()
// v := map[string]int{"a": 1}
// out := d.DumpStr(v)
// _ = out
// // "#map[string]int {\n a => 1 #int\n}" #string
func (d *Dumper) DumpStr(vs ...any) string {
local := d.clone()
state := newDumpState()
var sb strings.Builder
local.printDumpHeader(&sb)
tw := tabwriter.NewWriter(&sb, 0, 0, 1, ' ', 0)
local.writeDump(tw, state, vs...)
tw.Flush()
return sb.String()
}
// DumpJSONStr pretty-prints values as JSON and returns it as a string.
// @group JSON
//
// Example: dump JSON string
//
// v := map[string]int{"a": 1}
// d := godump.NewDumper()
// out := d.DumpJSONStr(v)
// _ = out
// // {"a":1}
func (d *Dumper) DumpJSONStr(vs ...any) string {
if len(vs) == 0 {
return `{"error": "DumpJSON called with no arguments"}`
}
var data any = vs
if len(vs) == 1 {
data = vs[0]
}
b, err := json.MarshalIndent(data, "", strings.Repeat(" ", indentWidth))
if err != nil {
//nolint:errchkjson // fallback handles this manually below
errorJSON, _ := json.Marshal(map[string]string{"error": err.Error()})
return string(errorJSON)
}
return string(b)
}
// DumpJSON prints a pretty-printed JSON string to the configured writer.
// @group JSON
//
// Example: print JSON
//
// v := map[string]int{"a": 1}
// d := godump.NewDumper()
// d.DumpJSON(v)
// // {
// // "a": 1
// // }
func (d *Dumper) DumpJSON(vs ...any) {
output := d.DumpJSONStr(vs...)
fmt.Fprintln(d.writer, output)
}
// DumpHTML dumps the values as HTML with colorized output.
// @group HTML
//
// Example: dump HTML
//
// v := map[string]int{"a": 1}
// html := godump.DumpHTML(v)
// _ = html
// // (html output)
func DumpHTML(vs ...any) string {
return defaultDumper.DumpHTML(vs...)
}
// DumpHTML dumps the values as HTML with colorized output.
// @group HTML
//
// Example: dump HTML with a custom dumper
//
// d := godump.NewDumper()
// v := map[string]int{"a": 1}
// html := d.DumpHTML(v)
// _ = html
// fmt.Println(html)
// // (html output)
func (d *Dumper) DumpHTML(vs ...any) string {
var sb strings.Builder
sb.WriteString(`<div style='background-color:black;'><pre style="background-color:black; color:white; padding:5px; border-radius: 5px">` + "\n")
htmlDumper := d.clone()
if !htmlDumper.disableColor {
htmlDumper.colorizer = colorizeHTML // use HTML colorizer
}
sb.WriteString(htmlDumper.DumpStr(vs...))
sb.WriteString("</pre></div>")
return sb.String()
}
// DumpJSON dumps the values as a pretty-printed JSON string.
// If there is more than one value, they are dumped as a JSON array.
// It returns an error string if marshaling fails.
// @group JSON
//
// Example: print JSON
//
// v := map[string]int{"a": 1}
// godump.DumpJSON(v)
// // {
// // "a": 1
// // }
func DumpJSON(vs ...any) {
defaultDumper.DumpJSON(vs...)
}
// DumpJSONStr dumps the values as a JSON string.
// @group JSON
//
// Example: JSON string
//
// v := map[string]int{"a": 1}
// out := godump.DumpJSONStr(v)
// _ = out
// // {"a":1}
func DumpJSONStr(vs ...any) string {
return defaultDumper.DumpJSONStr(vs...)
}
// Dd is a debug function that prints the values and exits the program.
// @group Dump
//
// Example: dump and exit
//
// v := map[string]int{"a": 1}
// godump.Dd(v)
// // #map[string]int {
// // a => 1 #int
// // }
func Dd(vs ...any) {
defaultDumper.Dd(vs...)
}
// Dd is a debug function that prints the values and exits the program.
// @group Debug
//
// Example: dump and exit with a custom dumper
//
// d := godump.NewDumper()
// v := map[string]int{"a": 1}
// d.Dd(v)
// // #map[string]int {
// // a => 1 #int
// // }
func (d *Dumper) Dd(vs ...any) {
d.Dump(vs...)
exitFunc(1)
}
// clone creates a copy of the [Dumper] with the same configuration.
// This is useful for creating a new dumper with the same settings without modifying the original.
func (d *Dumper) clone() *Dumper {
newDumper := *d
return &newDumper
}
// colorize applies the configured [Colorizer] to the string with the given color code.
func (d *Dumper) colorize(code, str string) string {
if d.colorizer == nil {
// this avoids detecting color if not needed
if d.disableColor {
d.colorizer = colorizeUnstyled
return d.colorizer(code, str)
}
d.colorizer = newColorizer()
}
return d.colorizer(code, str)
}
// ensureColorizer initializes the colorizer when none is configured.
func (d *Dumper) ensureColorizer() {
if d.colorizer == nil {
if d.disableColor {
d.colorizer = colorizeUnstyled
return
}
d.colorizer = newColorizer()
}
}
// printDumpHeader prints the header for the dump output, including the file and line number.
func (d *Dumper) printDumpHeader(out io.Writer) {
if d.disableHeader {
return
}
file, line := d.findFirstNonInternalFrame(d.skippedStackFrames)
if file == "" {
return
}
relPath := file
if wd, err := os.Getwd(); err == nil {
if rel, err := filepath.Rel(wd, file); err == nil {
relPath = rel
}
}
header := fmt.Sprintf("<#dump // %s:%d", relPath, line)
fmt.Fprintln(out, d.colorize(colorGray, header))
}
// findFirstNonInternalFrame iterates through the call stack to find the first non-internal frame.
func (d *Dumper) findFirstNonInternalFrame(skip int) (string, int) {
for i := initialCallerSkip; i < defaultMaxStackDepth; i++ {
pc, file, line, ok := d.callerFn(i)
if !ok {
break
}
fn := runtime.FuncForPC(pc)
if fn == nil || !strings.Contains(fn.Name(), "godump") || strings.HasSuffix(file, "_test.go") {
if skip > 0 {
skip--
continue
}
return file, line
}
}
return "", 0
}
// formatByteSliceAsHexDump formats a byte slice as a hex dump with ASCII representation.
func (d *Dumper) formatByteSliceAsHexDump(b []byte, indent int) string {
var sb strings.Builder
const lineLen = 16
const asciiStartCol = 50
const asciiMaxLen = 16
fieldIndent := strings.Repeat(" ", indent*indentWidth)
bodyIndent := fieldIndent
// Header
sb.WriteString(fmt.Sprintf("([]uint8) (len=%d cap=%d) {\n", len(b), cap(b)))
for i := 0; i < len(b); i += lineLen {
end := i + lineLen
if end > len(b) {
end = len(b)
}
line := b[i:end]
visibleLen := 0
// Offset
offsetStr := fmt.Sprintf("%08x ", i)
sb.WriteString(bodyIndent)
sb.WriteString(d.colorize(colorMeta, offsetStr))
visibleLen += len(offsetStr)
// Hex bytes
for j := 0; j < lineLen; j++ {
var hexStr string
if j < len(line) {
hexStr = fmt.Sprintf("%02x ", line[j])
} else {
hexStr = " "
}
if j == 7 {
hexStr += " "
}
sb.WriteString(d.colorize(colorCyan, hexStr))
visibleLen += len(hexStr)
}
// Padding before ASCII
padding := asciiStartCol - visibleLen
if padding < 1 {
padding = 1
}
sb.WriteString(strings.Repeat(" ", padding))
// ASCII section
sb.WriteString(d.colorize(colorGray, "| "))
asciiCount := 0
for _, c := range line {
ch := "."
if c >= 32 && c <= 126 {
ch = string(c)
}
sb.WriteString(d.colorize(colorLime, ch))
asciiCount++
}
if asciiCount < asciiMaxLen {
sb.WriteString(strings.Repeat(" ", asciiMaxLen-asciiCount))
}
sb.WriteString(d.colorize(colorGray, " |") + "\n")
}
// Closing
fieldIndent = fieldIndent[:len(fieldIndent)-indentWidth]
sb.WriteString(fieldIndent + "}")
return sb.String()
}
func (d *Dumper) writeDump(w io.Writer, state *dumpState, vs ...any) {
for _, v := range vs {
rv := reflect.ValueOf(v)
rv = makeAddressable(rv)
d.printValue(w, rv, 0, state)
fmt.Fprintln(w)
}
}
func (d *Dumper) getTypeString(t reflect.Type) string {
switch t.Kind() {
case reflect.Map:
return fmt.Sprintf("map[%s]%s", d.getTypeString(t.Key()), d.getTypeString(t.Elem()))
case reflect.Slice:
return fmt.Sprintf("[]%s", d.getTypeString(t.Elem()))
case reflect.Array:
return fmt.Sprintf("[%d]%s", t.Len(), d.getTypeString(t.Elem()))
case reflect.Ptr:
return fmt.Sprintf("*%s", d.getTypeString(t.Elem()))
default:
return t.String()
}
}
func (d *Dumper) printValue(w io.Writer, v reflect.Value, indent int, state *dumpState) {
if !v.IsValid() {
fmt.Fprint(w, d.colorize(colorGray, "<invalid>"))
return
}
if isNil(v) {
typeStr := d.getTypeString(v.Type())
fmt.Fprintf(w, d.colorize(colorLime, typeStr)+d.colorize(colorGray, "(nil)"))
return
}
if shouldTruncateAtDepth(v, indent, d.maxDepth) {
fmt.Fprint(w, d.colorize(colorGray, "... (max depth)"))
return
}
if s := d.asStringer(v); s != "" {
fmt.Fprint(w, s)
return
}
switch v.Kind() {
case reflect.Chan:
typ := d.colorizer(colorGray, d.getTypeString(v.Type()))
fmt.Fprintf(w, "%s(%s)", d.colorize(colorGray, typ), d.colorize(colorCyan, fmt.Sprintf("%#x", v.Pointer())))
return
}
if v.Kind() == reflect.Ptr && v.CanAddr() {
ptr := v.Pointer()
if id, ok := state.refs[ptr]; ok {
fmt.Fprintf(w, d.colorize(colorRef, "↩︎ &%d"), id)
return
} else {
state.refs[ptr] = state.nextRefID
state.nextRefID++
}
}
// We don't need to check any previous checks (validity, channel, nil,
// addressable pointer) since they all work directly on the pointer type. We
// can simply continue with the reference value from here and add a pointer
// prefix to the output.
ptrPrefix := ""
for v.Kind() == reflect.Ptr {
ptrPrefix += "*"
v = v.Elem()
}
switch v.Kind() {
case reflect.Interface:
d.printValue(w, v.Elem(), indent, state)
case reflect.Struct:
t := v.Type()
fmt.Fprintf(w, "%s {", d.colorize(colorGray, fmt.Sprintf("#%s%s", ptrPrefix, d.getTypeString(v.Type()))))
fmt.Fprintln(w)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fieldVal := v.Field(i)
if !d.shouldIncludeField(field.Name) {
continue
}
symbol := "+"
if field.PkgPath != "" {
symbol = "-"
fieldVal = forceExported(fieldVal)
}
indentPrint(w, indent+1, d.colorize(colorYellow, symbol)+field.Name)
fmt.Fprint(w, " => ")
if d.shouldRedactField(field.Name) {
fmt.Fprint(w, d.redactedValue(fieldVal))
} else {
d.printValue(w, fieldVal, indent+1, state)
}
fmt.Fprintln(w)
}
indentPrint(w, indent, "")
fmt.Fprint(w, "}")
case reflect.Complex64, reflect.Complex128:
fmt.Fprint(w, d.colorize(colorCyan, fmt.Sprintf("%v", v.Complex())))
case reflect.UnsafePointer:
fmt.Fprint(w, d.colorize(colorGray, fmt.Sprintf("unsafe.Pointer(%#x)", v.Pointer())))
case reflect.Map:
fmt.Fprintf(w, "%s {", d.colorize(colorGray, fmt.Sprintf("#%s%s", ptrPrefix, d.getTypeString(v.Type()))))
fmt.Fprintln(w)
keys := v.MapKeys()
for i, key := range keys {
if i >= d.maxItems {
indentPrint(w, indent+1, d.colorize(colorGray, "... (truncated)"))
break
}