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

Add to error all missed fields with required tag #143

Merged
merged 1 commit into from
Sep 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions aconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,15 +261,22 @@ func (l *Loader) loadSources() error {
}

func (l *Loader) checkRequired() error {
missedFields := []string{}
for _, field := range l.fields {
if field.isSet {
continue
}
if field.isRequired || l.config.AllFieldRequired {
return fmt.Errorf("field %s is required but not set", field.name)
missedFields = append(missedFields, field.name)
}
}
return nil
if len(missedFields) == 0 {
return nil
}
if len(missedFields) == 1 {
return fmt.Errorf("field %s is required but not set", missedFields[0])
}
return fmt.Errorf("fields %s are required but not set", strings.Join(missedFields, ","))
}

func (l *Loader) loadDefaults() error {
Expand Down
32 changes: 32 additions & 0 deletions aconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1087,6 +1087,38 @@ func TestBadRequiredTag(t *testing.T) {
f(&TestConfig{})
}

func TestMissingFieldWithRequiredTag(t *testing.T) {
cfg := struct {
Field1 string `required:"true"`
}{}
loader := LoaderFor(&cfg, Config{
SkipFlags: true,
})

err := loader.Load()

want := "load config: field Field1 is required but not set"
if err.Error() != want {
t.Fatalf("got %v, want %v", err, want)
}
}
func TestMissingFieldsWithRequiredTag(t *testing.T) {
cfg := struct {
Field1 string `required:"true"`
Field2 string `required:"true"`
}{}
loader := LoaderFor(&cfg, Config{
SkipFlags: true,
})

err := loader.Load()

want := "load config: fields Field1,Field2 are required but not set"
if err.Error() != want {
t.Fatalf("got %v, want %v", err, want)
}
}

func int32Ptr(a int32) *int32 {
return &a
}
Expand Down