Skip to content

Commit

Permalink
More PR Feedback
Browse files Browse the repository at this point in the history
1. Implement  support for enums pointers.
2. Add various enum test cases.
  • Loading branch information
scottwis committed Mar 19, 2022
1 parent 979cc69 commit 1a9585b
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
6 changes: 5 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -889,7 +889,11 @@ func checkEnum(value *Value, target reflect.Value) error {

case reflect.Map, reflect.Struct:
return errors.Errorf("enum can only be applied to a slice or value")

case reflect.Ptr:
if target.IsNil() {
return nil
}
return checkEnum(value, target.Elem())
default:
enumSlice := value.EnumSlice()
v := fmt.Sprintf("%v", target)
Expand Down
41 changes: 41 additions & 0 deletions kong_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1704,3 +1704,44 @@ func TestUnsupportedPtr(t *testing.T) {
require.Error(t, err)
require.Equal(t, "--f: cannot find mapper for kong_test.Foo", err.Error())
}

func TestEnumPtr(t *testing.T) {
var cli struct {
X *string `enum:"A,B,C" default:"C"`
}
k, err := kong.New(&cli)
require.NoError(t, err)
require.NotNil(t, k)
ctx, err := k.Parse([]string{"--x=A"})
require.NoError(t, err)
require.NotNil(t, ctx)
require.NotNil(t, cli.X)
require.Equal(t, "A", *cli.X)
}

func TestEnumPtrOmitted(t *testing.T) {
var cli struct {
X *string `enum:"A,B,C" default:"C"`
}
k, err := kong.New(&cli)
require.NoError(t, err)
require.NotNil(t, k)
ctx, err := k.Parse([]string{})
require.NoError(t, err)
require.NotNil(t, ctx)
require.NotNil(t, cli.X)
require.Equal(t, "C", *cli.X)
}

func TestEnumPtrOmittedNoDefault(t *testing.T) {
var cli struct {
X *string `enum:"A,B,C"`
}
k, err := kong.New(&cli)
require.NoError(t, err)
require.NotNil(t, k)
ctx, err := k.Parse([]string{})
require.NoError(t, err)
require.NotNil(t, ctx)
require.Nil(t, cli.X)
}
2 changes: 1 addition & 1 deletion tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ func hydrateTag(t *Tag, typ reflect.Type) error { // nolint: gocyclo
}
t.PlaceHolder = t.Get("placeholder")
t.Enum = t.Get("enum")
scalarType := (typ == nil || !(typ.Kind() == reflect.Slice || typ.Kind() == reflect.Map))
scalarType := (typ == nil || !(typ.Kind() == reflect.Slice || typ.Kind() == reflect.Map || typ.Kind() == reflect.Ptr))
if t.Enum != "" && !(t.Required || t.HasDefault) && scalarType {
return fmt.Errorf("enum value is only valid if it is either required or has a valid default value")
}
Expand Down

0 comments on commit 1a9585b

Please sign in to comment.