-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathfako.go
More file actions
74 lines (61 loc) · 1.96 KB
/
Copy pathfako.go
File metadata and controls
74 lines (61 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package fako
import (
"reflect"
"slices"
)
// Fill fills all the fields that have a fako: tag
// This function is safe for concurrent use.
func Fill(elems ...any) {
for _, elem := range elems {
FillElem(elem)
}
}
// FillElem provides a way to fill a simple interface
// This function is safe for concurrent use.
func FillElem(strukt any) {
fillWithDetails(strukt, []string{}, []string{})
}
// FillOnly fills fields that have a fako: tag and its name is on the second argument array
// This function is safe for concurrent use.
func FillOnly(strukt any, fields ...string) {
fillWithDetails(strukt, fields, []string{})
}
// FillExcept fills fields that have a fako: tag and its name is not on the second argument array
// This function is safe for concurrent use.
func FillExcept(strukt any, fields ...string) {
fillWithDetails(strukt, []string{}, fields)
}
// fillWithDetails fills fields that have a fako: tag and its name is on the second argument array or not on the third argument array
// This function is safe for concurrent use.
func fillWithDetails(strukt any, only []string, except []string) {
elem := reflect.ValueOf(strukt).Elem()
elemT := reflect.TypeOf(strukt).Elem()
for i := range elem.NumField() {
field := elem.Field(i)
fieldt := elemT.Field(i)
fakerID := fieldt.Tag.Get("fako")
fakerID = camelize(fakerID)
// If no fako tag is specified, try to match field name with faker functions
if fakerID == "" {
// Convert field name to camelized format and check if a faker function exists
fakerID = camelize(fieldt.Name)
_, exists := allGenerators()[fakerID]
if !exists {
continue
}
}
if fakerID == "" {
continue
}
inOnly := len(only) == 0 || (len(only) > 0 && slices.Contains(only, fieldt.Name))
inExcept := len(except) != 0 && slices.Contains(except, fieldt.Name)
if !inOnly || inExcept {
continue
}
if !field.CanSet() {
continue
}
function := findFakeFunctionFor(fakerID)
field.SetString(function())
}
}