Skip to content

Commit

Permalink
client: add a sentinel error for ParseFields
Browse files Browse the repository at this point in the history
This error allows the caller to check whether a candidate struct has any
setec-tagged fields to decide whether to include it in a store config.
  • Loading branch information
creachadair committed Nov 7, 2024
1 parent 3954dc4 commit d49b6e4
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
7 changes: 6 additions & 1 deletion client/setec/fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ import (
"golang.org/x/exp/slices"
)

// ErrNoFields is a sentinel error reported by ParseFields when its argument is
// a valid pointer to a struct, but does not contain any matching setec-tagged
// fields. The caller should use [errors.Is] to check for this error.
var ErrNoFields = errors.New("no setec-tagged fields")

// ParseFields parses information about setec-tagged fields from v. The
// concrete type of v must be a pointer to a struct value with at least one
// tagged field. The namePrefix, if non-empty, is joined to the front of each
Expand All @@ -28,7 +33,7 @@ func ParseFields(v any, namePrefix string) (*Fields, error) {
return nil, err
}
if len(fi) == 0 {
return nil, fmt.Errorf("type %v has no setec-tagged fields", reflect.TypeOf(v).Elem())
return nil, fmt.Errorf("type %v: %w", reflect.TypeOf(v).Elem(), ErrNoFields)
}
return &Fields{prefix: namePrefix, fields: fi}, nil
}
Expand Down
8 changes: 7 additions & 1 deletion client/setec/fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,14 @@ func TestParseErrors(t *testing.T) {
}
t.Run("NonPointer", checkFail(struct{ X string }{}, "not a pointer"))
t.Run("NonStruct", checkFail(new(string), "not a pointer to a struct"))
t.Run("NoTaggedFields", checkFail(&struct{ X string }{}, "no setec-tagged fields"))
t.Run("InvalidType", checkFail(&struct {
X float64 `setec:"x"` // N.B. not marked with JSON
}{}, "unsupported type"))

t.Run("NoTaggedFields", func(t *testing.T) {
_, err := setec.ParseFields(&struct{ X string }{}, "")
if !errors.Is(err, setec.ErrNoFields) {
t.Fatalf("ParseFields: got %v, want %v", err, setec.ErrNoFields)
}
})
}

0 comments on commit d49b6e4

Please sign in to comment.