1515package resource
1616
1717import (
18- "context "
18+ "maps "
1919
2020 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
21- "sigs.k8s.io/controller-runtime/pkg/client"
22- "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
2321)
2422
2523var (
@@ -38,14 +36,7 @@ func SetGlobalLabels(labels map[string]string) {
3836
3937// GetGlobalLabels returns a copy of the current global labels.
4038func GetGlobalLabels () map [string ]string {
41- if globalLabels == nil {
42- return make (map [string ]string )
43- }
44- result := make (map [string ]string , len (globalLabels ))
45- for k , v := range globalLabels {
46- result [k ] = v
47- }
48- return result
39+ return maps .Clone (globalLabels )
4940}
5041
5142// AddGlobalLabels adds the global labels to the given object's labels.
@@ -54,58 +45,5 @@ func AddGlobalLabels(obj metav1.Object) {
5445 if obj .GetLabels () == nil {
5546 obj .SetLabels (make (map [string ]string ))
5647 }
57- labels := obj .GetLabels ()
58- for k , v := range globalLabels {
59- labels [k ] = v
60- }
61- obj .SetLabels (labels )
62- }
63-
64- // MergeLabels creates a new map containing all global labels.
65- // Optionally, additional labels can be provided which will be merged with the global labels.
66- func MergeLabels (additionalLabels ... map [string ]string ) map [string ]string {
67- result := GetGlobalLabels ()
68- for _ , labels := range additionalLabels {
69- for k , v := range labels {
70- result [k ] = v
71- }
72- }
73- return result
74- }
75-
76- // CreateOrUpdate is a wrapper around controllerutil.CreateOrUpdate that automatically adds global labels and annotations.
77- // It takes the same parameters as controllerutil.CreateOrUpdate plus an optional list of additional labels to merge.
78- func CreateOrUpdate (ctx context.Context , c client.Client , obj client.Object ,
79- mutateFn func () error ) (controllerutil.OperationResult , error ) {
80- // Create a wrapper mutation function that adds labels before calling the original
81- wrappedMutateFn := func () error {
82- // First call the original mutation function
83- if err := mutateFn (); err != nil {
84- return err
85- }
86-
87- // Then add global labels and any additional labels
88- if obj .GetLabels () == nil {
89- obj .SetLabels (make (map [string ]string ))
90- }
91- labels := obj .GetLabels ()
92- for k , v := range GetGlobalLabels () {
93- labels [k ] = v
94- }
95- obj .SetLabels (labels )
96-
97- // Add global annotations
98- if obj .GetAnnotations () == nil {
99- obj .SetAnnotations (make (map [string ]string ))
100- }
101- annotations := obj .GetAnnotations ()
102- for k , v := range GetGlobalAnnotations () {
103- annotations [k ] = v
104- }
105- obj .SetAnnotations (annotations )
106-
107- return nil
108- }
109-
110- return controllerutil .CreateOrUpdate (ctx , c , obj , wrappedMutateFn )
48+ maps .Copy (obj .GetLabels (), globalLabels )
11149}
0 commit comments