Skip to content

Commit 67b9a3b

Browse files
committed
fix: avoid nameclashes by considering the filepath
Signed-off-by: Nico Braun <[email protected]>
1 parent d9ba9b2 commit 67b9a3b

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

functions/go/gatekeeper/main.go

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,21 @@ import (
1919
"fmt"
2020
"io/ioutil"
2121
"os"
22+
"strings"
2223

2324
"github.com/GoogleContainerTools/kpt-functions-catalog/functions/go/gatekeeper/generated"
2425
"github.com/spf13/cobra"
2526
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
2627
"sigs.k8s.io/kustomize/kyaml/fn/framework"
2728
"sigs.k8s.io/kustomize/kyaml/kio"
29+
"sigs.k8s.io/kustomize/kyaml/kio/kioutil"
2830
k8syaml "sigs.k8s.io/yaml"
2931
)
3032

3133
const (
32-
stdin = "/dev/stdin"
33-
stdout = "/dev/stdout"
34+
stdin = "/dev/stdin"
35+
stdout = "/dev/stdout"
36+
nullByte = "\x00"
3437
)
3538

3639
type GatekeeperProcessor struct {
@@ -59,6 +62,15 @@ func (gkp *GatekeeperProcessor) Process(resourceList *framework.ResourceList) er
5962
return err
6063
}
6164

65+
// add the filepath to the objects name in sanitized form. this is done
66+
// to get unique identifier in case the same resource is defined in
67+
// different files. Usually this happens when running the function
68+
// across packages
69+
if !isTemplate(un) && !isConstraint(un) {
70+
un.SetName(fmt.Sprintf("%s%s%s", un.GetName(), nullByte,
71+
strings.ReplaceAll(item.GetAnnotations()[kioutil.PathAnnotation], "/", nullByte)))
72+
}
73+
6274
objects = append(objects, un)
6375
}
6476

@@ -74,6 +86,17 @@ func (gkp *GatekeeperProcessor) Process(resourceList *framework.ResourceList) er
7486
},
7587
}
7688
}
89+
90+
// unwrap the null-byte filename hack again
91+
for i, item := range result.Items {
92+
parts := strings.SplitN(item.ResourceRef.Name, nullByte, 2)
93+
item.ResourceRef.Name = parts[0]
94+
if len(parts) == 2 {
95+
item.Field.Path = strings.ReplaceAll(parts[1], nullByte, "/")
96+
}
97+
result.Items[i] = item
98+
}
99+
77100
resourceList.Result = result
78101
if resultContainsError(result) {
79102
return result
@@ -198,3 +221,13 @@ func resultContainsError(result *framework.Result) bool {
198221
}
199222
return false
200223
}
224+
225+
func isTemplate(u *unstructured.Unstructured) bool {
226+
gvk := u.GroupVersionKind()
227+
return gvk.Kind == "ConstraintTemplate"
228+
}
229+
230+
func isConstraint(u *unstructured.Unstructured) bool {
231+
gvk := u.GroupVersionKind()
232+
return gvk.Group == "constraints.gatekeeper.sh"
233+
}

0 commit comments

Comments
 (0)