From 3b49e512c4e40994a4e8fdc77cd005a71974696e Mon Sep 17 00:00:00 2001 From: Eric Lippmann Date: Mon, 21 Oct 2024 10:12:42 +0200 Subject: [PATCH] Revert "Merge pull request #72 from Icinga/reflectPtr" This reverts commit f25f8a03e301395f9bf3873783970f8e502479a7, reversing changes made to a2fd4d4fc03652d0871e4800eeb2f2b005d6f08b. While the changes relax the necessary checks for passing a valid pointer, they complicate the tests and still allow non-construct pointer types that implement the validator interface to pass. This negates the benefits, making it simpler to validate the pointer argument in a function as previously done. --- config/config.go | 15 +++++++++------ config/contracts.go | 6 ------ 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/config/config.go b/config/config.go index bccf1fa6..df998a82 100644 --- a/config/config.go +++ b/config/config.go @@ -8,6 +8,7 @@ import ( "github.com/jessevdk/go-flags" "github.com/pkg/errors" "os" + "reflect" ) // ErrInvalidArgument is the error returned by [ParseFlags] or [FromYAMLFile] if @@ -18,9 +19,10 @@ 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[T any, V validatorPtr[T]](name string, v V) error { - if v == nil { - return errors.Wrap(ErrInvalidArgument, "got nil pointer") +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) } // #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. @@ -57,9 +59,10 @@ func FromYAMLFile[T any, V validatorPtr[T]](name string, v V) 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[T any](v *T) error { - if v == nil { - return errors.Wrap(ErrInvalidArgument, "got nil pointer") +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) } parser := flags.NewParser(v, flags.Default^flags.PrintErrors) diff --git a/config/contracts.go b/config/contracts.go index 288a8f3a..76022991 100644 --- a/config/contracts.go +++ b/config/contracts.go @@ -3,9 +3,3 @@ package config type Validator interface { Validate() error } - -// validatorPtr combines the [Validator] interface with a pointer constraint. -type validatorPtr[T any] interface { - Validator - *T -}