Expose smart path splitter as a utility.

This commit is contained in:
monopole
2021-01-31 06:45:04 -08:00
parent 86168cebbc
commit b3a9314e27
5 changed files with 73 additions and 74 deletions

View File

@@ -0,0 +1,22 @@
// Copyright 2021 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package utils
import "strings"
// PathSplitter splits a slash delimited string, permitting escaped slashes.
func PathSplitter(path string) []string {
ps := strings.Split(path, "/")
var res []string
res = append(res, ps[0])
for i := 1; i < len(ps); i++ {
last := len(res) - 1
if strings.HasSuffix(res[last], `\`) {
res[last] = strings.TrimSuffix(res[last], `\`) + "/" + ps[i]
} else {
res = append(res, ps[i])
}
}
return res
}

View File

@@ -0,0 +1,49 @@
// Copyright 2021 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package utils_test
import (
"testing"
"github.com/stretchr/testify/assert"
. "sigs.k8s.io/kustomize/api/internal/utils"
)
func TestPathSplitter(t *testing.T) {
for _, tc := range []struct {
exp []string
path string
}{
{
path: "",
exp: []string{""},
},
{
path: "s",
exp: []string{"s"},
},
{
path: "a/b/c",
exp: []string{"a", "b", "c"},
},
{
path: `a/b[]/c`,
exp: []string{"a", "b[]", "c"},
},
{
path: `a/b\/c/d\/e/f`,
exp: []string{"a", "b/c", "d/e", "f"},
},
{
// The actual reason for this.
path: `metadata/annotations/nginx.ingress.kubernetes.io\/auth-secret`,
exp: []string{
"metadata",
"annotations",
"nginx.ingress.kubernetes.io/auth-secret"},
},
} {
assert.Equal(t, tc.exp, PathSplitter(tc.path))
}
}