Replace strings.SplitN with strings.Cut

Cut is a cleaner & more performant api relative to SplitN(_, _, 2) added in go 1.18

Previously applied this refactoring to buildah:
https://github.com/containers/buildah/pull/5239

Signed-off-by: Philip Dubé <philip@peerdb.io>
This commit is contained in:
Philip Dubé
2024-01-02 18:31:25 +00:00
parent f1ea4fbb3d
commit 522934d5cf
56 changed files with 596 additions and 678 deletions

32
pkg/env/env.go vendored
View File

@ -40,14 +40,9 @@ func Slice(m map[string]string) []string {
// map.
func Map(slice []string) map[string]string {
envmap := make(map[string]string, len(slice))
for _, val := range slice {
data := strings.SplitN(val, "=", 2)
if len(data) > 1 {
envmap[data[0]] = data[1]
} else {
envmap[data[0]] = ""
}
for _, line := range slice {
key, val, _ := strings.Cut(line, "=")
envmap[key] = val
}
return envmap
}
@ -94,26 +89,25 @@ func ParseFile(path string) (_ map[string]string, err error) {
}
func parseEnv(env map[string]string, line string) error {
data := strings.SplitN(line, "=", 2)
key, val, hasVal := strings.Cut(line, "=")
// catch invalid variables such as "=" or "=A"
if data[0] == "" {
if key == "" {
return fmt.Errorf("invalid variable: %q", line)
}
// trim the front of a variable, but nothing else
name := strings.TrimLeft(data[0], whiteSpaces)
if len(data) > 1 {
env[name] = data[1]
name := strings.TrimLeft(key, whiteSpaces)
if hasVal {
env[name] = val
} else {
if strings.HasSuffix(name, "*") {
name = strings.TrimSuffix(name, "*")
if name, hasStar := strings.CutSuffix(name, "*"); hasStar {
for _, e := range os.Environ() {
part := strings.SplitN(e, "=", 2)
if len(part) < 2 {
envKey, envVal, hasEq := strings.Cut(e, "=")
if !hasEq {
continue
}
if strings.HasPrefix(part[0], name) {
env[part[0]] = part[1]
if strings.HasPrefix(envKey, name) {
env[envKey] = envVal
}
}
} else if val, ok := os.LookupEnv(name); ok {