Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support to nested structs #1

Merged
merged 3 commits into from
Dec 2, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 27 additions & 5 deletions flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ func (f Flags) SetDefault(long string, val any) bool {
return false
}

// BuildFlags creates a slice of Flags from a struct.
// It supports nested structs and will only generate flags if it finds a 'short' and 'long' tag.
func BuildFlags(obj any) Flags {
v := reflect.ValueOf(obj)
if v.Kind() != reflect.Ptr {
Expand All @@ -74,19 +76,39 @@ func BuildFlags(obj any) Flags {
if v.Kind() != reflect.Struct {
panic(fmt.Errorf("expected a struct, got %s", v.Kind()))
}

return buildFlagsRecursive(v)
}

func buildFlagsRecursive(v reflect.Value) Flags {
t := v.Type()
var flags Flags

var err error
flags := make([]Flag, t.NumField())
for i := 0; i < t.NumField(); i++ {
flags[i], err = buildFlag(v.Field(i), t.Field(i))
if err != nil {
panic(err)
field := t.Field(i)
fieldValue := v.Field(i)

// Only process fields with a 'short' or 'long' tag
if hasTag(field.Tag, "short"); hasTag(field.Tag, "long") {
raulb marked this conversation as resolved.
Show resolved Hide resolved
flag, err := buildFlag(fieldValue, field)
if err != nil {
panic(err)
}
flags = append(flags, flag)
} else if fieldValue.Kind() == reflect.Struct {
hariso marked this conversation as resolved.
Show resolved Hide resolved
// If the field is a struct, recurse into it
embeddedFlags := buildFlagsRecursive(fieldValue)
flags = append(flags, embeddedFlags...)
}
}
return flags
}

func hasTag(tag reflect.StructTag, key string) bool {
_, ok := tag.Lookup(key)
return ok
}

func buildFlag(val reflect.Value, sf reflect.StructField) (Flag, error) {
const (
tagNameLong = "long"
Expand Down