Skip to content

Commit

Permalink
Added debug.List that returns the fields and methods of a struct/poin…
Browse files Browse the repository at this point in the history
…ter or keys of the map.
  • Loading branch information
saleem-accuknox committed Nov 10, 2021
1 parent 9369d13 commit 2994a16
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions tpl/debug/debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
package debug

import (
"reflect"
"sort"

"github.com/sanity-io/litter"

"github.com/gohugoio/hugo/deps"
Expand All @@ -38,3 +41,43 @@ type Namespace struct {
func (ns *Namespace) Dump(val interface{}) string {
return litter.Sdump(val)
}

// List returns the fields and methods of the struct/pointer or keys of the map.
func (ns *Namespace) List(val interface{}) []string {
values := make([]string, 0)

v := reflect.ValueOf(val)

// If the type is struct
if v.Kind() == reflect.Struct {
for i := 0; i < v.NumField(); i++ {
values = append(values, v.Type().Field(i).Name)
}

for i := 0; i < v.NumMethod(); i++ {
values = append(values, v.Type().Method(i).Name)
}
}

// If the type is pointer
if v.Kind() == reflect.Ptr {
for i := 0; i < reflect.Indirect(v).NumField(); i++ {
values = append(values, v.Elem().Type().Field(i).Name)
}

for i := 0; i < v.NumMethod(); i++ {
values = append(values, v.Type().Method(i).Name)
}
}

// If the type is map
if v.Kind() == reflect.Map {
iter := v.MapRange()
for iter.Next() {
values = append(values, iter.Key().String())
}
}

sort.Strings(values)
return values
}

0 comments on commit 2994a16

Please sign in to comment.