-
Notifications
You must be signed in to change notification settings - Fork 731
/
util.go
64 lines (61 loc) 路 2.01 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package v1beta1
import (
"fmt"
"strings"
)
// dashExtractor unpacks the status resource name, unescaping `-`.
func dashExtractor(val string) []string {
b := strings.Builder{}
var tokens []string
var prevDash bool
for _, chr := range val {
if prevDash && chr != '-' {
tokens = append(tokens, b.String())
b.Reset()
prevDash = false
}
if chr == '-' {
if prevDash {
b.WriteRune(chr)
prevDash = false
continue
} else {
prevDash = true
continue
}
}
b.WriteRune(chr)
}
tokens = append(tokens, b.String())
return tokens
}
// DashPacker puts a list of strings into a dash-separated format. Note that
// it cannot handle empty strings, as that makes the dash separator for the empty
// string reduce to an escaped dash. This is fine because none of the packed strings
// are allowed to be empty. If this changes in the future, we could create a placeholder
// for the empty string, say `b`, and replace all instances of `b` in the input
// stream with `bb`, which could then be unfolded. If we need that, we are already
// changing the schema of the status resource, and therefore don't need to deal with
// it now. It also doesn't handle the case where a value begins or ends with a dash,
// which is also disallowed by the schema (and would require an additional placeholder
// character to fix). Finally, note that it is impossible to distinguish between
// a nil list of strings and a list of one empty string.
func DashPacker(vals ...string) (string, error) {
if len(vals) == 0 {
return "", fmt.Errorf("DashPacker cannot pack an empty list of strings")
}
b := strings.Builder{}
for i, val := range vals {
if strings.HasPrefix(val, "-") || strings.HasSuffix(val, "-") {
return "", fmt.Errorf("DashPacker cannot pack strings that begin or end with a dash: %+v", vals)
}
if len(val) == 0 {
return "", fmt.Errorf("DashPacker cannot pack empty strings: %v", vals)
}
if i != 0 {
b.WriteString("-")
}
b.WriteString(strings.ReplaceAll(val, "-", "--"))
}
return b.String(), nil
}