Skip to content

Commit 2994a16

Browse files
Added debug.List that returns the fields and methods of a struct/pointer or keys of the map.
1 parent 9369d13 commit 2994a16

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Diff for: tpl/debug/debug.go

+43
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515
package debug
1616

1717
import (
18+
"reflect"
19+
"sort"
20+
1821
"github.com/sanity-io/litter"
1922

2023
"github.com/gohugoio/hugo/deps"
@@ -38,3 +41,43 @@ type Namespace struct {
3841
func (ns *Namespace) Dump(val interface{}) string {
3942
return litter.Sdump(val)
4043
}
44+
45+
// List returns the fields and methods of the struct/pointer or keys of the map.
46+
func (ns *Namespace) List(val interface{}) []string {
47+
values := make([]string, 0)
48+
49+
v := reflect.ValueOf(val)
50+
51+
// If the type is struct
52+
if v.Kind() == reflect.Struct {
53+
for i := 0; i < v.NumField(); i++ {
54+
values = append(values, v.Type().Field(i).Name)
55+
}
56+
57+
for i := 0; i < v.NumMethod(); i++ {
58+
values = append(values, v.Type().Method(i).Name)
59+
}
60+
}
61+
62+
// If the type is pointer
63+
if v.Kind() == reflect.Ptr {
64+
for i := 0; i < reflect.Indirect(v).NumField(); i++ {
65+
values = append(values, v.Elem().Type().Field(i).Name)
66+
}
67+
68+
for i := 0; i < v.NumMethod(); i++ {
69+
values = append(values, v.Type().Method(i).Name)
70+
}
71+
}
72+
73+
// If the type is map
74+
if v.Kind() == reflect.Map {
75+
iter := v.MapRange()
76+
for iter.Next() {
77+
values = append(values, iter.Key().String())
78+
}
79+
}
80+
81+
sort.Strings(values)
82+
return values
83+
}

0 commit comments

Comments
 (0)