forked from creasty/defaults
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunset.go
86 lines (79 loc) · 1.74 KB
/
unset.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package defaults
import (
"reflect"
)
const (
unsetFlag = "unset"
// unsetRecursion means that the field will be unset recursively
unsetRecursion = "walk"
)
func MustUnset(ptr interface{}) {
if err := Unset(ptr); err != nil {
panic(err)
}
}
func Unset(obj interface{}) error {
v := indirect(reflect.ValueOf(obj))
if v.Kind() != reflect.Struct {
return errInvalidType
}
unsetStruct(v)
return nil
}
func unsetStruct(obj reflect.Value) {
t := obj.Type()
for i := 0; i < t.NumField(); i++ {
unsetVal := t.Field(i).Tag.Get(unsetFlag)
if unsetVal == "-" {
continue
}
unsetField(obj.Field(i), unsetVal == unsetRecursion)
}
}
func indirect(v reflect.Value) reflect.Value {
finalValue := v
for finalValue.Kind() == reflect.Ptr {
finalValue = finalValue.Elem()
}
return finalValue
}
func unsetField(field reflect.Value, unsetWalk bool) {
if !field.CanSet() {
return
}
isInitial := isInitialValue(field)
if isInitial {
return
}
if !unsetWalk {
field.Set(reflect.Zero(field.Type()))
return
}
switch field.Kind() {
default:
field.Set(reflect.Zero(field.Type()))
case reflect.Ptr:
unsetField(field.Elem(), true)
case reflect.Struct:
unsetStruct(field)
case reflect.Slice:
for j := 0; j < field.Len(); j++ {
unsetField(field.Index(j), true)
}
case reflect.Map:
for _, e := range field.MapKeys() {
var mapValue = field.MapIndex(e)
switch mapValue.Kind() {
case reflect.Ptr:
unsetField(mapValue.Elem(), true)
case reflect.Struct, reflect.Slice, reflect.Map:
ref := reflect.New(mapValue.Type())
ref.Elem().Set(mapValue)
unsetField(ref.Elem(), true)
field.SetMapIndex(e, ref.Elem().Convert(mapValue.Type()))
default:
field.SetMapIndex(e, reflect.Zero(mapValue.Type()))
}
}
}
}