-
Notifications
You must be signed in to change notification settings - Fork 12
/
fako.go
53 lines (41 loc) · 1.39 KB
/
fako.go
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
package fako
import (
"reflect"
"github.com/markbates/inflect"
)
//Fill fills all the fields that have a fako: tag
func Fill(elems ...interface{}) {
for _, elem := range elems {
FillElem(elem)
}
}
//FillElem provides a way to fill a simple interface
func FillElem(strukt interface{}) {
fillWithDetails(strukt, []string{}, []string{})
}
//FillOnly fills fields that have a fako: tag and its name is on the second argument array
func FillOnly(strukt interface{}, fields ...string) {
fillWithDetails(strukt, fields, []string{})
}
//FillExcept fills fields that have a fako: tag and its name is not on the second argument array
func FillExcept(strukt interface{}, fields ...string) {
fillWithDetails(strukt, []string{}, fields)
}
func fillWithDetails(strukt interface{}, only []string, except []string) {
elem := reflect.ValueOf(strukt).Elem()
elemT := reflect.TypeOf(strukt).Elem()
for i := 0; i < elem.NumField(); i++ {
field := elem.Field(i)
fieldt := elemT.Field(i)
fakeType := fieldt.Tag.Get("fako")
if fakeType != "" {
fakeType = inflect.Camelize(fakeType)
function := findFakeFunctionFor(fakeType)
inOnly := len(only) == 0 || (len(only) > 0 && contains(only, fieldt.Name))
notInExcept := len(except) == 0 || (len(except) > 0 && !contains(except, fieldt.Name))
if field.CanSet() && fakeType != "" && inOnly && notInExcept {
field.SetString(function())
}
}
}
}