Debian Codegraph @

kyaml/utils/pathsplitter.go

raw symbols SCIP
1 // Copyright 2021 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package utils
5
6 import "strings"
7
8 // TODO: Move these to kyaml
9
10 // PathSplitter splits a delimited string, permitting escaped delimiters.
11 func PathSplitter(path string, delimiter string) []string {
12 ps := strings.Split(path, delimiter)
13 var res []string
14
15 // allow path to start with forward slash
16 // i.e. /a/b/c
17 if len(ps) > 1 && ps[0] == "" {
18 ps = ps[1:]
19 }
20
21 res = append(res, ps[0])
22 for i := 1; i < len(ps); i++ {
23 last := len(res) - 1
24 if strings.HasSuffix(res[last], `\`) {
25 res[last] = strings.TrimSuffix(res[last], `\`) + delimiter + ps[i]
26 } else {
27 res = append(res, ps[i])
28 }
29 }
30 return res
31 }
32
33 // SmarterPathSplitter splits a path, retaining bracketed elements.
34 // If the element is a list entry identifier (defined by the '='),
35 // it will retain the brackets.
36 // E.g. "[name=com.foo.someapp]" survives as one thing after splitting
37 // "spec.template.spec.containers.[name=com.foo.someapp].image"
38 // See kyaml/yaml/match.go for use of list entry identifiers.
39 // If the element is a mapping entry identifier, it will remove the
40 // brackets.
41 // E.g. "a.b.c" survives as one thing after splitting
42 // "metadata.annotations.[a.b.c]
43 // This function uses `PathSplitter`, so it also respects escaped delimiters.
44 func SmarterPathSplitter(path string, delimiter string) []string {
45 var result []string
46 split := PathSplitter(path, delimiter)
47
48 for i := 0; i < len(split); i++ {
49 elem := split[i]
50 if strings.HasPrefix(elem, "[") && !strings.HasSuffix(elem, "]") {
51 // continue until we find the matching "]"
52 bracketed := []string{elem}
53 for i < len(split)-1 {
54 i++
55 bracketed = append(bracketed, split[i])
56 if strings.HasSuffix(split[i], "]") {
57 break
58 }
59 }
60 bracketedStr := strings.Join(bracketed, delimiter)
61 if strings.Contains(bracketedStr, "=") {
62 result = append(result, bracketedStr)
63 } else {
64 result = append(result, strings.Trim(bracketedStr, "[]"))
65 }
66 } else {
67 result = append(result, elem)
68 }
69 }
70 return result
71 }