...
1 package v1
2
3 import (
4 "errors"
5
6 corev1 "k8s.io/api/core/v1"
7 )
8
9 var errMinObjectRef = errors.New("object reference must have, at a minimum: apiVersion, kind, and name")
10
11
12 func SetObjectReference(objects *[]corev1.ObjectReference, newObject corev1.ObjectReference) error {
13 if !minObjectReference(newObject) {
14 return errMinObjectRef
15 }
16
17 if objects == nil {
18 objects = &[]corev1.ObjectReference{}
19 }
20 existingObject, err := FindObjectReference(*objects, newObject)
21 if err != nil {
22 return err
23 }
24 if existingObject == nil {
25 *objects = append(*objects, newObject)
26 } else {
27 *existingObject = newObject
28 }
29 return nil
30 }
31
32
33 func RemoveObjectReference(objects *[]corev1.ObjectReference, rmObject corev1.ObjectReference) error {
34 if !minObjectReference(rmObject) {
35 return errMinObjectRef
36 }
37
38 if objects == nil {
39 return nil
40 }
41 newObjectReferences := []corev1.ObjectReference{}
42
43
44 for _, object := range *objects {
45 if !ObjectReferenceEqual(object, rmObject) {
46 newObjectReferences = append(newObjectReferences, object)
47 }
48 }
49
50 *objects = newObjectReferences
51 return nil
52 }
53
54
55
56 func FindObjectReference(objects []corev1.ObjectReference, find corev1.ObjectReference) (*corev1.ObjectReference, error) {
57 if !minObjectReference(find) {
58 return nil, errMinObjectRef
59 }
60
61 for i := range objects {
62 if ObjectReferenceEqual(find, objects[i]) {
63 return &objects[i], nil
64 }
65 }
66
67 return nil, nil
68 }
69
70
71
72
73
74 func ObjectReferenceEqual(gotRef, expectedRef corev1.ObjectReference) bool {
75 if !minObjectReference(gotRef) || !minObjectReference(expectedRef) {
76 return false
77 }
78 if gotRef.APIVersion != expectedRef.APIVersion {
79 return false
80 }
81 if gotRef.Kind != expectedRef.Kind {
82 return false
83 }
84 if gotRef.Name != expectedRef.Name {
85 return false
86 }
87 if expectedRef.Namespace != "" && (gotRef.Namespace != expectedRef.Namespace) {
88 return false
89 }
90 return true
91 }
92
93
94
95
96 func minObjectReference(objRef corev1.ObjectReference) bool {
97 if objRef.APIVersion == "" {
98 return false
99 }
100 if objRef.Kind == "" {
101 return false
102 }
103 if objRef.Name == "" {
104 return false
105 }
106
107 return true
108 }
109
View as plain text