Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/insei/fmap/v3"

"github.com/insei/valigo/internal/tags"
"github.com/insei/valigo/shared"
)

Expand Down Expand Up @@ -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)
}
12 changes: 12 additions & 0 deletions builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
3 changes: 2 additions & 1 deletion docs/architecture/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
44 changes: 0 additions & 44 deletions helper.go

This file was deleted.

47 changes: 47 additions & 0 deletions internal/helper/helper.go
Original file line number Diff line number Diff line change
@@ -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()
},
}
}
6 changes: 3 additions & 3 deletions helper_test.go → internal/helper/helper_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package valigo
package helper

import (
"context"
Expand All @@ -13,7 +13,7 @@ type admin struct {
}

func TestHelperErrorT(t *testing.T) {
h := newHelper()
h := New()
testAdmin := admin{
Name: "John",
Age: 33,
Expand All @@ -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)
}
}
34 changes: 21 additions & 13 deletions tags.go → internal/tags/tags.go
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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))
}
Expand Down
13 changes: 7 additions & 6 deletions tags_test.go → internal/tags/tags_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package valigo
package tags_test

import (
"context"
Expand All @@ -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"
)
Expand Down Expand Up @@ -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
})
Expand Down Expand Up @@ -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`},
Expand Down Expand Up @@ -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") })
}
16 changes: 9 additions & 7 deletions zero.go → internal/zero/zero.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
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"
"reflect"
"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",
Expand Down Expand Up @@ -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)
}
Expand Down
26 changes: 13 additions & 13 deletions zero_test.go → internal/zero/zero_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package valigo
package zero

import (
"testing"
Expand Down Expand Up @@ -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)
}
})
}
Expand All @@ -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) {
Expand All @@ -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")
}
}

Expand All @@ -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)
}
}
4 changes: 2 additions & 2 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
})
}
Expand All @@ -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
}
})
}
Expand Down
Loading
Loading