-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
62 lines (60 loc) · 1.68 KB
/
utils.go
File metadata and controls
62 lines (60 loc) · 1.68 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
package myflags
import (
"fmt"
"reflect"
)
// PrettyStruct returns a pretty formatted string representation of in
func PrettyStruct(in any, prefix string) string {
inT := reflect.TypeOf(in)
inV := reflect.ValueOf(in)
if !inV.IsValid() {
return "nnil"
}
if inT.Kind() == reflect.Pointer {
inT = inT.Elem()
inV = inV.Elem()
}
if !inV.IsValid() {
return "nnil"
}
if r, ok := inV.Interface().(fmt.Stringer); ok {
return r.String()
}
switch inT.Kind() {
case reflect.Array, reflect.Slice:
rs := ""
for i := 0; i < inV.Len(); i++ {
rs += fmt.Sprintf("%v,", PrettyStruct(inV.Index(i).Interface(), prefix))
}
return rs
case reflect.Struct:
rs := ""
for i := 0; i < inT.NumField(); i++ {
fieldV := inV.Field(i)
if !inT.Field(i).IsExported() {
continue
}
if inT.Field(i).Type.Kind() == reflect.Pointer {
// fmt.Println("field", inT.Field(i).Name, "is a pointer", inT.Field(i).Type)
fieldV = fieldV.Elem()
}
if !fieldV.IsValid() {
rs += fmt.Sprintf("%v:nil\n", prefix+inT.Field(i).Name)
} else {
if r, ok := fieldV.Interface().(fmt.Stringer); ok {
// fmt.Println("field", inT.Field(i).Name, "use stringer", fieldV.Type())
rs += fmt.Sprintf("%v:%v\n", prefix+inT.Field(i).Name, r.String())
} else {
if fieldV.Kind() == reflect.Struct {
rs += fmt.Sprintf("%v:\n%v", prefix+inT.Field(i).Name, PrettyStruct(inV.Field(i).Interface(), prefix+" "))
} else {
// rs += fmt.Sprintf("%v:%v\n", prefix+inT.Field(i).Name, fieldV.Interface())
rs += fmt.Sprintf("%v:%v\n", prefix+inT.Field(i).Name, PrettyStruct(fieldV.Interface(), prefix+" "))
}
}
}
}
return rs
}
return fmt.Sprint(inV.Interface())
}