Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MustProcess: panic if processing fails, return the value #114

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions envconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,15 @@ func Process(ctx context.Context, i any, mus ...Mutator) error {
})
}

// MustProcess is a helper that calls [Process] and panics if an error is
// encountered. The input value is returned after processing.
func MustProcess[T any](ctx context.Context, i T, mus ...Mutator) T {
if err := Process(ctx, i, mus...); err != nil {
panic(err)
}
return i
}

// ProcessWith executes the decoding process using the provided [Config].
func ProcessWith(ctx context.Context, c *Config) error {
if c == nil {
Expand Down
22 changes: 22 additions & 0 deletions envconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3034,3 +3034,25 @@ func TestValidateEnvName(t *testing.T) {
func ptrTo[T any](i T) *T {
return &i
}

func TestMustProcess_Panic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected a panic")
}
}()
MustProcess(context.Background(), struct {
Unset string `env:"UNSET" required:"true"`
}{})
}

func TestMustProcess_Value(t *testing.T) {
t.Setenv("SET", "value")
s := MustProcess(context.Background(), &struct {
Set string `env:"SET"`
}{})

if s.Set != "value" {
t.Fatalf("expected %q to be %q", s.Set, "value")
}
}