k3s/vendor/github.com/rancher/wrangler/pkg/kv/split.go

46 lines
1.0 KiB
Go
Raw Normal View History

2019-01-12 04:58:27 +00:00
package kv
import "strings"
2019-12-12 01:27:03 +00:00
// Like split but if there is only one item return "", item
func RSplit(s, sep string) (string, string) {
parts := strings.SplitN(s, sep, 2)
if len(parts) == 1 {
return "", strings.TrimSpace(parts[0])
}
return strings.TrimSpace(parts[0]), strings.TrimSpace(safeIndex(parts, 1))
}
2019-01-12 04:58:27 +00:00
func Split(s, sep string) (string, string) {
parts := strings.SplitN(s, sep, 2)
return strings.TrimSpace(parts[0]), strings.TrimSpace(safeIndex(parts, 1))
}
2020-03-26 21:07:15 +00:00
func SplitLast(s, sep string) (string, string) {
idx := strings.LastIndex(s, sep)
if idx > -1 {
return strings.TrimSpace(s[:idx]), strings.TrimSpace(s[idx+1:])
}
return s, ""
}
2019-01-12 04:58:27 +00:00
func SplitMap(s, sep string) map[string]string {
2019-05-09 22:03:45 +00:00
return SplitMapFromSlice(strings.Split(s, sep))
}
func SplitMapFromSlice(parts []string) map[string]string {
2019-01-12 04:58:27 +00:00
result := map[string]string{}
2019-05-09 22:03:45 +00:00
for _, part := range parts {
2019-01-12 04:58:27 +00:00
k, v := Split(part, "=")
result[k] = v
}
return result
}
func safeIndex(parts []string, idx int) string {
if len(parts) <= idx {
return ""
}
return parts[idx]
}