diff --git a/README.md b/README.md index 7597a7a6..63ae78c5 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ # getenv Package getenv provides a simple way to get environment variables. -It's type-safe and supports built-in types and slices of them. +It's generic and supports built-in types, custom types and slices of them. Empty environment variable values are treated as not set. Slices are split by "," and time.Time values are parsed with the time.RFC3339 layout, @@ -64,13 +64,176 @@ Types supported: - complex128 - []complex128 +Custom types are supported as well, and so are slices of the supported types, +named slice types such as type Tags []string included. +A value of a custom type T is parsed with the first one that fits: +- the ParseEnv method of T, see EnvParser; +- the UnmarshalText method of *T, or of T if it is a pointer type, see encoding.TextUnmarshaler; +- the underlying type of T, if it is a string, bool or numeric type, as for type Port uint16. +Note that type Timeout time.Duration is parsed as int64 nanoseconds, not as a duration: +its underlying type is int64, and it does not get the methods of time.Duration. +To parse it as a duration, implement EnvParser (see its example), +or declare an alias instead, type Timeout = time.Duration, if it needs no methods of its own. + +Env and EnvOrDefault panic for any other type, even when the variable is not set. + ## Examples +### CustomType + +This example shows how to read custom types from the environment with the same Env and EnvOrDefault: +types that implement getenv.EnvParser or encoding.TextUnmarshaler, types over basic types and slices of them. + +```golang +package main + +import ( + "errors" + "fmt" + "log/slog" + "os" + "strings" + + "github.com/obalunenko/getenv" + "github.com/obalunenko/getenv/option" +) + +// Level is a custom type: it implements getenv.EnvParser. +type Level int + +// Level values. The zero value is not a valid level. +const ( + LevelDebug Level = iota + 1 + LevelInfo + LevelWarn + LevelError +) + +// Check at compile time that Level implements getenv.EnvParser. +var _ getenv.EnvParser[Level] = Level(0) + +// String returns the name of the level. +func (l Level) String() string { + switch l { + case LevelDebug: + return "debug" + case LevelInfo: + return "info" + case LevelWarn: + return "warn" + case LevelError: + return "error" + default: + return fmt.Sprintf("Level(%d)", int(l)) + } +} + +// ParseEnv parses Level from the value of an environment variable. +// It has a value receiver: getenv calls it on the zero value. +func (Level) ParseEnv(raw string) (Level, error) { + switch strings.ToLower(raw) { + case "debug": + return LevelDebug, nil + case "info": + return LevelInfo, nil + case "warn": + return LevelWarn, nil + case "error": + return LevelError, nil + default: + return 0, fmt.Errorf("unknown level %q", raw) + } +} + +// Port is a custom type over a basic type: it is parsed as uint16. +type Port uint16 + +// This example shows how to read custom types from the environment with the same Env and EnvOrDefault: +// types that implement getenv.EnvParser or encoding.TextUnmarshaler, types over basic types and slices of them. +func main() { + const ( + key = "GH_GETENV_TEST" + ) + + var ( + lvl Level + lvls []Level + err error + ) + + defer func() { + if err = os.Unsetenv(key); err != nil { + panic(err) + } + }() + + // Level + if err = os.Setenv(key, "warn"); err != nil { + panic(err) + } + + lvl, err = getenv.Env[Level](key) + fmt.Printf("[%T]: %v; err: %v\n", lvl, lvl, err) + + // []Level + if err = os.Setenv(key, "debug|error"); err != nil { + panic(err) + } + + lvls, err = getenv.Env[[]Level](key, option.WithSeparator("|")) + fmt.Printf("[%T]: %v; err: %v\n", lvls, lvls, err) + + // Level parse error + if err = os.Setenv(key, "verbose"); err != nil { + panic(err) + } + + lvl, err = getenv.Env[Level](key) + fmt.Printf("[%T]: %v; err: %v\n", lvl, lvl, err) + fmt.Printf("is invalid value: %t\n", errors.Is(err, getenv.ErrInvalidValue)) + + // Level default + lvl = getenv.EnvOrDefault(key, LevelInfo) + fmt.Printf("[%T]: %v\n", lvl, lvl) + + // slog.Level implements encoding.TextUnmarshaler + if err = os.Setenv(key, "WARN,ERROR"); err != nil { + panic(err) + } + + slvls, err := getenv.Env[[]slog.Level](key) + fmt.Printf("[%T]: %v; err: %v\n", slvls, slvls, err) + + // Port + if err = os.Setenv(key, "8080"); err != nil { + panic(err) + } + + port := getenv.EnvOrDefault(key, Port(80)) + fmt.Printf("[%T]: %v\n", port, port) + +} + +``` + +Output: + +``` +[main.Level]: warn; err: +[[]main.Level]: [debug error]; err: +[main.Level]: Level(0); err: failed to parse environment variable[GH_GETENV_TEST]: unknown level "verbose": invalid value +is invalid value: true +[main.Level]: info +[[]slog.Level]: [WARN ERROR]; err: +[main.Port]: 8080 +``` + ### Env Env retrieves the value of the environment variable named by the key. If the variable is present in the environment the value will be parsed and returned. Otherwise, an error will be returned. +Env panics if T is not supported (see the package documentation), even when the variable is not set. ```golang package main @@ -216,6 +379,7 @@ EnvOrDefault retrieves the value of the environment variable named by the key. If the variable is set and its value can be parsed, the parsed value is returned. Otherwise, defaultVal is returned: both when the variable is not set (or empty) and when its value is invalid. Use Env to tell these cases apart. +EnvOrDefault panics if T is not supported, like Env. ```golang package main @@ -347,3 +511,77 @@ Output: [complex128]: (1+2i) [[]complex64]: [(1+2i) (3+4i)] ``` + +### EnvParser + +This example shows how to parse a type defined over time.Duration as a duration. + +```golang +package main + +import ( + "fmt" + "os" + "time" + + "github.com/obalunenko/getenv" +) + +// Timeout is defined over time.Duration: without ParseEnv it would be parsed as int64 nanoseconds. +type Timeout time.Duration + +// Check at compile time that Timeout implements getenv.EnvParser. +var _ getenv.EnvParser[Timeout] = Timeout(0) + +// ParseEnv parses Timeout as a duration. +func (Timeout) ParseEnv(raw string) (Timeout, error) { + d, err := time.ParseDuration(raw) + + return Timeout(d), err +} + +// String returns Timeout as a duration. +func (t Timeout) String() string { + return time.Duration(t).String() +} + +// This example shows how to parse a type defined over time.Duration as a duration. +func main() { + const ( + key = "GH_GETENV_TEST" + ) + + var err error + + defer func() { + if err = os.Unsetenv(key); err != nil { + panic(err) + } + }() + + // Timeout + if err = os.Setenv(key, "2m30s"); err != nil { + panic(err) + } + + timeout, err := getenv.Env[Timeout](key) + fmt.Printf("[%T]: %v; err: %v\n", timeout, timeout, err) + + // []Timeout + if err = os.Setenv(key, "1s,500ms"); err != nil { + panic(err) + } + + timeouts := getenv.EnvOrDefault(key, []Timeout{Timeout(time.Second)}) + fmt.Printf("[%T]: %v\n", timeouts, timeouts) + +} + +``` + +Output: + +``` +[main.Timeout]: 2m30s; err: +[[]main.Timeout]: [1s 500ms] +``` diff --git a/getenv.go b/getenv.go index c36fe750..4927b1df 100644 --- a/getenv.go +++ b/getenv.go @@ -1,5 +1,5 @@ // Package getenv provides a simple way to get environment variables. -// It's type-safe and supports built-in types and slices of them. +// It's generic and supports built-in types, custom types and slices of them. // Note: empty environment variable values are treated as "not set". // // Slices are split by "," and time.Time values are parsed with the time.RFC3339 layout, @@ -54,6 +54,19 @@ // - []complex64 // - complex128 // - []complex128 +// +// Custom types are supported as well, and so are slices of the supported types, +// named slice types such as type Tags []string included. +// A value of a custom type T is parsed with the first one that fits: +// - the ParseEnv method of T, see EnvParser; +// - the UnmarshalText method of *T, or of T if it is a pointer type, see encoding.TextUnmarshaler; +// - the underlying type of T, if it is a string, bool or numeric type, as for type Port uint16. +// Note that type Timeout time.Duration is parsed as int64 nanoseconds, not as a duration: +// its underlying type is int64, and it does not get the methods of time.Duration. +// To parse it as a duration, implement EnvParser (see its example), +// or declare an alias instead, type Timeout = time.Duration, if it needs no methods of its own. +// +// Env and EnvOrDefault panic for any other type, even when the variable is not set. package getenv import ( @@ -70,6 +83,8 @@ var ( ErrNotSet = internal.ErrNotSet // ErrInvalidValue is an error that is returned when the environment variable is not valid. ErrInvalidValue = internal.ErrInvalidValue + // ErrUnsupportedType is wrapped by the value that Env and EnvOrDefault panic with for a type they cannot parse. + ErrUnsupportedType = internal.ErrUnsupportedType ) // Defaults for the options that were not passed. @@ -78,18 +93,33 @@ const ( defaultTimeLayout = time.RFC3339 ) -// Parsable is a constraint for the types that Env and EnvOrDefault can parse. +// Parsable is a constraint for the built-in types that Env and EnvOrDefault can parse. // The list of supported types is in the package documentation. type Parsable = internal.EnvParsable +// EnvParser is implemented by custom types that parse themselves from an environment variable. +// ParseEnv is called on the zero value of T, so it needs a value receiver, unless T is a pointer type. +// +// Implementing EnvParser is checked at run time. +// To check it at compile time, assign a value of the type to an EnvParser variable: +// +// var _ getenv.EnvParser[Level] = Level(0) +type EnvParser[T EnvParser[T]] interface { + ParseEnv(raw string) (T, error) +} + // Env retrieves the value of the environment variable named by the key. // If the variable is present in the environment, the value will be parsed and returned. // Otherwise, an error will be returned. -func Env[T Parsable](key string, options ...option.Option) (T, error) { +// Env panics if T is not supported (see the package documentation), even when the variable is not set. +func Env[T any](key string, options ...option.Option) (T, error) { var zero T raw, ok := os.LookupEnv(key) if !ok || raw == "" { + // An unsupported T is reported even when there is nothing to parse. + internal.MustSupport[T]() + return zero, fmt.Errorf("failed to get environment variable[%s]: %w", key, ErrNotSet) } @@ -105,7 +135,8 @@ func Env[T Parsable](key string, options ...option.Option) (T, error) { // If the variable is set and its value can be parsed, the parsed value is returned. // Otherwise, defaultVal is returned: both when the variable is not set (or empty) // and when its value is invalid. Use Env to tell these cases apart. -func EnvOrDefault[T Parsable](key string, defaultVal T, options ...option.Option) T { +// EnvOrDefault panics if T is not supported, like Env. +func EnvOrDefault[T any](key string, defaultVal T, options ...option.Option) T { val, err := Env[T](key, options...) if err != nil { return defaultVal diff --git a/getenv_custom_example_test.go b/getenv_custom_example_test.go new file mode 100644 index 00000000..c22a3a48 --- /dev/null +++ b/getenv_custom_example_test.go @@ -0,0 +1,136 @@ +package getenv_test + +import ( + "errors" + "fmt" + "log/slog" + "os" + "strings" + + "github.com/obalunenko/getenv" + "github.com/obalunenko/getenv/option" +) + +// Level is a custom type: it implements getenv.EnvParser. +type Level int + +// Level values. The zero value is not a valid level. +const ( + LevelDebug Level = iota + 1 + LevelInfo + LevelWarn + LevelError +) + +// Check at compile time that Level implements getenv.EnvParser. +var _ getenv.EnvParser[Level] = Level(0) + +// String returns the name of the level. +func (l Level) String() string { + switch l { + case LevelDebug: + return "debug" + case LevelInfo: + return "info" + case LevelWarn: + return "warn" + case LevelError: + return "error" + default: + return fmt.Sprintf("Level(%d)", int(l)) + } +} + +// ParseEnv parses Level from the value of an environment variable. +// It has a value receiver: getenv calls it on the zero value. +func (Level) ParseEnv(raw string) (Level, error) { + switch strings.ToLower(raw) { + case "debug": + return LevelDebug, nil + case "info": + return LevelInfo, nil + case "warn": + return LevelWarn, nil + case "error": + return LevelError, nil + default: + return 0, fmt.Errorf("unknown level %q", raw) + } +} + +// Port is a custom type over a basic type: it is parsed as uint16. +type Port uint16 + +// This example shows how to read custom types from the environment with the same Env and EnvOrDefault: +// types that implement getenv.EnvParser or encoding.TextUnmarshaler, types over basic types and slices of them. +func Example_customType() { + const ( + key = "GH_GETENV_TEST" + ) + + var ( + lvl Level + lvls []Level + err error + ) + + defer func() { + if err = os.Unsetenv(key); err != nil { + panic(err) + } + }() + + // Level + if err = os.Setenv(key, "warn"); err != nil { + panic(err) + } + + lvl, err = getenv.Env[Level](key) + fmt.Printf("[%T]: %v; err: %v\n", lvl, lvl, err) + + // []Level + if err = os.Setenv(key, "debug|error"); err != nil { + panic(err) + } + + lvls, err = getenv.Env[[]Level](key, option.WithSeparator("|")) + fmt.Printf("[%T]: %v; err: %v\n", lvls, lvls, err) + + // Level parse error + if err = os.Setenv(key, "verbose"); err != nil { + panic(err) + } + + lvl, err = getenv.Env[Level](key) + fmt.Printf("[%T]: %v; err: %v\n", lvl, lvl, err) + fmt.Printf("is invalid value: %t\n", errors.Is(err, getenv.ErrInvalidValue)) + + // Level default + lvl = getenv.EnvOrDefault(key, LevelInfo) + fmt.Printf("[%T]: %v\n", lvl, lvl) + + // slog.Level implements encoding.TextUnmarshaler + if err = os.Setenv(key, "WARN,ERROR"); err != nil { + panic(err) + } + + slvls, err := getenv.Env[[]slog.Level](key) + fmt.Printf("[%T]: %v; err: %v\n", slvls, slvls, err) + + // Port + if err = os.Setenv(key, "8080"); err != nil { + panic(err) + } + + port := getenv.EnvOrDefault(key, Port(80)) + fmt.Printf("[%T]: %v\n", port, port) + + // Output: + // [getenv_test.Level]: warn; err: + // [[]getenv_test.Level]: [debug error]; err: + // [getenv_test.Level]: Level(0); err: failed to parse environment variable[GH_GETENV_TEST]: unknown level "verbose": invalid value + // is invalid value: true + // [getenv_test.Level]: info + // [[]slog.Level]: [WARN ERROR]; err: + // [getenv_test.Port]: 8080 +} diff --git a/getenv_parser_example_test.go b/getenv_parser_example_test.go new file mode 100644 index 00000000..279d653d --- /dev/null +++ b/getenv_parser_example_test.go @@ -0,0 +1,62 @@ +package getenv_test + +import ( + "fmt" + "os" + "time" + + "github.com/obalunenko/getenv" +) + +// Timeout is defined over time.Duration: without ParseEnv it would be parsed as int64 nanoseconds. +type Timeout time.Duration + +// Check at compile time that Timeout implements getenv.EnvParser. +var _ getenv.EnvParser[Timeout] = Timeout(0) + +// ParseEnv parses Timeout as a duration. +func (Timeout) ParseEnv(raw string) (Timeout, error) { + d, err := time.ParseDuration(raw) + + return Timeout(d), err +} + +// String returns Timeout as a duration. +func (t Timeout) String() string { + return time.Duration(t).String() +} + +// This example shows how to parse a type defined over time.Duration as a duration. +func ExampleEnvParser() { + const ( + key = "GH_GETENV_TEST" + ) + + var err error + + defer func() { + if err = os.Unsetenv(key); err != nil { + panic(err) + } + }() + + // Timeout + if err = os.Setenv(key, "2m30s"); err != nil { + panic(err) + } + + timeout, err := getenv.Env[Timeout](key) + fmt.Printf("[%T]: %v; err: %v\n", timeout, timeout, err) + + // []Timeout + if err = os.Setenv(key, "1s,500ms"); err != nil { + panic(err) + } + + timeouts := getenv.EnvOrDefault(key, []Timeout{Timeout(time.Second)}) + fmt.Printf("[%T]: %v\n", timeouts, timeouts) + + // Output: + // [getenv_test.Timeout]: 2m30s; err: + // [[]getenv_test.Timeout]: [1s 500ms] +} diff --git a/getenv_test.go b/getenv_test.go index aaf3091d..5dadfffc 100644 --- a/getenv_test.go +++ b/getenv_test.go @@ -1,6 +1,7 @@ package getenv_test import ( + "fmt" "strconv" "testing" "time" @@ -154,6 +155,89 @@ func TestEnvOrDefaultOptions(t *testing.T) { }) } +// color is a custom type: it implements getenv.EnvParser. +type color string + +var _ getenv.EnvParser[color] = color("") + +func (color) ParseEnv(raw string) (color, error) { + switch raw { + case "red", "green": + return color(raw), nil + default: + return "", fmt.Errorf("unknown color %q", raw) + } +} + +func TestEnvCustomType(t *testing.T) { + t.Run("value", func(t *testing.T) { + t.Setenv(testEnvKey, "red") + + got, err := getenv.Env[color](testEnvKey) + require.NoError(t, err) + assert.Equal(t, color("red"), got) + }) + + t.Run("slice", func(t *testing.T) { + t.Setenv(testEnvKey, "red|green") + + got, err := getenv.Env[[]color](testEnvKey, option.WithSeparator("|")) + require.NoError(t, err) + assert.Equal(t, []color{"red", "green"}, got) + }) + + t.Run("invalid", func(t *testing.T) { + t.Setenv(testEnvKey, "blue") + + got, err := getenv.Env[color](testEnvKey) + require.ErrorIs(t, err, getenv.ErrInvalidValue) + assert.ErrorContains(t, err, testEnvKey) + assert.Zero(t, got) + }) + + t.Run("not set", func(t *testing.T) { + _, err := getenv.Env[color](testEnvKey) + require.ErrorIs(t, err, getenv.ErrNotSet) + }) + + t.Run("default", func(t *testing.T) { + t.Setenv(testEnvKey, "blue") + + assert.Equal(t, color("green"), getenv.EnvOrDefault(testEnvKey, color("green"))) + }) +} + +func TestUnsupportedType(t *testing.T) { + const msg = "getenv: unsupported type: chan int" + + t.Run("set", func(t *testing.T) { + t.Setenv(testEnvKey, "1") + + assert.PanicsWithError(t, msg, func() { + _, err := getenv.Env[chan int](testEnvKey) + t.Errorf("returned %v instead of panicking", err) + }) + }) + + t.Run("not set", func(t *testing.T) { + assert.PanicsWithError(t, msg, func() { + _, err := getenv.Env[chan int](testEnvKey) + t.Errorf("returned %v instead of panicking", err) + }) + }) + + t.Run("default", func(t *testing.T) { + defer func() { + err, ok := recover().(error) + require.True(t, ok, "panic value is not an error") + require.ErrorIs(t, err, getenv.ErrUnsupportedType) + }() + + got := getenv.EnvOrDefault(testEnvKey, make(chan int)) + t.Errorf("returned %v instead of panicking", got) + }) +} + // mustEnv is a caller-side generic helper: it compiles only because Parsable is exported. func mustEnv[T getenv.Parsable](tb testing.TB, key string) T { tb.Helper() diff --git a/internal/custom.go b/internal/custom.go new file mode 100644 index 00000000..6f9ebe43 --- /dev/null +++ b/internal/custom.go @@ -0,0 +1,222 @@ +package internal + +import ( + "encoding" + "net" + "reflect" + "strconv" +) + +// valueParser converts the raw value to a single value of a type known at run time. +type valueParser func(raw string) (reflect.Value, error) + +var ( + stringType = reflect.TypeFor[string]() + errorType = reflect.TypeFor[error]() + textUnmarshalerType = reflect.TypeFor[encoding.TextUnmarshaler]() + ipType = reflect.TypeFor[net.IP]() + hardwareAddrType = reflect.TypeFor[net.HardwareAddr]() +) + +// kindParsers parse the types whose underlying type is a basic type, by its kind. +var kindParsers = map[reflect.Kind]valueParser{ + reflect.String: valueOf(parseString), + reflect.Bool: valueOf(strconv.ParseBool), + reflect.Int: valueOf(parseInt[int]), + reflect.Int8: valueOf(parseInt[int8]), + reflect.Int16: valueOf(parseInt[int16]), + reflect.Int32: valueOf(parseInt[int32]), + reflect.Int64: valueOf(parseInt[int64]), + reflect.Uint: valueOf(parseUint[uint]), + reflect.Uint8: valueOf(parseUint[uint8]), + reflect.Uint16: valueOf(parseUint[uint16]), + reflect.Uint32: valueOf(parseUint[uint32]), + reflect.Uint64: valueOf(parseUint[uint64]), + reflect.Uintptr: valueOf(parseUint[uintptr]), + reflect.Float32: valueOf(parseFloat[float32]), + reflect.Float64: valueOf(parseFloat[float64]), + reflect.Complex64: valueOf(parseComplex[complex64]), + reflect.Complex128: valueOf(parseComplex[complex128]), +} + +// customParserOf returns the function that parses raw into the value that dst points to, +// or nil if the type is not supported. +// The type is either a custom type (see valueParserOf), or a slice of custom or EnvParsable types. +func customParserOf(dst any, p Parameters) func(raw string) error { + rv := reflect.ValueOf(dst).Elem() + + if parse := valueParserOf(rv.Type(), p); parse != nil { + return func(raw string) error { + v, err := parse(raw) + if err != nil { + return err + } + + rv.Set(v) + + return nil + } + } + + if rv.Kind() != reflect.Slice { + return nil + } + + parse := valueParserOf(rv.Type().Elem(), p) + if parse == nil { + return nil + } + + return func(raw string) error { + elems, err := parseSlice(raw, p.Separator, parse) + if err != nil { + return err + } + + res := reflect.MakeSlice(rv.Type(), len(elems), len(elems)) + for i, e := range elems { + res.Index(i).Set(e) + } + + rv.Set(res) + + return nil + } +} + +// valueParserOf returns the parser of a single value of type t, or nil if t is not supported. +// The first one that fits is used: +// - the parser of a scalar EnvParsable type; +// - the ParseEnv method of t; +// - the UnmarshalText method of *t or of t, if it is a pointer type; +// - the parser of the underlying basic type of t. +func valueParserOf(t reflect.Type, p Parameters) valueParser { + if parse := builtinValueParserOf(t, p); parse != nil { + return parse + } + + if parse := envParserOf(t); parse != nil { + return parse + } + + if parse := textParserOf(t); parse != nil { + return parse + } + + return kindParserOf(t) +} + +// builtinValueParserOf returns the parser of t if t is a scalar EnvParsable type, or nil otherwise. +func builtinValueParserOf(t reflect.Type, p Parameters) valueParser { + // The slice EnvParsable types are split by the separator, so they cannot be slice elements. + // net.IP and net.HardwareAddr are the only scalar EnvParsable types of the slice kind. + if t.Kind() == reflect.Slice && t != ipType && t != hardwareAddrType { + return nil + } + + if !isBuiltin(reflect.New(t).Interface()) { + return nil + } + + return func(raw string) (reflect.Value, error) { + ptr := reflect.New(t) + + if err := parseBuiltin(ptr.Interface(), raw, p); err != nil { + return reflect.Value{}, err + } + + return ptr.Elem(), nil + } +} + +// envParserOf returns the ParseEnv method of the zero value of t, +// if t has the method ParseEnv(string) (t, error), or nil otherwise. +func envParserOf(t reflect.Type) valueParser { + m, ok := t.MethodByName("ParseEnv") + // The method type has the receiver as the first argument. + if !ok || m.Type != reflect.FuncOf([]reflect.Type{t, stringType}, []reflect.Type{t, errorType}, false) { + return nil + } + + parseEnv := reflect.Zero(t).Method(m.Index) + + return func(raw string) (reflect.Value, error) { + out := parseEnv.Call([]reflect.Value{reflect.ValueOf(raw)}) + + // A nil error is a nil interface, so the assertion fails for it. + if err, ok := out[1].Interface().(error); ok { + return reflect.Value{}, err + } + + return out[0], nil + } +} + +// textParserOf returns the parser of t if *t implements encoding.TextUnmarshaler, +// or t is a pointer type that implements it, or nil otherwise. +func textParserOf(t reflect.Type) valueParser { + switch { + case reflect.PointerTo(t).Implements(textUnmarshalerType): + return func(raw string) (reflect.Value, error) { + ptr := reflect.New(t) + + if err := unmarshalText(ptr, raw); err != nil { + return reflect.Value{}, err + } + + return ptr.Elem(), nil + } + case t.Kind() == reflect.Pointer && t.Implements(textUnmarshalerType): + return func(raw string) (reflect.Value, error) { + ptr := reflect.New(t.Elem()) + + if err := unmarshalText(ptr, raw); err != nil { + return reflect.Value{}, err + } + + return ptr, nil + } + default: + return nil + } +} + +// unmarshalText calls the UnmarshalText method of ptr, which implements encoding.TextUnmarshaler. +func unmarshalText(ptr reflect.Value, raw string) error { + u, ok := ptr.Interface().(encoding.TextUnmarshaler) + if !ok { + // Unreachable while textParserOf checks that ptr implements encoding.TextUnmarshaler. + panic("getenv: " + ptr.Type().String() + " does not implement encoding.TextUnmarshaler") + } + + return u.UnmarshalText([]byte(raw)) +} + +// kindParserOf returns the parser of t if the underlying type of t is a basic type, or nil otherwise. +func kindParserOf(t reflect.Type) valueParser { + parse, ok := kindParsers[t.Kind()] + if !ok { + return nil + } + + return func(raw string) (reflect.Value, error) { + v, err := parse(raw) + if err != nil { + return reflect.Value{}, err + } + + return v.Convert(t), nil + } +} + +// valueOf adapts parse to return a reflect.Value. +func valueOf[E any](parse func(string) (E, error)) valueParser { + return func(raw string) (reflect.Value, error) { + v, err := parse(raw) + if err != nil { + return reflect.Value{}, err + } + + return reflect.ValueOf(v), nil + } +} diff --git a/internal/custom_test.go b/internal/custom_test.go new file mode 100644 index 00000000..492ecd7c --- /dev/null +++ b/internal/custom_test.go @@ -0,0 +1,243 @@ +package internal + +import ( + "errors" + "fmt" + "log/slog" + "net" + "reflect" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var errUnknownLevel = errors.New("unknown level") + +// level has the ParseEnv method. +type level int + +func (level) ParseEnv(raw string) (level, error) { + switch raw { + case "debug": + return 1, nil + case "warn": + return 2, nil + default: + return 0, fmt.Errorf("%w %q", errUnknownLevel, raw) + } +} + +// point implements encoding.TextUnmarshaler with a pointer receiver. +type point struct { + x, y int +} + +func (p *point) UnmarshalText(text []byte) error { + _, err := fmt.Sscanf(string(text), "%d:%d", &p.x, &p.y) + + return err +} + +// both has the ParseEnv method and implements encoding.TextUnmarshaler. +type both string + +func (both) ParseEnv(raw string) (both, error) { + return both("env:" + raw), nil +} + +func (b *both) UnmarshalText(text []byte) error { + *b = both("text:" + string(text)) + + return nil +} + +// wrongParseEnv has the ParseEnv method with another signature. +type wrongParseEnv struct{} + +func (wrongParseEnv) ParseEnv(raw string) (string, error) { + return raw, nil +} + +// unsupported is a type that has no parser. +type unsupported struct{} + +// Types defined over time.Duration: their underlying type is int64. +type ( + nanos time.Duration + timeout time.Duration +) + +func (timeout) ParseEnv(raw string) (timeout, error) { + d, err := time.ParseDuration(raw) + + return timeout(d), err +} + +// Types whose underlying type is a basic type, and named slice types. +type ( + port uint16 + mode string + offset int8 + ratio float64 + enabled bool + wave complex64 + levels []level + ports []port + tags []string + timeouts []time.Duration + stamps []time.Time + ips []net.IP +) + +func TestParseEnvParser(t *testing.T) { + testParse(t, + parseCase[level]{name: "value", raw: "warn", want: 2}, + parseCase[level]{name: "invalid", raw: "loud", wantErr: true}, + ) + testParse(t, + parseCase[[]level]{name: "values", raw: "debug,warn", params: comma, want: []level{1, 2}}, + parseCase[[]level]{name: "invalid element", raw: "debug,loud", params: comma, wantErr: true}, + ) + testParse(t, parseCase[levels]{name: "named slice", raw: "debug,warn", params: comma, want: levels{1, 2}}) + + _, err := Parse[[]level]("debug,loud", comma) + require.ErrorIs(t, err, errUnknownLevel) + assert.ErrorContains(t, err, "element 1") +} + +func TestParseTextUnmarshaler(t *testing.T) { + testParse(t, + parseCase[point]{name: "value", raw: "1:2", want: point{x: 1, y: 2}}, + parseCase[point]{name: "invalid", raw: "1-2", wantErr: true}, + ) + testParse(t, + parseCase[*point]{name: "pointer type", raw: "1:2", want: &point{x: 1, y: 2}}, + parseCase[*point]{name: "pointer type invalid", raw: "1-2", wantErr: true}, + ) + testParse(t, parseCase[[]point]{name: "values", raw: "1:2,3:4", params: comma, want: []point{{1, 2}, {3, 4}}}) + testParse(t, parseCase[[]*point]{name: "pointers", raw: "1:2,3:4", params: comma, want: []*point{{1, 2}, {3, 4}}}) + testParse(t, + parseCase[slog.Level]{name: "standard library type", raw: "WARN", want: slog.LevelWarn}, + parseCase[slog.Level]{name: "standard library type invalid", raw: "LOUD", wantErr: true}, + ) +} + +func TestParseUnderlyingType(t *testing.T) { + testParse(t, + parseCase[port]{name: "value", raw: "8080", want: 8080}, + parseCase[port]{name: "overflow", raw: "65536", wantErr: true}, + ) + testParse(t, parseCase[mode]{name: "value", raw: "prod", want: "prod"}) + testParse(t, parseCase[offset]{name: "value", raw: "-128", want: -128}) + testParse(t, parseCase[ratio]{name: "value", raw: "0.5", want: 0.5}) + testParse(t, parseCase[enabled]{name: "value", raw: "true", want: true}) + testParse(t, parseCase[wave]{name: "value", raw: "1+2i", want: 1 + 2i}) + testParse(t, + parseCase[[]port]{name: "values", raw: "80,443", params: comma, want: []port{80, 443}}, + parseCase[[]port]{name: "invalid element", raw: "80,https", params: comma, wantErr: true}, + ) + testParse(t, parseCase[ports]{name: "named slice", raw: "80,443", params: comma, want: ports{80, 443}}) + testParse(t, parseCase[tags]{name: "named slice of a basic type", raw: "a,b", params: comma, want: tags{"a", "b"}}) +} + +// The elements of a named slice type are parsed as their EnvParsable type, with the parameters. +func TestParseNamedSliceOfEnvParsable(t *testing.T) { + testParse(t, + parseCase[timeouts]{name: "durations", raw: "1s,2m", params: comma, want: timeouts{time.Second, 2 * time.Minute}}, + parseCase[timeouts]{name: "not parsed as int64", raw: "1,2", params: comma, wantErr: true}, + ) + testParse(t, parseCase[stamps]{ + name: "time layout", + raw: "2022-01-20", + params: Parameters{Separator: ",", Layout: time.DateOnly}, + want: stamps{time.Date(2022, 1, 20, 0, 0, 0, 0, time.UTC)}, + }) + testParse(t, parseCase[ips]{ + name: "slice kind element", + raw: "192.168.8.1,::1", + params: comma, + want: ips{net.ParseIP("192.168.8.1"), net.ParseIP("::1")}, + }) +} + +// A type defined over time.Duration is parsed as int64, unless it has the ParseEnv method. +func TestParseDefinedDuration(t *testing.T) { + testParse(t, + parseCase[nanos]{name: "int64 nanoseconds", raw: "2000000000", want: nanos(2 * time.Second)}, + parseCase[nanos]{name: "not a duration", raw: "2s", wantErr: true}, + ) + testParse(t, + parseCase[timeout]{name: "ParseEnv", raw: "2s", want: timeout(2 * time.Second)}, + parseCase[timeout]{name: "ParseEnv invalid", raw: "2", wantErr: true}, + ) + testParse(t, parseCase[[]timeout]{name: "ParseEnv values", raw: "1s,500ms", params: comma, want: []timeout{ + timeout(time.Second), timeout(500 * time.Millisecond), + }}) +} + +func TestParsePrecedence(t *testing.T) { + testParse(t, parseCase[both]{name: "ParseEnv over UnmarshalText", raw: "x", want: "env:x"}) + testParse(t, parseCase[slog.Level]{name: "UnmarshalText over the underlying type", raw: "WARN", want: slog.LevelWarn}) +} + +func TestParseUnsupportedType(t *testing.T) { + testUnsupported[unsupported](t) + testUnsupported[chan int](t) + testUnsupported[*int](t) + testUnsupported[map[string]string](t) + testUnsupported[any](t) + testUnsupported[[][]string](t) + testUnsupported[[]unsupported](t) + testUnsupported[wrongParseEnv](t) +} + +// testUnsupported checks that MustSupport and Parse panic for T with an error that wraps ErrUnsupportedType. +func testUnsupported[T any](t *testing.T) { + t.Helper() + + typ := reflect.TypeFor[T]().String() + + t.Run(typ, func(t *testing.T) { + msg := "getenv: unsupported type: " + typ + + assert.PanicsWithError(t, msg, MustSupport[T]) + assert.PanicsWithError(t, msg, func() { + _, err := Parse[T]("1", comma) + t.Errorf("returned %v instead of panicking", err) + }) + + require.ErrorIs(t, recoverError(MustSupport[T]), ErrUnsupportedType) + }) +} + +// recoverError returns the error that f panics with. +func recoverError(f func()) (err error) { + defer func() { + if e, ok := recover().(error); ok { + err = e + } + }() + + f() + + return nil +} + +// This panic guards against programming errors in this package: textParserOf cannot reach it +// while it checks that the type implements encoding.TextUnmarshaler. +func TestUnmarshalTextPanics(t *testing.T) { + assert.PanicsWithValue(t, "getenv: *int does not implement encoding.TextUnmarshaler", func() { + err := unmarshalText(reflect.ValueOf(new(int)), "1") + t.Errorf("returned %v instead of panicking", err) + }) +} + +func TestMustSupport(t *testing.T) { + assert.NotPanics(t, MustSupport[int]) + assert.NotPanics(t, MustSupport[[]time.Time]) + assert.NotPanics(t, MustSupport[level]) + assert.NotPanics(t, MustSupport[[]*point]) + assert.NotPanics(t, MustSupport[ports]) +} diff --git a/internal/errors.go b/internal/errors.go index 3d1f5d97..bc169eeb 100644 --- a/internal/errors.go +++ b/internal/errors.go @@ -9,6 +9,9 @@ var ( ErrNotSet = errors.New("not set") // ErrInvalidValue is an error that is returned when the environment variable is not valid. ErrInvalidValue = errors.New("invalid value") + // ErrUnsupportedType is an error that is wrapped by the panic value for a type that cannot be parsed. + ErrUnsupportedType = errors.New("unsupported type") errEmptySeparator = errors.New("empty separator") + errNotBuiltin = errors.New("not an EnvParsable type") ) diff --git a/internal/parse.go b/internal/parse.go index eaf5ed0e..60facb33 100644 --- a/internal/parse.go +++ b/internal/parse.go @@ -2,6 +2,7 @@ package internal import ( + "errors" "fmt" "net" "net/netip" @@ -17,10 +18,25 @@ const decimalBase = 10 // Parse converts the raw value of an environment variable to T. // Slices are split by Parameters.Separator, time.Time is parsed with Parameters.Layout. // Every returned error wraps ErrInvalidValue. -func Parse[T EnvParsable](raw string, p Parameters) (T, error) { +// Parse panics if T is not supported, see MustSupport. +func Parse[T any](raw string, p Parameters) (T, error) { var res T - if err := parseValue(&res, raw, p); err != nil { + err := parseBuiltin(&res, raw, p) + if errors.Is(err, errNotBuiltin) { + // A separate variable keeps res on the stack for the EnvParsable types. + var custom T + + parse := customParserOf(&custom, p) + if parse == nil { + panic(unsupportedError[T]()) + } + + err = parse(raw) + res = custom + } + + if err != nil { var zero T return zero, fmt.Errorf("%w: %w", err, ErrInvalidValue) @@ -29,10 +45,32 @@ func Parse[T EnvParsable](raw string, p Parameters) (T, error) { return res, nil } -// parseValue parses raw into the value that dst points to. +// MustSupport panics if Parse cannot parse T: T is neither an EnvParsable type, +// nor a custom type (see valueParserOf), nor a slice of them. +func MustSupport[T any]() { + var probe T + + if !isBuiltin(&probe) && customParserOf(&probe, Parameters{}) == nil { + panic(unsupportedError[T]()) + } +} + +// unsupportedError returns the value that Parse and MustSupport panic with. +func unsupportedError[T any]() error { + return fmt.Errorf("getenv: %w: %s", ErrUnsupportedType, reflect.TypeFor[T]()) +} + +// isBuiltin reports whether dst points to a value of an EnvParsable type. +// It parses the empty string into dst: that has no side effects for the EnvParsable types. +func isBuiltin(dst any) bool { + return !errors.Is(parseBuiltin(dst, "", Parameters{}), errNotBuiltin) +} + +// parseBuiltin parses raw into the value that dst points to. +// It returns errNotBuiltin if the value is not of an EnvParsable type. // //nolint:gocyclo,funlen // Flat dispatch: one case per supported type and its slice. -func parseValue(dst any, raw string, p Parameters) error { +func parseBuiltin(dst any, raw string, p Parameters) error { var err error switch dst.(type) { @@ -85,8 +123,7 @@ func parseValue(dst any, raw string, p Parameters) error { case *net.HardwareAddr, *[]net.HardwareAddr: err = parseInto(dst, raw, p, net.ParseMAC) default: - // Unreachable from Parse while every EnvParsable type has a case above. - panic("getenv: no parser for " + reflect.TypeOf(dst).String()) + return errNotBuiltin } return err @@ -102,7 +139,7 @@ func parseInto[E any](dst any, raw string, p Parameters, parse func(string) (E, case *[]E: *v, err = parseSlice(raw, p.Separator, parse) default: - // Unreachable while every case of Parse passes the parser of its own type. + // Unreachable while every case of parseBuiltin passes the parser of its own type. panic("getenv: parser does not match the destination type") } diff --git a/internal/parse_test.go b/internal/parse_test.go index 06fa922d..030f49e5 100644 --- a/internal/parse_test.go +++ b/internal/parse_test.go @@ -17,7 +17,7 @@ import ( // comma holds the parameters for slice cases. var comma = Parameters{Separator: ","} -type parseCase[T EnvParsable] struct { +type parseCase[T any] struct { name string raw string params Parameters @@ -26,7 +26,7 @@ type parseCase[T EnvParsable] struct { } // testParse runs Parse[T] for every case: an error must wrap ErrInvalidValue and come with the zero value. -func testParse[T EnvParsable](t *testing.T, cases ...parseCase[T]) { +func testParse[T any](t *testing.T, cases ...parseCase[T]) { t.Helper() t.Run(fmt.Sprintf("%T", *new(T)), func(t *testing.T) { @@ -269,21 +269,9 @@ func TestParseSliceErrors(t *testing.T) { assert.ErrorContains(t, err, "element 2") } -// unsupported is a type that has no parser. -type unsupported struct{} - -// The panics guard against programming errors in this package: Parse cannot reach them -// while every EnvParsable type has a parser of its own type. func TestParsePanics(t *testing.T) { - t.Run("no parser for the type", func(t *testing.T) { - var dst unsupported - - assert.PanicsWithValue(t, "getenv: no parser for *internal.unsupported", func() { - err := parseValue(&dst, "1", comma) - t.Errorf("returned %v instead of panicking", err) - }) - }) - + // This panic guards against programming errors in this package: Parse cannot reach it + // while every case of parseBuiltin passes the parser of its own type. t.Run("parser does not match the destination", func(t *testing.T) { var dst int @@ -318,6 +306,10 @@ func FuzzParse(f *testing.F) { checkErrContract[net.IP](t, raw, p) checkErrContract[[]netip.Prefix](t, raw, p) checkErrContract[net.HardwareAddr](t, raw, p) + checkErrContract[level](t, raw, p) + checkErrContract[[]*point](t, raw, p) + checkErrContract[ports](t, raw, p) + checkErrContract[timeouts](t, raw, p) got, err := Parse[[]string](raw, p) require.NoError(t, err) @@ -326,7 +318,7 @@ func FuzzParse(f *testing.F) { } // checkErrContract asserts that a failed Parse returns the zero value and an error wrapping ErrInvalidValue. -func checkErrContract[T EnvParsable](t *testing.T, raw string, p Parameters) { +func checkErrContract[T any](t *testing.T, raw string, p Parameters) { t.Helper() got, err := Parse[T](raw, p)