Skip to content

Commit

Permalink
Merge pull request #158 from alexflint/unexported-embedded
Browse files Browse the repository at this point in the history
Recurse into unexported embedded structs
  • Loading branch information
alexflint authored May 25, 2021
2 parents 679be43 + fa12c02 commit eb0393e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
13 changes: 10 additions & 3 deletions parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,17 +257,24 @@ func cmdFromStruct(name string, dest path, t reflect.Type) (*command, error) {

var errs []string
walkFields(t, func(field reflect.StructField, t reflect.Type) bool {
// Check for the ignore switch in the tag
// check for the ignore switch in the tag
tag := field.Tag.Get("arg")
if tag == "-" || !isExported(field.Name) {
if tag == "-" {
return false
}

// If this is an embedded struct then recurse into its fields
// if this is an embedded struct then recurse into its fields, even if
// it is unexported, because exported fields on unexported embedded
// structs are still writable
if field.Anonymous && field.Type.Kind() == reflect.Struct {
return true
}

// ignore any other unexported field
if !isExported(field.Name) {
return false
}

// duplicate the entire path to avoid slice overwrites
subdest := dest.Child(field)
spec := spec{
Expand Down
23 changes: 23 additions & 0 deletions parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1095,6 +1095,29 @@ func TestEmbeddedWithDuplicateField2(t *testing.T) {
assert.Equal(t, "", args.U.A)
}

func TestUnexportedEmbedded(t *testing.T) {
type embeddedArgs struct {
Foo string
}
var args struct {
embeddedArgs
}
err := parse("--foo bar", &args)
require.NoError(t, err)
assert.Equal(t, "bar", args.Foo)
}

func TestIgnoredEmbedded(t *testing.T) {
type embeddedArgs struct {
Foo string
}
var args struct {
embeddedArgs `arg:"-"`
}
err := parse("--foo bar", &args)
require.Error(t, err)
}

func TestEmptyArgs(t *testing.T) {
origArgs := os.Args

Expand Down

0 comments on commit eb0393e

Please sign in to comment.