From 09e3cfe0bf7094602577f254a4ea376ee55e37d3 Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 11:56:31 +0300 Subject: [PATCH] refactor: move the internals of the root package to internal zero allocates the models of Configure, helper builds the errors with the translator and the locations, tags configures the rules of the tags; the root has the API: Validator, Configure, Configurator and options. --- builder.go | 13 +++++ builder_test.go | 12 +++++ docs/architecture/index.md | 3 +- helper.go | 44 ----------------- internal/helper/helper.go | 47 +++++++++++++++++++ .../helper/helper_test.go | 6 +-- tags.go => internal/tags/tags.go | 34 +++++++++----- tags_test.go => internal/tags/tags_test.go | 13 ++--- zero.go => internal/zero/zero.go | 16 ++++--- zero_test.go => internal/zero/zero_test.go | 26 +++++----- options.go | 4 +- options_test.go | 14 +++--- validator.go | 8 ++-- 13 files changed, 141 insertions(+), 99 deletions(-) delete mode 100644 helper.go create mode 100644 internal/helper/helper.go rename helper_test.go => internal/helper/helper_test.go (85%) rename tags.go => internal/tags/tags.go (93%) rename tags_test.go => internal/tags/tags_test.go (96%) rename zero.go => internal/zero/zero.go (79%) rename zero_test.go => internal/zero/zero_test.go (87%) diff --git a/builder.go b/builder.go index 601f622..66b21b3 100644 --- a/builder.go +++ b/builder.go @@ -8,6 +8,7 @@ import ( "github.com/insei/fmap/v3" + "github.com/insei/valigo/internal/tags" "github.com/insei/valigo/shared" ) @@ -133,3 +134,15 @@ func (c Configurator[T]) Map[K comparable, V any](mapFieldPtr *map[K]V) *shared. field := c.field(mapFieldPtr) return shared.NewMapFieldConfigurator[K, V](field, c.b.v.helper, c.field, c.add, c.describe()) } + +// Tags configures the rules of the tag name of the fields of T and of its nested structs in the syntax of +// go-playground/validator, validate:"required,max=64", for a migration from it: the tags and the rules in code +// can be mixed in one Configure. The rules are the rules of valigo with their messages, codes and constraints: +// required is Required, min and max are the lengths in characters of strings, the values of numbers and the lengths +// of slices and maps, dive applies the next rules to the elements of a slice or the values of a map[string]V. +// The rules of the fields of a nil nested struct are skipped, like by go-playground/validator, unlike the rules in code. +// See the documentation for the list of the rules. Tags panics on an unknown rule, like Configure on invalid rules. +func (c Configurator[T]) Tags(name string) { + tags.Apply(tags.Struct{Storage: c.b.fields, Model: c.b.obj, Helper: c.b.v.helper, Fields: c.field, + Add: c.add, Describe: c.describe()}, name) +} diff --git a/builder_test.go b/builder_test.go index 1edf087..8003403 100644 --- a/builder_test.go +++ b/builder_test.go @@ -381,3 +381,15 @@ func TestZeroAllocationsOnValid(t *testing.T) { require.Nil(t, v.Validate(ctx, obj)) assert.Zero(t, testing.AllocsPerRun(100, func() { v.Validate(ctx, obj) })) } + +func TestConfiguratorTags(t *testing.T) { + type tagged struct { + Name string `validate:"required"` + } + v := New() + Configure[tagged](v, func(b Configurator[tagged], _ *tagged) { b.Tags("validate") }) + errs := v.ValidateTyped(context.Background(), &tagged{}) + if len(errs) != 1 || errs[0].Code != "string.required" { + t.Errorf("errors of the tags: %v", errs) + } +} diff --git a/docs/architecture/index.md b/docs/architecture/index.md index dab54c8..9382df2 100644 --- a/docs/architecture/index.md +++ b/docs/architecture/index.md @@ -41,7 +41,8 @@ The rules append their errors to one pooled buffer of the validation, and `Valid | Package | Contents | |---|---| -| `valigo` | `Validator`, `Configure`, `Configurator` with `Field`, `Slice`, `When` and `Custom`, options | +| `valigo` | `Validator`, `Configure`, `Configurator` with `Field`, `Slice`, `Map`, `When`, `Custom` and `Tags`, options | +| `internal/zero`, `internal/helper`, `internal/tags` | the allocation of the models of `Configure`, the helper of the errors with the translator and the locations, the rules of the tags | | `shared` | the rules core `Field[T]`, slice configurator and `Elems[E]`, `As` and the conversions `Deref`, `Retype`, `RetypeSlice`, `SlicePtr`, `SliceRules`, `Error`, helpers | | `str`, `num`, `timex`, `eq` | configurators of strings, numbers, times and comparable values built on `shared.Field[T]`, their conversions `str.Of`, `num.Of`, `num.Ptr`, `timex.Of`, `eq.Of`... and slice conversions | | `problem` | the problem details of RFC 9457 | diff --git a/helper.go b/helper.go deleted file mode 100644 index e614074..0000000 --- a/helper.go +++ /dev/null @@ -1,44 +0,0 @@ -package valigo - -import ( - "context" - - "github.com/insei/fmap/v3" - - "github.com/insei/valigo/shared" - "github.com/insei/valigo/translator" -) - -// helper is a struct that provides functionality for handling errors and translations. -type helper struct { - t translator.Translator - getFieldLocation func(field fmap.Field) string -} - -// ErrorT returns a shared.Error with the given location, message, and value. -// The message is translated using the translator, the code of the error is the locale key. -func (h *helper) ErrorT(ctx context.Context, field fmap.Field, value any, localeKey string, args ...any) shared.Error { - location := h.getFieldLocation(field) - msg := h.t.T(ctx, localeKey, args...) - return shared.Error{ - Location: location, - Message: msg, - Value: value, - Code: localeKey, - } -} - -// FieldLocation returns the location of the field in errors. -func (h *helper) FieldLocation(field fmap.Field) string { - return h.getFieldLocation(field) -} - -// newHelper returns a new helper with a default translator and getFieldLocation function. -func newHelper() *helper { - return &helper{ - t: translator.New(), - getFieldLocation: func(field fmap.Field) string { - return field.GetStructPath() - }, - } -} diff --git a/internal/helper/helper.go b/internal/helper/helper.go new file mode 100644 index 0000000..05dbd2a --- /dev/null +++ b/internal/helper/helper.go @@ -0,0 +1,47 @@ +// Package helper builds the errors of the rules with the translated messages and the locations of the fields. +package helper + +import ( + "context" + + "github.com/insei/fmap/v3" + + "github.com/insei/valigo/shared" + "github.com/insei/valigo/translator" +) + +// Helper is the shared.Helper of a validator. +type Helper struct { + // Translator translates the messages. + Translator translator.Translator + // Location returns the location of a field in the errors. + Location func(field fmap.Field) string +} + +// ErrorT returns a shared.Error with the given location, message, and value. +// The message is translated using the translator, the code of the error is the locale key. +func (h *Helper) ErrorT(ctx context.Context, field fmap.Field, value any, localeKey string, args ...any) shared.Error { + location := h.Location(field) + msg := h.Translator.T(ctx, localeKey, args...) + return shared.Error{ + Location: location, + Message: msg, + Value: value, + Code: localeKey, + } +} + +// FieldLocation returns the location of the field in errors. +func (h *Helper) FieldLocation(field fmap.Field) string { + return h.Location(field) +} + +// New returns a helper with the default translator and the struct paths of the fields as their locations. +func New() *Helper { + return &Helper{ + Translator: translator.New(), + Location: func(field fmap.Field) string { + return field.GetStructPath() + }, + } +} diff --git a/helper_test.go b/internal/helper/helper_test.go similarity index 85% rename from helper_test.go rename to internal/helper/helper_test.go index 0556a66..9d72378 100644 --- a/helper_test.go +++ b/internal/helper/helper_test.go @@ -1,4 +1,4 @@ -package valigo +package helper import ( "context" @@ -13,7 +13,7 @@ type admin struct { } func TestHelperErrorT(t *testing.T) { - h := newHelper() + h := New() testAdmin := admin{ Name: "John", Age: 33, @@ -32,7 +32,7 @@ func TestHelperErrorT(t *testing.T) { func TestHelperFieldLocation(t *testing.T) { strg, _ := fmap.GetFrom(admin{}) - if got := newHelper().FieldLocation(strg.MustFind("Name")); got != "Name" { + if got := New().FieldLocation(strg.MustFind("Name")); got != "Name" { t.Errorf("FieldLocation() = %q, want Name", got) } } diff --git a/tags.go b/internal/tags/tags.go similarity index 93% rename from tags.go rename to internal/tags/tags.go index 37e605b..81e5f3c 100644 --- a/tags.go +++ b/internal/tags/tags.go @@ -1,4 +1,5 @@ -package valigo +// Package tags configures the rules of the tags of go-playground/validator by the rules of valigo. +package tags import ( "context" @@ -18,22 +19,29 @@ import ( "github.com/insei/valigo/timex" ) -// Tags configures the rules of the tag name of the fields of T and of its nested structs in the syntax of -// go-playground/validator, validate:"required,max=64", for a migration from it: the tags and the rules in code -// can be mixed in one Configure. The rules are the rules of valigo with their messages, codes and constraints: -// required is Required, min and max are the lengths in characters of strings, the values of numbers and the lengths -// of slices and maps, dive applies the next rules to the elements of a slice or the values of a map[string]V. -// The rules of the fields of a nil nested struct are skipped, like by go-playground/validator, unlike the rules in code. -// See the documentation for the list of the rules. Tags panics on an unknown rule, like Configure on invalid rules. -func (c Configurator[T]) Tags(name string) { - for _, path := range c.b.fields.GetAllPaths() { - field := c.b.fields.MustFind(path) +// Struct is the configuration of the rules of a struct by its model, see valigo.Configure. +type Struct struct { + // Storage is the fields of the model, Model is the pointer to the model. + Storage fmap.Storage + Model any + Helper shared.Helper + Fields shared.Fields + // Add registers the rules, Describe their constraints, it can be nil. + Add func(fn shared.ValidationFn) + Describe shared.Describe +} + +// Apply configures the rules of the tag name of the fields of the struct and of its nested structs, +// see valigo.Configurator.Tags. It panics on an unknown rule. +func Apply(s Struct, name string) { + for _, path := range s.Storage.GetAllPaths() { + field := s.Storage.MustFind(path) tag := field.GetTag().Get(name) if tag == "" || tag == "-" { continue } - t := tagContext{field: field, h: c.b.v.helper, fields: c.field, add: inStruct(field, c.add), describe: c.describe(), - storage: c.b.fields, model: c.b.obj} + t := tagContext{field: field, h: s.Helper, fields: s.Fields, add: inStruct(field, s.Add), describe: s.Describe, + storage: s.Storage, model: s.Model} if err := t.apply(parseTag(tag)); err != nil { panic(fmt.Sprintf("valigo: tag %s:%q of field %s: %v", name, tag, path, err)) } diff --git a/tags_test.go b/internal/tags/tags_test.go similarity index 96% rename from tags_test.go rename to internal/tags/tags_test.go index f134202..a7fb4d5 100644 --- a/tags_test.go +++ b/internal/tags/tags_test.go @@ -1,4 +1,4 @@ -package valigo +package tags_test import ( "context" @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" + "github.com/insei/valigo" "github.com/insei/valigo/internal/testenv" "github.com/insei/valigo/str" ) @@ -76,9 +77,9 @@ func validTagsModel() *tagsModel { } } -func newTagsValidator() *Validator { - v := New() - Configure[tagsModel](v, func(b Configurator[tagsModel], m *tagsModel) { +func newTagsValidator() *valigo.Validator { + v := valigo.New() + valigo.Configure[tagsModel](v, func(b valigo.Configurator[tagsModel], m *tagsModel) { b.Tags("validate") b.Field(&m.Untagged).As(str.Of).MaxLen(1) // the rules in code with the tags }) @@ -211,7 +212,7 @@ func TestTagsErrors(t *testing.T) { }], `valigo: tag validate:"unique" of field A: unique of the slices of pointers isn't supported`}, {"dive into structs", tagsOf[struct { A []tagsAddress `validate:"dive"` - }], `valigo: tag validate:"dive" of field A: the elements of type valigo.tagsAddress aren't supported, configure the rules of their type`}, + }], `valigo: tag validate:"dive" of field A: the elements of type tags_test.tagsAddress aren't supported, configure the rules of their type`}, {"dive into a map of ints", tagsOf[struct { A map[int]string `validate:"dive,required"` }], `valigo: tag validate:"dive,required" of field A: dive is supported for the maps of strings to values, map[string]V`}, @@ -271,5 +272,5 @@ func TestTagsErrors(t *testing.T) { // tagsOf configures the tags of T. func tagsOf[T any]() { - Configure[T](New(), func(b Configurator[T], _ *T) { b.Tags("validate") }) + valigo.Configure[T](valigo.New(), func(b valigo.Configurator[T], _ *T) { b.Tags("validate") }) } diff --git a/zero.go b/internal/zero/zero.go similarity index 79% rename from zero.go rename to internal/zero/zero.go index f52c574..4b67650 100644 --- a/zero.go +++ b/internal/zero/zero.go @@ -1,4 +1,6 @@ -package valigo +// Package zero allocates the pointer fields of the models of Configure, so the rules are configured by the pointers +// to the fields of the nested structs. +package zero import ( "fmt" @@ -6,13 +8,13 @@ import ( "slices" ) -// Zero allocates an input structure such that all pointer fields +// Allocate allocates an input structure such that all pointer fields // are fully allocated, i.e. rather than having a nil value, // the pointer contains a pointer to an initialized value, // e.g. an *int field will be a pointer to 0 instead of a nil pointer. // -// zero does not allocate private fields. -func zero(obj interface{}) error { +// Allocate does not allocate private fields. +func Allocate(obj interface{}) error { val := reflect.ValueOf(obj) if val.Kind() != reflect.Pointer || val.IsNil() { return fmt.Errorf("input interface is not addressable (can't Set the memory address): %#v", @@ -56,9 +58,9 @@ func zeroStruct(val reflect.Value, path []reflect.Type) { } } -// MustZero will panic instead of return error -func mustZero(obj interface{}) { - err := zero(obj) +// Must is Allocate that panics on an error. +func Must(obj interface{}) { + err := Allocate(obj) if err != nil { panic(err) } diff --git a/zero_test.go b/internal/zero/zero_test.go similarity index 87% rename from zero_test.go rename to internal/zero/zero_test.go index 57cf7d7..67b9f22 100644 --- a/zero_test.go +++ b/internal/zero/zero_test.go @@ -1,4 +1,4 @@ -package valigo +package zero import ( "testing" @@ -217,9 +217,9 @@ func TestZero(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - err := zero(tc.input) + err := Allocate(tc.input) if (err != nil) != tc.wantErr { - t.Errorf("zero() error = %v, wantErr %v", err, tc.wantErr) + t.Errorf("Allocate() error = %v, wantErr %v", err, tc.wantErr) } }) } @@ -229,11 +229,11 @@ func TestMustZero(t *testing.T) { defer func() { if r := recover(); r != nil { } else { - t.Errorf("mustZero() did not panic") + t.Errorf("Must() did not panic") } }() - mustZero("hello") + Must("hello") } func TestZeroRecursiveTypes(t *testing.T) { @@ -243,17 +243,17 @@ func TestZeroRecursiveTypes(t *testing.T) { Meta *struct{ Parent *node } } obj := &node{} - if err := zero(obj); err != nil { - t.Fatalf("zero() error = %v", err) + if err := Allocate(obj); err != nil { + t.Fatalf("Allocate() error = %v", err) } if obj.Next != nil || obj.Meta == nil || obj.Meta.Parent != nil { - t.Errorf("zero() must allocate non recursive pointers only, got %+v", obj) + t.Errorf("Allocate() must allocate non recursive pointers only, got %+v", obj) } } func TestZeroErrors(t *testing.T) { - if err := zero(new(int)); err == nil { - t.Errorf("zero() of a non-struct must fail") + if err := Allocate(new(int)); err == nil { + t.Errorf("Allocate() of a non-struct must fail") } } @@ -263,10 +263,10 @@ func TestZeroSkipsUnexportedFields(t *testing.T) { Shown *struct{ X int } } obj := &withHidden{} - if err := zero(obj); err != nil { - t.Fatalf("zero() error = %v", err) + if err := Allocate(obj); err != nil { + t.Fatalf("Allocate() error = %v", err) } if obj.hidden != nil || obj.Shown == nil { - t.Errorf("zero() must allocate exported fields only, got %+v", obj) + t.Errorf("Allocate() must allocate exported fields only, got %+v", obj) } } diff --git a/options.go b/options.go index 90c52b7..30163df 100644 --- a/options.go +++ b/options.go @@ -27,7 +27,7 @@ func (f optionFunc) apply(v *Validator) { func WithTranslator(t translator.Translator) Option { return optionFunc(func(v *Validator) { if t != nil { - v.helper.t = t + v.helper.Translator = t } }) } @@ -37,7 +37,7 @@ func WithTranslator(t translator.Translator) Option { func WithFieldLocationNamingFn(fn func(field fmap.Field) string) Option { return optionFunc(func(v *Validator) { if fn != nil { - v.helper.getFieldLocation = fn + v.helper.Location = fn } }) } diff --git a/options_test.go b/options_test.go index 57d90bc..923da3f 100644 --- a/options_test.go +++ b/options_test.go @@ -24,7 +24,7 @@ func TestOptionApply(t *testing.T) { opt := WithTranslator(tr) v := New(opt) opt.apply(v) - if v.helper.t == nil { + if v.helper.Translator == nil { t.Errorf("expected translator to be set") } } @@ -33,7 +33,7 @@ func TestOptionApplyWithNilTranslator(t *testing.T) { opt := WithTranslator(nil) v := New(opt) opt.apply(v) - if v.helper.t == nil { + if v.helper.Translator == nil { t.Errorf("expected translator to be nil") } } @@ -44,9 +44,9 @@ func TestOptionApplyWithFieldLocationNamingFn(t *testing.T) { } opt := WithFieldLocationNamingFn(fn) v := New(opt) - v.helper.getFieldLocation = nil + v.helper.Location = nil opt.apply(v) - if v.helper.getFieldLocation == nil { + if v.helper.Location == nil { t.Errorf("expected getFieldLocation to be set") } } @@ -55,7 +55,7 @@ func TestOptionApplyWithNilFieldLocationNamingFn(t *testing.T) { opt := WithFieldLocationNamingFn(nil) v := New(opt) opt.apply(v) - if v.helper.getFieldLocation == nil { + if v.helper.Location == nil { t.Errorf("expected getFieldLocation to be nil") } } @@ -73,10 +73,10 @@ func TestOptionApplyWithMultipleOptions(t *testing.T) { v := New(opt1, opt2) opt1.apply(v) opt2.apply(v) - if v.helper.t == nil { + if v.helper.Translator == nil { t.Errorf("expected translator to be set") } - if v.helper.getFieldLocation == nil { + if v.helper.Location == nil { t.Errorf("expected getFieldLocation to be set") } } diff --git a/validator.go b/validator.go index 84b1be4..c46a76a 100644 --- a/validator.go +++ b/validator.go @@ -11,6 +11,8 @@ import ( "github.com/insei/fmap/v3" + "github.com/insei/valigo/internal/helper" + "github.com/insei/valigo/internal/zero" "github.com/insei/valigo/shared" ) @@ -18,7 +20,7 @@ import ( type Validator struct { validators map[reflect.Type][]shared.ValidationFn constraints map[reflect.Type][]shared.Constraint - helper *helper + helper *helper.Helper transformError func(errs []shared.Error) []error } @@ -105,7 +107,7 @@ func New(opts ...Option) *Validator { v := &Validator{ validators: make(map[reflect.Type][]shared.ValidationFn), constraints: make(map[reflect.Type][]shared.Constraint), - helper: newHelper(), + helper: helper.New(), transformError: func(errs []shared.Error) []error { errsNew := make([]error, len(errs)) for i, err := range errs { @@ -133,6 +135,6 @@ func Configure[T any](v *Validator, fn func(builder Configurator[T], m *T)) { panic(err) } // allocate all pointer fields values recursively - mustZero(model) + zero.Must(model) fn(Configurator[T]{b: &builder[T]{v: v, obj: model, fields: fields}}, model) }