MSP-8520 up deps
This commit is contained in:
1 parent
c14f8441fb
commit
884aa6a439
304 files changed
+18223
-4352
No files matched your search
+2
@@ -43,6 +43,7 @@ go get -u github.com/go-faker/faker/v4
|
||||
- [language: example_with_tags_lang_test.go](/example_with_tags_lang_test.go)
|
||||
- [unique: example_with_tags_unique_test.go](example_with_tags_unique_test.go)
|
||||
- [slice length: example_with_tags_slicelength_test.go](example_with_tags_slicelength_test.go)
|
||||
- [template (derived fields): example_template_tag_test.go](example_template_tag_test.go)
|
||||
- Custom Struct's tag (define your own faker data): [example_custom_faker_test.go](/example_custom_faker_test.go)
|
||||
- Without struct's tag: [example_without_tag_test.go](/example_without_tag_test.go)
|
||||
- Single Fake Data Function: [example_single_fake_data_test.go](/example_single_fake_data_test.go)
|
||||
@@ -103,6 +104,7 @@ Unfortunately this library has some limitation
|
||||
- It does not support the `map[any]any`, `map[T]any` & `map[any]T` data types (where `T` is any concrete type). Once again, we cannot generate values for an unknown data type.
|
||||
- Some extra custom types can be supported IF AND ONLY IF extended with [AddProvider()](https://github.com/go-faker/faker/blob/7473ac7d8d0440d24addac302c73e13c08895764/faker.go#L303) please see [example](example_custom_faker_test.go#L46)
|
||||
- The `oneof` tag currently only supports `string`, the `int` types, and both `float32` & `float64`. Further support is coming soon (i.e. hex numbers, etc). See [example](example_with_tags_test.go#L53) for usage.
|
||||
- The `template` tag currently only supports `string`, named string types & `*string`, and can only reference the fields of the struct that declares it. See [example](example_template_tag_test.go) for usage.
|
||||
|
||||
## Contribution
|
||||
|
||||
|
||||
+64
-1
@@ -91,6 +91,7 @@ const (
|
||||
comma = ","
|
||||
colon = ":"
|
||||
ONEOF = "oneof"
|
||||
TemplateTag = "template"
|
||||
RussianFirstNameMaleTag = "russian_first_name_male"
|
||||
RussianMiddleNameMaleTag = "russian_middle_name_male"
|
||||
RussianLastNameMaleTag = "russian_last_name_male"
|
||||
@@ -586,6 +587,8 @@ func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (re
|
||||
}
|
||||
originalDataVal := reflect.ValueOf(item)
|
||||
v := reflect.New(t).Elem()
|
||||
// collect template fields to evaluate in a second pass
|
||||
var templateFields []int
|
||||
if opts.MaxFieldDepthOption == 0 {
|
||||
return v, nil
|
||||
} else if opts.MaxFieldDepthOption > 0 {
|
||||
@@ -617,6 +620,27 @@ func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (re
|
||||
}
|
||||
|
||||
tags := decodeTags(t, i, opts.TagName)
|
||||
// A template field is derived from other fields, so it is deferred to a
|
||||
// second pass that runs once every other field has been generated.
|
||||
if tags.isTemplate {
|
||||
if tags.unique {
|
||||
// A template over fixed inputs is deterministic, so the retry loop
|
||||
// could never produce a different value. Fail loudly instead.
|
||||
return reflect.Value{}, fmt.Errorf(fakerErrors.ErrTemplateWithUnique, t.Field(i).Name)
|
||||
}
|
||||
if tags.keepOriginal {
|
||||
zero, err := isZero(originalDataVal.Field(i))
|
||||
if err != nil {
|
||||
return reflect.Value{}, err
|
||||
}
|
||||
if !zero {
|
||||
v.Field(i).Set(originalDataVal.Field(i))
|
||||
continue
|
||||
}
|
||||
}
|
||||
templateFields = append(templateFields, i)
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case tags.keepOriginal:
|
||||
zero, err := isZero(reflect.ValueOf(item).Field(i))
|
||||
@@ -675,6 +699,10 @@ func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (re
|
||||
}
|
||||
|
||||
}
|
||||
// second pass: evaluate template fields using values generated above
|
||||
if err := evaluateTemplateFields(t, v, templateFields, opts.TagName); err != nil {
|
||||
return reflect.Value{}, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
@@ -699,6 +727,10 @@ func decodeTags(typ reflect.Type, i int, tagName string) structTag {
|
||||
uni := false
|
||||
res := make([]string, 0)
|
||||
pMap := make(map[string]string)
|
||||
// body collects the template body once a "template:" chunk is seen. Everything
|
||||
// after that chunk belongs to the body, so a template may contain commas; only
|
||||
// the standalone "keep" and "unique" chunks keep their usual meaning.
|
||||
var body []string
|
||||
for _, tag := range tags {
|
||||
if tag == keep {
|
||||
keepOriginal = true
|
||||
@@ -707,12 +739,30 @@ func decodeTags(typ reflect.Type, i int, tagName string) structTag {
|
||||
uni = true
|
||||
continue
|
||||
}
|
||||
if body != nil {
|
||||
body = append(body, tag)
|
||||
continue
|
||||
}
|
||||
if hasTemplatePrefix(strings.TrimSpace(tag)) {
|
||||
body = append(body, strings.TrimSpace(tag)[len(TemplateTag)+1:])
|
||||
continue
|
||||
}
|
||||
// res = append(res, tag)
|
||||
ptag := strings.ToLower(strings.Trim(strings.Split(tag, "=")[0], " "))
|
||||
pMap[ptag] = tag
|
||||
ptag = strings.ToLower(strings.Trim(strings.Split(tag, ":")[0], " "))
|
||||
pMap[ptag] = tag
|
||||
}
|
||||
if body != nil {
|
||||
// A template body is opaque: it must never reach the priority scanner, which
|
||||
// would otherwise hijack a chunk such as ", email: {{.X}}" as the email tag.
|
||||
return structTag{
|
||||
template: strings.Join(body, comma),
|
||||
isTemplate: true,
|
||||
unique: uni,
|
||||
keepOriginal: keepOriginal,
|
||||
}
|
||||
}
|
||||
// Priority
|
||||
for _, ptag := range PriorityTags {
|
||||
if tag, ok := pMap[ptag]; ok {
|
||||
@@ -739,9 +789,22 @@ func decodeTags(typ reflect.Type, i int, tagName string) structTag {
|
||||
}
|
||||
|
||||
type structTag struct {
|
||||
fieldType string
|
||||
fieldType string
|
||||
// template holds the verbatim template body when isTemplate is set. It is kept
|
||||
// out of fieldType because a template body is not a tag and must not be parsed
|
||||
// as one.
|
||||
template string
|
||||
unique bool
|
||||
keepOriginal bool
|
||||
isTemplate bool
|
||||
}
|
||||
|
||||
// hasTemplatePrefix reports whether s starts with "template:" (case-insensitive).
|
||||
// The colon is required, so `faker:"template"` and `faker:"templated"` stay with
|
||||
// the normal tag pipeline.
|
||||
func hasTemplatePrefix(s string) bool {
|
||||
const n = len(TemplateTag) + 1
|
||||
return len(s) >= n && strings.EqualFold(s[:n], TemplateTag+colon)
|
||||
}
|
||||
|
||||
func setDataWithTag(v reflect.Value, tag string, opt options.Options) error {
|
||||
|
||||
+13
@@ -10,6 +10,12 @@ package errors
|
||||
// ErrTagDoesNotExist: Error when tag does not exist and call RemoveProvider
|
||||
// ErrMoreArguments: Error on passing more arguments
|
||||
// ErrNotSupportedPointer: Error when passing unsupported pointer
|
||||
// ErrTemplateNotStringField: Error when the template tag is used on a non-string field
|
||||
// ErrTemplateEmptyBody: Error when the template tag has no body
|
||||
// ErrTemplateParse: Error when the template body fails to parse
|
||||
// ErrTemplateEvaluate: Error when the template body fails to execute
|
||||
// ErrTemplateCycle: Error when template fields reference each other in a cycle
|
||||
// ErrTemplateWithUnique: Error when the template tag is combined with the unique tag
|
||||
var (
|
||||
ErrUnsupportedKindPtr = "Unsupported kind: %s Change Without using * (pointer) in Field of %s"
|
||||
ErrUnsupportedKind = "Unsupported kind: %s"
|
||||
@@ -33,4 +39,11 @@ var (
|
||||
ErrNotEnoughTagArguments = "Not enough arguments for tag."
|
||||
ErrUnsupportedNumberType = "Unsupported Number type."
|
||||
ErrOnlyStructTypeSupported = "only struct type supported."
|
||||
|
||||
ErrTemplateNotStringField = "Template tag is only supported on string fields, field \"%s\" is %s"
|
||||
ErrTemplateEmptyBody = "Template tag for field \"%s\" has an empty body"
|
||||
ErrTemplateParse = "Failed to parse template for field \"%s\": %w"
|
||||
ErrTemplateEvaluate = "Failed to evaluate template for field \"%s\": %w"
|
||||
ErrTemplateCycle = "Template tag cycle detected: %s"
|
||||
ErrTemplateWithUnique = "Tag \"unique\" can not be combined with the template tag (field \"%s\")"
|
||||
)
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
package faker
|
||||
|
||||
// The template tag (`faker:"template:{{.Other}}"`) derives a field's value from
|
||||
// other fields of the same struct. Because a template reads values that faker
|
||||
// itself generates, template fields are filled in a second pass that runs after
|
||||
// every other field of the struct is done — see getFakedValueForStruct.
|
||||
//
|
||||
// Within that second pass, template fields are evaluated in dependency order
|
||||
// rather than declaration order, so a template may reference another template
|
||||
// field declared later. Only a true cycle is an error.
|
||||
//
|
||||
// TemplateTag is deliberately absent from PriorityTags: it is not a provider, and
|
||||
// listing it there would route the tag through setDataWithTag.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"text/template"
|
||||
"text/template/parse"
|
||||
"unicode"
|
||||
|
||||
fakerErrors "github.com/go-faker/faker/v4/pkg/errors"
|
||||
)
|
||||
|
||||
// templateField is one parsed, validated template-tagged field of a struct.
|
||||
type templateField struct {
|
||||
index int // index of the field within the struct
|
||||
name string // field name, used in error messages
|
||||
tpl *template.Template
|
||||
deps []int // positions within templatePlan.fields this field depends on
|
||||
}
|
||||
|
||||
// templatePlan is the validated evaluation plan for the template fields of one
|
||||
// struct type.
|
||||
type templatePlan struct {
|
||||
fields []templateField // declaration order
|
||||
order []int // positions within fields, in dependency order
|
||||
}
|
||||
|
||||
// evaluateTemplateFields fills the template-tagged fields of v listed in fields.
|
||||
// v must be an addressable struct value of type t. fields holds struct field
|
||||
// indices collected by the first pass; a template field missing from it was
|
||||
// handled by a higher-precedence option (IgnoreFields, OnlyZeroFields,
|
||||
// FieldProviders, keep) and is left alone.
|
||||
func evaluateTemplateFields(t reflect.Type, v reflect.Value, fields []int, tagName string) error {
|
||||
if len(fields) == 0 {
|
||||
return nil
|
||||
}
|
||||
if !v.CanAddr() {
|
||||
return errors.New(fakerErrors.ErrValueNotPtr)
|
||||
}
|
||||
plan, err := buildTemplatePlan(t, tagName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Templates read the struct itself rather than a map built by reflection. That
|
||||
// is what makes unexported fields safe: text/template reports them as an error
|
||||
// instead of us panicking on reflect.Value.Interface. Taking the address means
|
||||
// each template also sees the results written by earlier ones.
|
||||
data := v.Addr().Interface()
|
||||
var buf bytes.Buffer
|
||||
for _, p := range plan.order {
|
||||
tf := &plan.fields[p]
|
||||
if !containsFieldIndex(fields, tf.index) {
|
||||
continue
|
||||
}
|
||||
buf.Reset()
|
||||
if err := tf.tpl.Execute(&buf, data); err != nil {
|
||||
return fmt.Errorf(fakerErrors.ErrTemplateEvaluate, tf.name, err)
|
||||
}
|
||||
setTemplateResult(v.Field(tf.index), buf.String())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func containsFieldIndex(fields []int, idx int) bool {
|
||||
for _, f := range fields {
|
||||
if f == idx {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// buildTemplatePlan parses and validates every template-tagged field of t and
|
||||
// works out the order they must be evaluated in.
|
||||
func buildTemplatePlan(t reflect.Type, tagName string) (*templatePlan, error) {
|
||||
plan := &templatePlan{}
|
||||
posByName := make(map[string]int)
|
||||
|
||||
for i := range t.NumField() {
|
||||
f := t.Field(i)
|
||||
if !f.IsExported() {
|
||||
continue
|
||||
}
|
||||
tags := decodeTags(t, i, tagName)
|
||||
if !tags.isTemplate {
|
||||
continue
|
||||
}
|
||||
// Validate the destination before anything is evaluated, so a bad tag can
|
||||
// never leave some fields written and others not.
|
||||
if !templateAssignable(f.Type) {
|
||||
return nil, fmt.Errorf(fakerErrors.ErrTemplateNotStringField, f.Name, f.Type)
|
||||
}
|
||||
if strings.TrimSpace(tags.template) == "" {
|
||||
return nil, fmt.Errorf(fakerErrors.ErrTemplateEmptyBody, f.Name)
|
||||
}
|
||||
tpl, err := template.New(f.Name).Funcs(templateHelpers).Parse(tags.template)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(fakerErrors.ErrTemplateParse, f.Name, err)
|
||||
}
|
||||
posByName[f.Name] = len(plan.fields)
|
||||
plan.fields = append(plan.fields, templateField{index: i, name: f.Name, tpl: tpl})
|
||||
}
|
||||
if len(plan.fields) == 0 {
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// Only references to other template fields become edges. References to ordinary
|
||||
// fields need no ordering: the first pass already filled them.
|
||||
for p := range plan.fields {
|
||||
for _, ref := range templateFieldRefs(plan.fields[p].tpl.Tree) {
|
||||
if q, ok := posByName[ref]; ok {
|
||||
plan.fields[p].deps = append(plan.fields[p].deps, q)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
order, err := topoSortTemplateFields(plan.fields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plan.order = order
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// templateAssignable reports whether the template result can be stored in a field
|
||||
// of type t. Named string types work through SetString; *string is allocated.
|
||||
func templateAssignable(t reflect.Type) bool {
|
||||
return t.Kind() == reflect.String ||
|
||||
(t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.String)
|
||||
}
|
||||
|
||||
func setTemplateResult(f reflect.Value, s string) {
|
||||
if f.Kind() == reflect.Pointer {
|
||||
p := reflect.New(f.Type().Elem())
|
||||
p.Elem().SetString(s)
|
||||
f.Set(p)
|
||||
return
|
||||
}
|
||||
f.SetString(s)
|
||||
}
|
||||
|
||||
// templateFieldRefs returns the names of the struct fields a template reads, in
|
||||
// source order and deduplicated.
|
||||
//
|
||||
// It walks the parse tree rather than matching the template source with a regular
|
||||
// expression: only the tree can tell a field reference from literal text such as
|
||||
// "@Example.Com", can report `{{.Addr.City}}` as a reference to Addr alone, and
|
||||
// can tell that the dot inside a `range` or `with` body is the loop value rather
|
||||
// than the struct.
|
||||
func templateFieldRefs(tree *parse.Tree) []string {
|
||||
if tree == nil || tree.Root == nil {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
seen := make(map[string]struct{})
|
||||
add := func(name string) {
|
||||
if _, ok := seen[name]; !ok {
|
||||
seen[name] = struct{}{}
|
||||
out = append(out, name)
|
||||
}
|
||||
}
|
||||
var walk func(parse.Node)
|
||||
// walkBranch handles if/range/with. The controlling pipe is always evaluated
|
||||
// with the outer dot; range and with rebind dot for their body, so the body
|
||||
// cannot reference our struct's fields. An else body runs with the outer dot.
|
||||
walkBranch := func(b *parse.BranchNode, rebindsDot bool) {
|
||||
walk(b.Pipe)
|
||||
if !rebindsDot && b.List != nil {
|
||||
walk(b.List)
|
||||
}
|
||||
if b.ElseList != nil {
|
||||
walk(b.ElseList)
|
||||
}
|
||||
}
|
||||
walk = func(n parse.Node) {
|
||||
switch n := n.(type) {
|
||||
case *parse.ListNode:
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
for _, c := range n.Nodes {
|
||||
walk(c)
|
||||
}
|
||||
case *parse.ActionNode:
|
||||
walk(n.Pipe)
|
||||
case *parse.PipeNode:
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
for _, d := range n.Decl {
|
||||
walk(d)
|
||||
}
|
||||
for _, c := range n.Cmds {
|
||||
walk(c)
|
||||
}
|
||||
case *parse.CommandNode:
|
||||
for _, a := range n.Args {
|
||||
walk(a)
|
||||
}
|
||||
case *parse.FieldNode:
|
||||
if len(n.Ident) > 0 {
|
||||
add(n.Ident[0])
|
||||
}
|
||||
case *parse.ChainNode:
|
||||
if _, isDot := n.Node.(*parse.DotNode); isDot && len(n.Field) > 0 {
|
||||
add(n.Field[0])
|
||||
}
|
||||
walk(n.Node)
|
||||
case *parse.IfNode:
|
||||
walkBranch(&n.BranchNode, false)
|
||||
case *parse.RangeNode:
|
||||
walkBranch(&n.BranchNode, true)
|
||||
case *parse.WithNode:
|
||||
walkBranch(&n.BranchNode, true)
|
||||
case *parse.TemplateNode:
|
||||
walk(n.Pipe)
|
||||
}
|
||||
}
|
||||
walk(tree.Root)
|
||||
return out
|
||||
}
|
||||
|
||||
// topoSortTemplateFields returns the positions of fields in dependency order:
|
||||
// every field appears after the template fields it references. Roots are visited
|
||||
// in declaration order so the result is deterministic. A cycle, including a field
|
||||
// that references itself, is an error.
|
||||
func topoSortTemplateFields(fields []templateField) ([]int, error) {
|
||||
const (
|
||||
white = iota
|
||||
grey
|
||||
black
|
||||
)
|
||||
state := make([]int8, len(fields))
|
||||
order := make([]int, 0, len(fields))
|
||||
stack := make([]int, 0, len(fields))
|
||||
|
||||
var visit func(p int) error
|
||||
visit = func(p int) error {
|
||||
switch state[p] {
|
||||
case black:
|
||||
return nil
|
||||
case grey:
|
||||
return fmt.Errorf(fakerErrors.ErrTemplateCycle, cyclePath(fields, stack, p))
|
||||
}
|
||||
state[p] = grey
|
||||
stack = append(stack, p)
|
||||
for _, d := range fields[p].deps {
|
||||
if err := visit(d); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
stack = stack[:len(stack)-1]
|
||||
state[p] = black
|
||||
order = append(order, p)
|
||||
return nil
|
||||
}
|
||||
for p := range fields {
|
||||
if err := visit(p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return order, nil
|
||||
}
|
||||
|
||||
// cyclePath renders a cycle as "A -> B -> A", starting from where p first appears
|
||||
// on the visit stack.
|
||||
func cyclePath(fields []templateField, stack []int, p int) string {
|
||||
start := 0
|
||||
for i, s := range stack {
|
||||
if s == p {
|
||||
start = i
|
||||
break
|
||||
}
|
||||
}
|
||||
names := make([]string, 0, len(stack)-start+1)
|
||||
for _, s := range stack[start:] {
|
||||
names = append(names, fields[s].name)
|
||||
}
|
||||
names = append(names, fields[p].name)
|
||||
return strings.Join(names, " -> ")
|
||||
}
|
||||
|
||||
// templateHelpers is read-only after initialization and shared by every template.
|
||||
var templateHelpers = template.FuncMap{
|
||||
"lower": func(v any) string { return strings.ToLower(templateString(v)) },
|
||||
"upper": func(v any) string { return strings.ToUpper(templateString(v)) },
|
||||
"trim": func(v any) string { return strings.TrimSpace(templateString(v)) },
|
||||
"slug": func(v any) string { return slugify(templateString(v)) },
|
||||
}
|
||||
|
||||
// templateString coerces a template argument to a string so the helpers also work
|
||||
// on named string types, numbers and fmt.Stringer values.
|
||||
func templateString(v any) string {
|
||||
switch s := v.(type) {
|
||||
case nil:
|
||||
return ""
|
||||
case string:
|
||||
return s
|
||||
case fmt.Stringer:
|
||||
return s.String()
|
||||
}
|
||||
if rv := reflect.ValueOf(v); rv.Kind() == reflect.String {
|
||||
return rv.String()
|
||||
}
|
||||
return fmt.Sprint(v)
|
||||
}
|
||||
|
||||
// slugify lowercases s and replaces each run of non-alphanumeric characters with
|
||||
// a single dash, trimming dashes from both ends. Letters and digits of any script
|
||||
// are kept, so names generated by the Chinese and Russian providers survive.
|
||||
func slugify(s string) string {
|
||||
s = strings.ToLower(s)
|
||||
var b strings.Builder
|
||||
b.Grow(len(s))
|
||||
lastDash := false
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case unicode.IsLetter(r) || unicode.IsDigit(r):
|
||||
b.WriteRune(r)
|
||||
lastDash = false
|
||||
case !lastDash:
|
||||
b.WriteByte('-')
|
||||
lastDash = true
|
||||
}
|
||||
}
|
||||
return strings.Trim(b.String(), "-")
|
||||
}
|
||||
Reference in new issue
Block a user