Skip to content

Commit

Permalink
Replace strings.SplitN with strings.Cut
Browse files Browse the repository at this point in the history
Cut is a cleaner & more performant api relative to SplitN(_, _, 2) added in go 1.18

Previously applied this refactoring to buildah:
containers/buildah#5239

Signed-off-by: Philip Dubé <[email protected]>
  • Loading branch information
serprex committed Jan 11, 2024
1 parent f1ea4fb commit 522934d
Show file tree
Hide file tree
Showing 56 changed files with 597 additions and 679 deletions.
22 changes: 11 additions & 11 deletions cmd/podman/common/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,15 +333,15 @@ func buildFlagsWrapperToOptions(c *cobra.Command, contextDir string, flags *Buil
}
if c.Flag("build-arg").Changed {
for _, arg := range flags.BuildArg {
av := strings.SplitN(arg, "=", 2)
if len(av) > 1 {
args[av[0]] = av[1]
key, val, hasVal := strings.Cut(arg, "=")
if hasVal {
args[key] = val
} else {
// check if the env is set in the local environment and use that value if it is
if val, present := os.LookupEnv(av[0]); present {
args[av[0]] = val
if val, present := os.LookupEnv(key); present {
args[key] = val
} else {
delete(args, av[0])
delete(args, key)
}
}
}
Expand Down Expand Up @@ -450,15 +450,15 @@ func buildFlagsWrapperToOptions(c *cobra.Command, contextDir string, flags *Buil
additionalBuildContext := make(map[string]*buildahDefine.AdditionalBuildContext)
if c.Flag("build-context").Changed {
for _, contextString := range flags.BuildContext {
av := strings.SplitN(contextString, "=", 2)
if len(av) > 1 {
parseAdditionalBuildContext, err := parse.GetAdditionalBuildContext(av[1])
key, val, hasVal := strings.Cut(contextString, "=")
if hasVal {
parseAdditionalBuildContext, err := parse.GetAdditionalBuildContext(val)
if err != nil {
return nil, fmt.Errorf("while parsing additional build context: %w", err)
}
additionalBuildContext[av[0]] = &parseAdditionalBuildContext
additionalBuildContext[key] = &parseAdditionalBuildContext
} else {
return nil, fmt.Errorf("while parsing additional build context: %q, accepts value in the form of key=value", av)
return nil, fmt.Errorf("while parsing additional build context: %s, accepts value in the form of key=value", contextString)
}
}
}
Expand Down
22 changes: 11 additions & 11 deletions cmd/podman/common/completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -423,9 +423,9 @@ func prefixSlice(pre string, slice []string) []string {

func suffixCompSlice(suf string, slice []string) []string {
for i := range slice {
split := strings.SplitN(slice[i], "\t", 2)
if len(split) > 1 {
slice[i] = split[0] + suf + "\t" + split[1]
key, val, hasVal := strings.Cut(slice[i], "\t")
if hasVal {
slice[i] = key + suf + "\t" + val
} else {
slice[i] += suf
}
Expand Down Expand Up @@ -878,10 +878,10 @@ func AutocompleteScp(cmd *cobra.Command, args []string, toComplete string) ([]st
}
switch len(args) {
case 0:
split := strings.SplitN(toComplete, "::", 2)
if len(split) > 1 {
imageSuggestions, _ := getImages(cmd, split[1])
return prefixSlice(split[0]+"::", imageSuggestions), cobra.ShellCompDirectiveNoFileComp
prefix, imagesToComplete, isImages := strings.Cut(toComplete, "::")
if isImages {
imageSuggestions, _ := getImages(cmd, imagesToComplete)
return prefixSlice(prefix+"::", imageSuggestions), cobra.ShellCompDirectiveNoFileComp
}
connectionSuggestions, _ := AutocompleteSystemConnections(cmd, args, toComplete)
imageSuggestions, _ := getImages(cmd, toComplete)
Expand All @@ -893,9 +893,9 @@ func AutocompleteScp(cmd *cobra.Command, args []string, toComplete string) ([]st
}
return totalSuggestions, directive
case 1:
split := strings.SplitN(args[0], "::", 2)
if len(split) > 1 {
if len(split[1]) > 0 {
_, imagesToComplete, isImages := strings.Cut(args[0], "::")
if isImages {
if len(imagesToComplete) > 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
imageSuggestions, _ := getImages(cmd, toComplete)
Expand Down Expand Up @@ -1076,7 +1076,7 @@ func AutocompleteUserFlag(cmd *cobra.Command, args []string, toComplete string)

var groups []string
scanner := bufio.NewScanner(file)
user := strings.SplitN(toComplete, ":", 2)[0]
user, _, _ := strings.Cut(toComplete, ":")
for scanner.Scan() {
entries := strings.SplitN(scanner.Text(), ":", 4)
groups = append(groups, user+":"+entries[0])
Expand Down
8 changes: 4 additions & 4 deletions cmd/podman/containers/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,10 +342,10 @@ func PullImage(imageName string, cliVals *entities.ContainerCreateOptions) (stri
if cliVals.Arch != "" || cliVals.OS != "" {
return "", errors.New("--platform option can not be specified with --arch or --os")
}
split := strings.SplitN(cliVals.Platform, "/", 2)
cliVals.OS = split[0]
if len(split) > 1 {
cliVals.Arch = split[1]
OS, Arch, hasArch := strings.Cut(cliVals.Platform, "/")
cliVals.OS = OS
if hasArch {
cliVals.Arch = Arch
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions cmd/podman/containers/pause.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,11 @@ func pause(cmd *cobra.Command, args []string) error {
}

for _, f := range filters {
split := strings.SplitN(f, "=", 2)
if len(split) < 2 {
fname, filter, hasFilter := strings.Cut(f, "=")
if !hasFilter {
return fmt.Errorf("invalid filter %q", f)
}
pauseOpts.Filters[split[0]] = append(pauseOpts.Filters[split[0]], split[1])
pauseOpts.Filters[fname] = append(pauseOpts.Filters[fname], filter)
}

responses, err := registry.ContainerEngine().ContainerPause(context.Background(), args, pauseOpts)
Expand Down
6 changes: 3 additions & 3 deletions cmd/podman/containers/ps.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,11 +195,11 @@ func ps(cmd *cobra.Command, _ []string) error {
}

for _, f := range filters {
split := strings.SplitN(f, "=", 2)
if len(split) == 1 {
fname, filter, hasFilter := strings.Cut(f, "=")
if !hasFilter {
return fmt.Errorf("invalid filter %q", f)
}
listOpts.Filters[split[0]] = append(listOpts.Filters[split[0]], split[1])
listOpts.Filters[fname] = append(listOpts.Filters[fname], filter)
}
listContainers, err := getResponses()
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions cmd/podman/containers/restart.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ func restart(cmd *cobra.Command, args []string) error {
}

for _, f := range filters {
split := strings.SplitN(f, "=", 2)
if len(split) < 2 {
fname, filter, hasFilter := strings.Cut(f, "=")
if !hasFilter {
return fmt.Errorf("invalid filter %q", f)
}
restartOpts.Filters[split[0]] = append(restartOpts.Filters[split[0]], split[1])
restartOpts.Filters[fname] = append(restartOpts.Filters[fname], filter)
}

responses, err := registry.ContainerEngine().ContainerRestart(context.Background(), args, restartOpts)
Expand Down
8 changes: 4 additions & 4 deletions cmd/podman/containers/rm.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,16 +116,16 @@ func rm(cmd *cobra.Command, args []string) error {
}
return fmt.Errorf("reading CIDFile: %w", err)
}
id := strings.Split(string(content), "\n")[0]
id, _, _ := strings.Cut(string(content), "\n")
args = append(args, id)
}

for _, f := range filters {
split := strings.SplitN(f, "=", 2)
if len(split) < 2 {
fname, filter, hasFilter := strings.Cut(f, "=")
if !hasFilter {
return fmt.Errorf("invalid filter %q", f)
}
rmOptions.Filters[split[0]] = append(rmOptions.Filters[split[0]], split[1])
rmOptions.Filters[fname] = append(rmOptions.Filters[fname], filter)
}

if rmOptions.All {
Expand Down
6 changes: 3 additions & 3 deletions cmd/podman/containers/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,11 @@ func start(cmd *cobra.Command, args []string) error {

containers := utils.RemoveSlash(args)
for _, f := range filters {
split := strings.SplitN(f, "=", 2)
if len(split) < 2 {
fname, filter, hasFilter := strings.Cut(f, "=")
if !hasFilter {
return fmt.Errorf("invalid filter %q", f)
}
startOptions.Filters[split[0]] = append(startOptions.Filters[split[0]], split[1])
startOptions.Filters[fname] = append(startOptions.Filters[fname], filter)
}

responses, err := registry.ContainerEngine().ContainerStart(registry.GetContext(), containers, startOptions)
Expand Down
6 changes: 3 additions & 3 deletions cmd/podman/containers/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,11 +119,11 @@ func stop(cmd *cobra.Command, args []string) error {
}

for _, f := range filters {
split := strings.SplitN(f, "=", 2)
if len(split) < 2 {
fname, filter, hasFilter := strings.Cut(f, "=")
if !hasFilter {
return fmt.Errorf("invalid filter %q", f)
}
stopOptions.Filters[split[0]] = append(stopOptions.Filters[split[0]], split[1])
stopOptions.Filters[fname] = append(stopOptions.Filters[fname], filter)
}

responses, err := registry.ContainerEngine().ContainerStop(context.Background(), args, stopOptions)
Expand Down
6 changes: 3 additions & 3 deletions cmd/podman/containers/unpause.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,11 @@ func unpause(cmd *cobra.Command, args []string) error {
}

for _, f := range filters {
split := strings.SplitN(f, "=", 2)
if len(split) < 2 {
fname, filter, hasFilter := strings.Cut(f, "=")
if !hasFilter {
return fmt.Errorf("invalid filter %q", f)
}
unpauseOpts.Filters[split[0]] = append(unpauseOpts.Filters[split[0]], split[1])
unpauseOpts.Filters[fname] = append(unpauseOpts.Filters[fname], filter)
}

responses, err := registry.ContainerEngine().ContainerUnpause(context.Background(), args, unpauseOpts)
Expand Down
12 changes: 8 additions & 4 deletions cmd/podman/images/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,14 @@ func imagePull(cmd *cobra.Command, args []string) error {
if pullOptions.Arch != "" || pullOptions.OS != "" {
return errors.New("--platform option can not be specified with --arch or --os")
}
split := strings.SplitN(platform, "/", 2)
pullOptions.OS = split[0]
if len(split) > 1 {
pullOptions.Arch = split[1]

specs := strings.Split(platform, "/")
pullOptions.OS = specs[0] // may be empty
if len(specs) > 1 {
pullOptions.Arch = specs[1]
if len(specs) > 2 {
pullOptions.Variant = specs[2]
}
}
}

Expand Down
11 changes: 5 additions & 6 deletions cmd/podman/kube/play.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,18 +246,17 @@ func play(cmd *cobra.Command, args []string) error {
}

for _, annotation := range playOptions.annotations {
splitN := strings.SplitN(annotation, "=", 2)
if len(splitN) != 2 {
key, val, hasVal := strings.Cut(annotation, "=")
if !hasVal {
return fmt.Errorf("annotation %q must include an '=' sign", annotation)
}
if playOptions.Annotations == nil {
playOptions.Annotations = make(map[string]string)
}
annotation := splitN[1]
if len(annotation) > define.MaxKubeAnnotation && !playOptions.UseLongAnnotations {
return fmt.Errorf("annotation exceeds maximum size, %d, of kubernetes annotation: %s", define.MaxKubeAnnotation, annotation)
if len(val) > define.MaxKubeAnnotation && !playOptions.UseLongAnnotations {
return fmt.Errorf("annotation exceeds maximum size, %d, of kubernetes annotation: %s", define.MaxKubeAnnotation, val)
}
playOptions.Annotations[splitN[0]] = annotation
playOptions.Annotations[key] = val
}

for _, mac := range playOptions.macs {
Expand Down
12 changes: 6 additions & 6 deletions cmd/podman/networks/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,16 +245,16 @@ func parseRoute(routeStr string) (*types.Route, error) {
}

func parseRange(iprange string) (*types.LeaseRange, error) {
split := strings.SplitN(iprange, "-", 2)
if len(split) > 1 {
startIPString, endIPString, hasDash := strings.Cut(iprange, "-")
if hasDash {
// range contains dash so assume form is start-end
start := net.ParseIP(split[0])
start := net.ParseIP(startIPString)
if start == nil {
return nil, fmt.Errorf("range start ip %q is not a ip address", split[0])
return nil, fmt.Errorf("range start ip %q is not a ip address", startIPString)
}
end := net.ParseIP(split[1])
end := net.ParseIP(endIPString)
if end == nil {
return nil, fmt.Errorf("range end ip %q is not a ip address", split[1])
return nil, fmt.Errorf("range end ip %q is not a ip address", endIPString)
}
return &types.LeaseRange{
StartIP: start,
Expand Down
6 changes: 3 additions & 3 deletions cmd/podman/parse/filters.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import (
func FilterArgumentsIntoFilters(filters []string) (url.Values, error) {
parsedFilters := make(url.Values)
for _, f := range filters {
t := strings.SplitN(f, "=", 2)
if len(t) < 2 {
fname, filter, hasFilter := strings.Cut(f, "=")
if !hasFilter {
return parsedFilters, fmt.Errorf("filter input must be in the form of filter=value: %s is invalid", f)
}
parsedFilters.Add(t[0], t[1])
parsedFilters.Add(fname, filter)
}
return parsedFilters, nil
}
42 changes: 17 additions & 25 deletions cmd/podman/parse/net.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@ var (
// for add-host flag
func ValidateExtraHost(val string) (string, error) {
// allow for IPv6 addresses in extra hosts by only splitting on first ":"
arr := strings.SplitN(val, ":", 2)
if len(arr) != 2 || len(arr[0]) == 0 {
name, ip, hasIP := strings.Cut(val, ":")
if !hasIP || len(name) == 0 {
return "", fmt.Errorf("bad format for add-host: %q", val)
}
if arr[1] == etchosts.HostGateway {
if ip == etchosts.HostGateway {
return val, nil
}
if _, err := validateIPAddress(arr[1]); err != nil {
return "", fmt.Errorf("invalid IP address in add-host: %q", arr[1])
if _, err := validateIPAddress(ip); err != nil {
return "", fmt.Errorf("invalid IP address in add-host: %q", ip)
}
return val, nil
}
Expand Down Expand Up @@ -82,45 +82,37 @@ func GetAllLabels(labelFile, inputLabels []string) (map[string]string, error) {
}
}
for _, label := range inputLabels {
split := strings.SplitN(label, "=", 2)
if split[0] == "" {
key, value, _ := strings.Cut(label, "=")
if key == "" {
return nil, fmt.Errorf("invalid label format: %q", label)
}
value := ""
if len(split) > 1 {
value = split[1]
}
labels[split[0]] = value
labels[key] = value
}
return labels, nil
}

func parseEnvOrLabel(env map[string]string, line, configType 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 environment variable: %q", line)
}

// trim the front of a variable, but nothing else
name := strings.TrimLeft(data[0], whiteSpaces)
name := strings.TrimLeft(key, whiteSpaces)
if strings.ContainsAny(name, whiteSpaces) {
return fmt.Errorf("name %q has white spaces, poorly formatted name", name)
}

if len(data) > 1 {
env[name] = data[1]
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 {
continue
}
if strings.HasPrefix(part[0], name) {
env[part[0]] = part[1]
envKey, envVal, hasEq := strings.Cut(e, "=")
if hasEq && strings.HasPrefix(envKey, name) {
env[envKey] = envVal
}
}
} else if configType == ENVType {
Expand Down
6 changes: 3 additions & 3 deletions cmd/podman/pods/ps.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,11 @@ func pods(cmd *cobra.Command, _ []string) error {
if cmd.Flag("filter").Changed {
psInput.Filters = make(map[string][]string)
for _, f := range inputFilters {
split := strings.SplitN(f, "=", 2)
if len(split) < 2 {
fname, filter, hasFilter := strings.Cut(f, "=")
if !hasFilter {
return fmt.Errorf("filter input must be in the form of filter=value: %s is invalid", f)
}
psInput.Filters[split[0]] = append(psInput.Filters[split[0]], split[1])
psInput.Filters[fname] = append(psInput.Filters[fname], filter)
}
}
responses, err := registry.ContainerEngine().PodPs(context.Background(), psInput)
Expand Down
Loading

0 comments on commit 522934d

Please sign in to comment.