diff --git a/cli/compose/convert/service.go b/cli/compose/convert/service.go index e1ba6ffb99..7e0b8cfc99 100644 --- a/cli/compose/convert/service.go +++ b/cli/compose/convert/service.go @@ -427,11 +427,11 @@ func uint32Ptr(value uint32) *uint32 { // convertExtraHosts converts : mappings to SwarmKit notation: // "IP-address hostname(s)". The original order of mappings is preserved. func convertExtraHosts(extraHosts composetypes.HostsList) []string { - hosts := []string{} + hosts := make([]string, 0, len(extraHosts)) for _, hostIP := range extraHosts { - if v := strings.SplitN(hostIP, ":", 2); len(v) == 2 { + if hostName, ipAddr, ok := strings.Cut(hostIP, ":"); ok { // Convert to SwarmKit notation: IP-address hostname(s) - hosts = append(hosts, fmt.Sprintf("%s %s", v[1], v[0])) + hosts = append(hosts, ipAddr+" "+hostName) } } return hosts diff --git a/cli/compose/loader/loader.go b/cli/compose/loader/loader.go index 57a4bffc32..a9b8f1f1f9 100644 --- a/cli/compose/loader/loader.go +++ b/cli/compose/loader/loader.go @@ -829,21 +829,20 @@ func transformListOrMapping(listOrMapping interface{}, sep string, allowNil bool } func transformMappingOrList(mappingOrList interface{}, sep string, allowNil bool) interface{} { - switch value := mappingOrList.(type) { + switch values := mappingOrList.(type) { case map[string]interface{}: - return toMapStringString(value, allowNil) - case ([]interface{}): + return toMapStringString(values, allowNil) + case []interface{}: result := make(map[string]interface{}) - for _, value := range value { - parts := strings.SplitN(value.(string), sep, 2) - key := parts[0] + for _, v := range values { + key, val, hasValue := strings.Cut(v.(string), sep) switch { - case len(parts) == 1 && allowNil: + case !hasValue && allowNil: result[key] = nil - case len(parts) == 1 && !allowNil: + case !hasValue && !allowNil: result[key] = "" default: - result[key] = parts[1] + result[key] = val } } return result diff --git a/cli/compose/template/template.go b/cli/compose/template/template.go index 12927ddeda..f8e507a90b 100644 --- a/cli/compose/template/template.go +++ b/cli/compose/template/template.go @@ -239,9 +239,9 @@ func matchGroups(matches []string, pattern *regexp.Regexp) map[string]string { // // If the separator is not found, return the string itself, followed by an empty string. func partition(s, sep string) (string, string) { - if strings.Contains(s, sep) { - parts := strings.SplitN(s, sep, 2) - return parts[0], parts[1] + k, v, ok := strings.Cut(s, sep) + if !ok { + return s, "" } - return s, "" + return k, v }