Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Added debug.List that returns the fields and methods of a struct/poin…
…ter or keys of the map.
  • Loading branch information
mohsalsaleem committed Nov 12, 2021
commit 8df11bdea081a3ceb68adf51dbc740a6a73d7cc9
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
}