Skip to content

Commit

Permalink
Add type safety check for validation
Browse files Browse the repository at this point in the history
  • Loading branch information
dearchap committed Jun 27, 2023
1 parent 6858650 commit 51cb2ef
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
9 changes: 9 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,12 @@ func handleMultiError(multiErr MultiError) int {
}
return code
}

type typeError[T any] struct {
other any
}

func (te *typeError[T]) Error() string {
var t T
return fmt.Sprintf("Expected type %T got instead %T", t, te.other)
}
12 changes: 10 additions & 2 deletions flag_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,11 @@ func (f *FlagBase[T, C, V]) Apply(set *flag.FlagSet) error {

// Validate the given default or values set from external sources as well
if f.Validator != nil {
if err := f.Validator(f.value.Get().(T)); err != nil {
if v, ok := f.value.Get().(T); !ok {
return &typeError[T]{
other: f.value.Get(),
}
} else if err := f.Validator(v); err != nil {
return err
}
}
Expand All @@ -176,7 +180,11 @@ func (f *FlagBase[T, C, V]) Apply(set *flag.FlagSet) error {
return err
}
if f.Validator != nil {
if err := f.Validator(f.value.Get().(T)); err != nil {
if v, ok := f.value.Get().(T); !ok {
return &typeError[T]{
other: f.value.Get(),
}
} else if err := f.Validator(v); err != nil {
return err
}
}
Expand Down

0 comments on commit 51cb2ef

Please sign in to comment.