use strings.SplitSeq where possible

Signed-off-by: Paul Holzinger <pholzing@redhat.com>
This commit is contained in:
Paul Holzinger
2025-09-08 18:14:37 +02:00
parent 4e3e9bfb70
commit b97525a78d
21 changed files with 23 additions and 33 deletions

View File

@ -125,8 +125,7 @@ func port(_ *cobra.Command, args []string) error {
if hostIP == "" { if hostIP == "" {
hostIP = "0.0.0.0" hostIP = "0.0.0.0"
} }
protocols := strings.Split(v.Protocol, ",") for protocol := range strings.SplitSeq(v.Protocol, ",") {
for _, protocol := range protocols {
// If not searching by port or port/proto, then dump what we see // If not searching by port or port/proto, then dump what we see
if port == "" { if port == "" {
for i := uint16(0); i < v.Range; i++ { for i := uint16(0); i < v.Range; i++ {

View File

@ -39,8 +39,7 @@ func ValidateExtraHost(val string) (string, error) {
} }
// Split the hostnames by semicolon and validate each one // Split the hostnames by semicolon and validate each one
nameList := strings.Split(names, ";") for name := range strings.SplitSeq(names, ";") {
for _, name := range nameList {
if len(name) == 0 { if len(name) == 0 {
return "", fmt.Errorf("hostname in add-host %q is empty", val) return "", fmt.Errorf("hostname in add-host %q is empty", val)
} }

View File

@ -294,8 +294,7 @@ func handler(ctx context.Context, conn io.Reader, pm rkport.Manager) error {
func exposePorts(pm rkport.Manager, portMappings []types.PortMapping, childIP string) error { func exposePorts(pm rkport.Manager, portMappings []types.PortMapping, childIP string) error {
ctx := context.TODO() ctx := context.TODO()
for _, port := range portMappings { for _, port := range portMappings {
protocols := strings.Split(port.Protocol, ",") for protocol := range strings.SplitSeq(port.Protocol, ",") {
for _, protocol := range protocols {
hostIP := port.HostIP hostIP := port.HostIP
if hostIP == "" { if hostIP == "" {
hostIP = "0.0.0.0" hostIP = "0.0.0.0"

View File

@ -96,7 +96,7 @@ func addPathToRegistry(dir string) error {
} }
// Is this directory already on the windows path? // Is this directory already on the windows path?
for _, element := range strings.Split(existing, ";") { for element := range strings.SplitSeq(existing, ";") {
if strings.EqualFold(element, dir) { if strings.EqualFold(element, dir) {
// Path already added // Path already added
return nil return nil
@ -147,7 +147,7 @@ func removePathFromRegistry(path string) error {
// No point preallocating we can't know how big the array needs to be. // No point preallocating we can't know how big the array needs to be.
//nolint:prealloc //nolint:prealloc
var elements []string var elements []string
for _, element := range strings.Split(existing, ";") { for element := range strings.SplitSeq(existing, ";") {
if strings.EqualFold(element, path) { if strings.EqualFold(element, path) {
continue continue
} }

View File

@ -72,7 +72,7 @@ func StartWithOptions(options *Options) (*Registry, error) {
// Parse the output. // Parse the output.
registry := Registry{} registry := Registry{}
for _, s := range strings.Split(out, "\n") { for s := range strings.SplitSeq(out, "\n") {
if s == "" { if s == "" {
continue continue
} }

View File

@ -201,7 +201,7 @@ func (c *Container) Top(descriptors []string) ([]string, error) {
// Also support comma-separated input. // Also support comma-separated input.
psgoDescriptors := []string{} psgoDescriptors := []string{}
for _, d := range descriptors { for _, d := range descriptors {
for _, s := range strings.Split(d, ",") { for s := range strings.SplitSeq(d, ",") {
if s != "" { if s != "" {
psgoDescriptors = append(psgoDescriptors, s) psgoDescriptors = append(psgoDescriptors, s)
} }

View File

@ -1084,8 +1084,7 @@ func containerToV1Container(ctx context.Context, c *Container, getService bool)
func portMappingToContainerPort(portMappings []types.PortMapping, getService bool) ([]v1.ContainerPort, error) { func portMappingToContainerPort(portMappings []types.PortMapping, getService bool) ([]v1.ContainerPort, error) {
containerPorts := make([]v1.ContainerPort, 0, len(portMappings)) containerPorts := make([]v1.ContainerPort, 0, len(portMappings))
for _, p := range portMappings { for _, p := range portMappings {
protocols := strings.Split(p.Protocol, ",") for proto := range strings.SplitSeq(p.Protocol, ",") {
for _, proto := range protocols {
var protocol v1.Protocol var protocol v1.Protocol
switch strings.ToUpper(proto) { switch strings.ToUpper(proto) {
case "TCP": case "TCP":
@ -1360,7 +1359,7 @@ func generateKubeSecurityContext(c *Container) (*v1.SecurityContext, bool, error
} }
var selinuxOpts v1.SELinuxOptions var selinuxOpts v1.SELinuxOptions
selinuxHasData := false selinuxHasData := false
for _, label := range strings.Split(c.config.Spec.Annotations[define.InspectAnnotationLabel], ",label=") { for label := range strings.SplitSeq(c.config.Spec.Annotations[define.InspectAnnotationLabel], ",label=") {
opt, val, hasVal := strings.Cut(label, ":") opt, val, hasVal := strings.Cut(label, ":")
if hasVal { if hasVal {
switch opt { switch opt {

View File

@ -363,8 +363,7 @@ func (r *ConmonOCIRuntime) StopContainer(ctr *Container, timeout uint, all bool)
// Before handling error from KillContainer, convert STDERR to a []string // Before handling error from KillContainer, convert STDERR to a []string
// (one string per line of output) and print it. // (one string per line of output) and print it.
stderrLines := strings.Split(stderr.String(), "\n") for line := range strings.SplitSeq(stderr.String(), "\n") {
for _, line := range stderrLines {
if line != "" { if line != "" {
fmt.Fprintf(os.Stderr, "%s\n", line) fmt.Fprintf(os.Stderr, "%s\n", line)
} }

View File

@ -81,7 +81,7 @@ func (r *ConmonOCIRuntime) createRootlessContainer(ctr *Container, restoreOption
for dir := filepath.Dir(rootPath); ; dir = filepath.Dir(dir) { for dir := filepath.Dir(rootPath); ; dir = filepath.Dir(dir) {
if m, found := byMountpoint[dir]; found { if m, found := byMountpoint[dir]; found {
parentMount = dir parentMount = dir
for _, o := range strings.Split(m.Optional, ",") { for o := range strings.SplitSeq(m.Optional, ",") {
opt := strings.Split(o, ":") opt := strings.Split(o, ":")
if opt[0] == "shared" { if opt[0] == "shared" {
isShared = true isShared = true

View File

@ -205,8 +205,7 @@ func writeHijackHeader(r *http.Request, conn io.Writer, tty bool) {
func makeInspectPortBindings(bindings []types.PortMapping) map[string][]define.InspectHostPort { func makeInspectPortBindings(bindings []types.PortMapping) map[string][]define.InspectHostPort {
portBindings := make(map[string][]define.InspectHostPort) portBindings := make(map[string][]define.InspectHostPort)
for _, port := range bindings { for _, port := range bindings {
protocols := strings.Split(port.Protocol, ",") for protocol := range strings.SplitSeq(port.Protocol, ",") {
for _, protocol := range protocols {
for i := uint16(0); i < port.Range; i++ { for i := uint16(0); i < port.Range; i++ {
key := fmt.Sprintf("%d/%s", port.ContainerPort+i, protocol) key := fmt.Sprintf("%d/%s", port.ContainerPort+i, protocol)
hostPorts := portBindings[key] hostPorts := portBindings[key]

View File

@ -24,9 +24,8 @@ func VolumeOptions(opts map[string]string) ([]libpod.VolumeCreateOption, error)
case "o": case "o":
// o has special handling to parse out UID, GID. // o has special handling to parse out UID, GID.
// These are separate Libpod options. // These are separate Libpod options.
splitVal := strings.Split(value, ",")
finalVal := []string{} finalVal := []string{}
for _, o := range splitVal { for o := range strings.SplitSeq(value, ",") {
// Options will be formatted as either "opt" or // Options will be formatted as either "opt" or
// "opt=value" // "opt=value"
opt, val, hasVal := strings.Cut(o, "=") opt, val, hasVal := strings.Cut(o, "=")

View File

@ -135,7 +135,7 @@ func (ic *ContainerEngine) prepareAutomountImages(ctx context.Context, forContai
return nil, nil return nil, nil
} }
for _, imageName := range strings.Split(automount, ";") { for imageName := range strings.SplitSeq(automount, ";") {
img, fullName, err := ic.Libpod.LibimageRuntime().LookupImage(imageName, nil) img, fullName, err := ic.Libpod.LibimageRuntime().LookupImage(imageName, nil)
if err != nil { if err != nil {
return nil, fmt.Errorf("image %s from container %s does not exist in local storage, cannot automount: %w", imageName, forContainer, err) return nil, fmt.Errorf("image %s from container %s does not exist in local storage, cannot automount: %w", imageName, forContainer, err)

View File

@ -75,7 +75,7 @@ func (ms *machineSession) Bytes() []byte {
func (ms *machineSession) outputToStringSlice() []string { func (ms *machineSession) outputToStringSlice() []string {
var results []string var results []string
output := string(ms.Out.Contents()) output := string(ms.Out.Contents())
for _, line := range strings.Split(output, "\n") { for line := range strings.SplitSeq(output, "\n") {
if line != "" { if line != "" {
results = append(results, line) results = append(results, line)
} }

View File

@ -71,7 +71,7 @@ func (n UsernsMode) GetKeepIDOptions() (*KeepIDUserNsOptions, error) {
if !hasOpts { if !hasOpts {
return &options, nil return &options, nil
} }
for _, o := range strings.Split(nsopts, ",") { for o := range strings.SplitSeq(nsopts, ",") {
opt, val, hasVal := strings.Cut(o, "=") opt, val, hasVal := strings.Cut(o, "=")
if !hasVal { if !hasVal {
return nil, fmt.Errorf("invalid option specified: %q", o) return nil, fmt.Errorf("invalid option specified: %q", o)

View File

@ -26,9 +26,8 @@ func GetRacct(filter string) (map[string]uint64, error) {
return nil, fmt.Errorf("error calling rctl_get_racct with filter %s: %v", filter, errno) return nil, fmt.Errorf("error calling rctl_get_racct with filter %s: %v", filter, errno)
} }
len := bytes.IndexByte(buf[:], byte(0)) len := bytes.IndexByte(buf[:], byte(0))
entries := strings.Split(string(buf[:len]), ",")
res := make(map[string]uint64) res := make(map[string]uint64)
for _, entry := range entries { for entry := range strings.SplitSeq(string(buf[:len]), ",") {
key, valstr, _ := strings.Cut(entry, "=") key, valstr, _ := strings.Cut(entry, "=")
val, err := strconv.ParseUint(valstr, 10, 0) val, err := strconv.ParseUint(valstr, 10, 0)
if err != nil { if err != nil {

View File

@ -230,7 +230,7 @@ func becomeRootInUserNS(pausePid string) (_ bool, _ int, retErr error) {
for _, m := range mounts { for _, m := range mounts {
if m.Mountpoint == "/" { if m.Mountpoint == "/" {
isShared := false isShared := false
for _, o := range strings.Split(m.Optional, ",") { for o := range strings.SplitSeq(m.Optional, ",") {
if strings.HasPrefix(o, "shared:") { if strings.HasPrefix(o, "shared:") {
isShared = true isShared = true
break break

View File

@ -293,8 +293,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener
ulimitVal, ok := opts.Annotations[define.UlimitAnnotation] ulimitVal, ok := opts.Annotations[define.UlimitAnnotation]
if ok { if ok {
ulimits := strings.Split(ulimitVal, ",") for ul := range strings.SplitSeq(ulimitVal, ",") {
for _, ul := range ulimits {
parsed, err := units.ParseUlimit(ul) parsed, err := units.ParseUlimit(ul)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -378,9 +378,8 @@ func createPortMappings(s *specgen.SpecGenerator, imageData *libimage.ImageData)
// Check a string to ensure it is a comma-separated set of valid protocols // Check a string to ensure it is a comma-separated set of valid protocols
func checkProtocol(protocol string) ([]string, error) { func checkProtocol(protocol string) ([]string, error) {
protocols := make(map[string]struct{}) protocols := make(map[string]struct{})
splitProto := strings.Split(protocol, ",")
// Don't error on duplicates - just deduplicate // Don't error on duplicates - just deduplicate
for _, p := range splitProto { for p := range strings.SplitSeq(protocol, ",") {
p = strings.ToLower(p) p = strings.ToLower(p)
switch p { switch p {
case protoTCP, "": case protoTCP, "":

View File

@ -1263,7 +1263,7 @@ func parseLinuxResourcesDeviceAccess(device string) (specs.LinuxDeviceCgroup, er
minor = &m minor = &m
} }
access = value[2] access = value[2]
for _, c := range strings.Split(access, "") { for c := range strings.SplitSeq(access, "") {
if !cgroupDeviceAccess[c] { if !cgroupDeviceAccess[c] {
return specs.LinuxDeviceCgroup{}, fmt.Errorf("invalid device access in device-access-add: %s", c) return specs.LinuxDeviceCgroup{}, fmt.Errorf("invalid device access in device-access-add: %s", c)
} }

View File

@ -145,7 +145,7 @@ func (p *NotifyProxy) listen() {
sBuilder.Write(buffer[:n]) sBuilder.Write(buffer[:n])
var isBarrier, isReady bool var isBarrier, isReady bool
for _, line := range strings.Split(sBuilder.String(), "\n") { for line := range strings.SplitSeq(sBuilder.String(), "\n") {
switch line { switch line {
case _notifyRdyMsg: case _notifyRdyMsg:
isReady = true isReady = true

View File

@ -288,7 +288,7 @@ func (s *PodmanSession) OutputToString() string {
func (s *PodmanSession) OutputToStringArray() []string { func (s *PodmanSession) OutputToStringArray() []string {
var results []string var results []string
output := string(s.Out.Contents()) output := string(s.Out.Contents())
for _, line := range strings.Split(output, "\n") { for line := range strings.SplitSeq(output, "\n") {
if line != "" { if line != "" {
results = append(results, line) results = append(results, line)
} }