diff --git a/config/config.go b/config/config.go index df998a82..bccf1fa6 100644 --- a/config/config.go +++ b/config/config.go @@ -8,7 +8,6 @@ import ( "github.com/jessevdk/go-flags" "github.com/pkg/errors" "os" - "reflect" ) // ErrInvalidArgument is the error returned by [ParseFlags] or [FromYAMLFile] if @@ -19,10 +18,9 @@ var ErrInvalidArgument = stderrors.New("invalid argument") // FromYAMLFile parses the given YAML file and stores the result // in the value pointed to by v. If v is nil or not a pointer, // FromYAMLFile returns an [ErrInvalidArgument] error. -func FromYAMLFile(name string, v Validator) error { - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Pointer || rv.IsNil() { - return errors.Wrapf(ErrInvalidArgument, "non-nil pointer expected, got %T", v) +func FromYAMLFile[T any, V validatorPtr[T]](name string, v V) error { + if v == nil { + return errors.Wrap(ErrInvalidArgument, "got nil pointer") } // #nosec G304 -- Potential file inclusion via variable - Its purpose is to load any file name that is passed to it, so doesn't need to validate anything. @@ -59,10 +57,9 @@ func FromYAMLFile(name string, v Validator) error { // ParseFlags prints the help message to [os.Stdout] and exits. // Note that errors are not printed automatically, // so error handling is the sole responsibility of the caller. -func ParseFlags(v any) error { - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Pointer || rv.IsNil() { - return errors.Wrapf(ErrInvalidArgument, "non-nil pointer expected, got %T", v) +func ParseFlags[T any](v *T) error { + if v == nil { + return errors.Wrap(ErrInvalidArgument, "got nil pointer") } parser := flags.NewParser(v, flags.Default^flags.PrintErrors) diff --git a/config/contracts.go b/config/contracts.go index 76022991..288a8f3a 100644 --- a/config/contracts.go +++ b/config/contracts.go @@ -3,3 +3,9 @@ package config type Validator interface { Validate() error } + +// validatorPtr combines the [Validator] interface with a pointer constraint. +type validatorPtr[T any] interface { + Validator + *T +}