-
Notifications
You must be signed in to change notification settings - Fork 117
/
helpers.go
82 lines (75 loc) · 2.03 KB
/
helpers.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
package v1alpha1
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
func AddFinalizer(ctx context.Context, c client.Client, obj client.Object) error {
if controllerutil.AddFinalizer(obj, FinalizerName) {
patchBytes := []byte(`{"metadata":{"finalizers":[`)
for i, finalizer := range obj.GetFinalizers() {
if i > 0 {
patchBytes = append(patchBytes, ',')
}
patchBytes = append(patchBytes, fmt.Sprintf("%q", finalizer)...)
}
patchBytes = append(patchBytes, "]}}"...)
if err := c.Patch(
ctx,
obj,
client.RawPatch(types.MergePatchType, patchBytes),
); err != nil {
return fmt.Errorf("patch annotation: %w", err)
}
return nil
}
return nil
}
func ClearAnnotations(ctx context.Context, c client.Client, obj client.Object, keys ...string) error {
if len(keys) == 0 {
return nil
}
patchBytes := []byte(`{"metadata":{"annotations":{`)
for i, key := range keys {
if i > 0 {
patchBytes = append(patchBytes, ',')
}
patchBytes = append(patchBytes, fmt.Sprintf(`"%s":null`, key)...)
}
patchBytes = append(patchBytes, "}}}"...)
patch := client.RawPatch(types.MergePatchType, patchBytes)
if err := c.Patch(ctx, obj, patch); err != nil {
return fmt.Errorf("patch annotation: %w", err)
}
return nil
}
func patchAnnotation(ctx context.Context, c client.Client, obj client.Object, key, value string) error {
patchBytes := []byte(
fmt.Sprintf(
`{"metadata":{"annotations":{"%s":"%s"}}}`,
key,
value,
),
)
patch := client.RawPatch(types.MergePatchType, patchBytes)
if err := c.Patch(ctx, obj, patch); err != nil {
return fmt.Errorf("patch annotation: %w", err)
}
return nil
}
func AddV05CompatibilityLabel(
ctx context.Context,
c client.Client,
obj client.Object,
) error {
patchBytes := []byte(
fmt.Sprintf(
`{"metadata":{"labels":{"%s":"true"}}}`,
V05CompatibilityLabelKey,
),
)
patch := client.RawPatch(types.MergePatchType, patchBytes)
return c.Patch(ctx, obj, patch)
}