AlecAivazis / survey

A golang library for building interactive and accessible prompts with full support for windows and posix terminals.
MIT License
4.07k stars 351 forks source link

Promoted fields / composition doesn't work #365

Closed System-Glitch closed 2 years ago

System-Glitch commented 2 years ago

What operating system and terminal are you using?
go version go1.16 linux/amd64

An example that showcases the bug.

type Common struct{
    Name string
}

type Register struct{
    Common // Name field added by composition
    Password string
}
[]*survey.Question{
    {
        Name: "Name",
        Prompt: &survey.Input{Message: "Your name"},
        Validate: survey.Required,
    },
    {
        Name:   "Password",
        Prompt: &survey.Password{Message: "Password"},
        Validate: survey.Required,
    },
}

What did you expect to see? I would expect promoted fields to be recognized by the library so redundancy can be avoided for common fields and behavior.

What did you see instead? Will always result in could not find field matching Name because core/write.go.findFieldIndex() doesn't check promoted fields.


Promoted fields can be checked using the following condition:

field := s.Field(i)
fieldType := sType.Field(i)
if field.Kind() == reflect.Struct && fieldType.Anonymous {
    // This field is a promoted struct
}

(Variable names are based on what's used in core/write.go.findFieldIndex().)

System-Glitch commented 2 years ago

Pull request coming shortly.