@@ -17,6 +17,7 @@ package sidecar
17
17
18
18
import (
19
19
"fmt"
20
+ "slices"
20
21
21
22
"github.com/go-logr/logr"
22
23
corev1 "k8s.io/api/core/v1"
@@ -75,37 +76,28 @@ func remove(pod corev1.Pod) corev1.Pod {
75
76
return pod
76
77
}
77
78
78
- var containers []corev1.Container
79
- for _ , container := range pod .Spec .Containers {
80
- if container .Name != naming .Container () {
81
- containers = append (containers , container )
82
- }
83
- }
84
- pod .Spec .Containers = containers
85
-
86
- // NOTE: we also remove init containers (native sidecars) since k8s 1.28.
87
- // This should have no side effects.
88
- var initContainers []corev1.Container
89
- for _ , initContainer := range pod .Spec .InitContainers {
90
- if initContainer .Name != naming .Container () {
91
- initContainers = append (initContainers , initContainer )
92
- }
79
+ fn := func (c corev1.Container ) bool { return c .Name == naming .Container () }
80
+ pod .Spec .Containers = slices .DeleteFunc (pod .Spec .Containers , fn )
81
+
82
+ if featuregate .EnableNativeSidecarContainers .IsEnabled () {
83
+ // NOTE: we also remove init containers (native sidecars) since k8s 1.28.
84
+ // This should have no side effects.
85
+ pod .Spec .InitContainers = slices .DeleteFunc (pod .Spec .InitContainers , fn )
93
86
}
94
- pod .Spec .InitContainers = initContainers
95
87
return pod
96
88
}
97
89
98
90
// existsIn checks whether a sidecar container exists in the given pod.
99
91
func existsIn (pod corev1.Pod ) bool {
100
- for _ , container := range pod .Spec .Containers {
101
- if container .Name == naming .Container () {
102
- return true
103
- }
92
+ fn := func (c corev1.Container ) bool { return c .Name == naming .Container () }
93
+ if slices .ContainsFunc (pod .Spec .Containers , fn ) {
94
+ return true
104
95
}
105
- // NOTE: we also check init containers (native sidecars) since k8s 1.28.
106
- // This should have no side effects.
107
- for _ , container := range pod .Spec .InitContainers {
108
- if container .Name == naming .Container () {
96
+
97
+ if featuregate .EnableNativeSidecarContainers .IsEnabled () {
98
+ // NOTE: we also check init containers (native sidecars) since k8s 1.28.
99
+ // This should have no side effects.
100
+ if slices .ContainsFunc (pod .Spec .InitContainers , fn ) {
109
101
return true
110
102
}
111
103
}
0 commit comments