Skip to content

Commit 7ad5b77

Browse files
authored
Check resource duplication by GVKNN (#567)
1 parent 5e888be commit 7ad5b77

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

go/fn/resourcelist.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,21 @@ type ResourceList struct {
5757
Results Results `yaml:"results,omitempty" json:"results,omitempty"`
5858
}
5959

60+
// CheckResourceDuplication checks the GVKNN of resourceList.items to make sure they are unique. It returns errors if
61+
// found more than one resource having the same GVKNN.
62+
func CheckResourceDuplication(rl *ResourceList) error {
63+
idMap := map[yaml.ResourceIdentifier]struct{}{}
64+
for _, obj := range rl.Items {
65+
id := obj.resourceIdentifier()
66+
if _, ok := idMap[*id]; ok{
67+
return fmt.Errorf("duplicate Resource(apiVersion=%v, kind=%v, Namespace=%v, Name=%v)",
68+
obj.GetAPIVersion(), obj.GetKind(), obj.GetNamespace(), obj.GetName())
69+
}
70+
idMap[*id] = struct{}{}
71+
}
72+
return nil
73+
}
74+
6075
// ParseResourceList parses a ResourceList from the input byte array.
6176
func ParseResourceList(in []byte) (*ResourceList, error) {
6277
rl := &ResourceList{}

go/fn/resourcelist_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package fn
2+
3+
import "testing"
4+
5+
var dupResourceInput = []byte(`
6+
apiVersion: config.kubernetes.io/v1
7+
kind: ResourceList
8+
items:
9+
- apiVersion: v1
10+
kind: Namespace
11+
metadata:
12+
name: example
13+
- apiVersion: v1
14+
kind: Namespace
15+
metadata:
16+
name: example
17+
`)
18+
19+
func TestCheckResourceDuplication(t *testing.T) {
20+
rl, _ := ParseResourceList(dupResourceInput)
21+
err := CheckResourceDuplication(rl)
22+
if err == nil {
23+
t.Errorf("expect to received duplicate error: got nil")
24+
}
25+
expectErr := "duplicate Resource(apiVersion=v1, kind=Namespace, Namespace=, Name=example)"
26+
if err.Error() != expectErr {
27+
t.Errorf("expect CheckResourceDuplication to fail; got %v, want %v", err ,expectErr)
28+
}
29+
}

go/fn/run.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,12 @@ func Run(p ResourceListProcessor, input []byte) (out []byte, err error) {
5858
v := recover()
5959
if v != nil {
6060
switch t := v.(type) {
61+
case ErrKubeObjectFields:
62+
err = &t
6163
case *ErrKubeObjectFields:
6264
err = t
65+
case ErrSubObjectFields:
66+
err = &t
6367
case *ErrSubObjectFields:
6468
err = t
6569
default:

0 commit comments

Comments
 (0)