forked from carvel-dev/kapp
/
mod_field_remove.go
99 lines (81 loc) · 2.17 KB
/
mod_field_remove.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
87
88
89
90
91
92
93
94
95
96
97
98
99
package resources
import (
"fmt"
)
type FieldRemoveMod struct {
ResourceMatcher ResourceMatcher
Path Path
}
var _ ResourceMod = FieldRemoveMod{}
var _ ResourceModWithMultiple = FieldCopyMod{}
func (t FieldRemoveMod) ApplyFromMultiple(res Resource, _ map[FieldCopyModSource]Resource) error {
return t.Apply(res)
}
func (t FieldRemoveMod) Apply(res Resource) error {
if !t.ResourceMatcher.Matches(res) {
return nil
}
err := t.apply(res.unstructured().Object, t.Path)
if err != nil {
return fmt.Errorf("FieldRemoveMod for path '%s' on resource '%s': %s", t.Path.AsString(), res.Description(), err)
}
return nil
}
func (t FieldRemoveMod) apply(obj interface{}, path Path) error {
for i, part := range path {
isLast := len(path) == i+1
switch {
case part.MapKey != nil:
typedObj, ok := obj.(map[string]interface{})
if !ok {
// TODO check strictness?
if typedObj == nil {
return nil // map is a nil, nothing to remove
}
return fmt.Errorf("Unexpected non-map found: %T", obj)
}
if isLast {
delete(typedObj, *part.MapKey)
return nil
}
var found bool
obj, found = typedObj[*part.MapKey]
if !found {
return nil // map key is not found, nothing to remove
}
case part.ArrayIndex != nil:
if isLast {
return fmt.Errorf("Expected last part of the path to be map key")
}
switch {
case part.ArrayIndex.All != nil:
typedObj, ok := obj.([]interface{})
if !ok {
return fmt.Errorf("Unexpected non-array found: %T", obj)
}
for _, obj := range typedObj {
err := t.apply(obj, path[i+1:])
if err != nil {
return err
}
}
return nil // dealt with children, get out
case part.ArrayIndex.Index != nil:
typedObj, ok := obj.([]interface{})
if !ok {
return fmt.Errorf("Unexpected non-array found: %T", obj)
}
if *part.ArrayIndex.Index < len(typedObj) {
obj = typedObj[*part.ArrayIndex.Index]
} else {
return nil // index not found, nothing to remove
}
default:
panic(fmt.Sprintf("Unknown array index: %#v", part.ArrayIndex))
}
default:
panic(fmt.Sprintf("Unexpected path part: %#v", part))
}
}
panic("unreachable")
}