Skip to content

Commit

Permalink
Merge pull request #72 from Icinga/reflectPtr
Browse files Browse the repository at this point in the history
config/: enforce type constraints via generics, not reflection
  • Loading branch information
yhabteab authored Oct 18, 2024
2 parents a2fd4d4 + 437111f commit f25f8a0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
15 changes: 6 additions & 9 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions config/contracts.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit f25f8a0

Please sign in to comment.