From 8bdf77aa20175b53998ca8196cd49733d76ef029 Mon Sep 17 00:00:00 2001 From: Oleksandr Redko Date: Fri, 5 Jan 2024 14:48:12 +0200 Subject: [PATCH] Refactor: replace StringInSlice with slices.Contains Signed-off-by: Oleksandr Redko --- cmd/podman/containers/create.go | 4 ++-- cmd/podman/farm/create.go | 4 ++-- cmd/podman/farm/update.go | 4 ++-- cmd/podman/images/save.go | 4 ++-- cmd/podman/images/trust_set.go | 4 ++-- cmd/podman/system/connection/list.go | 4 ++-- cmd/podman/system/connection/remove.go | 4 ++-- libpod/container_internal.go | 3 ++- libpod/container_internal_common.go | 6 +++--- libpod/container_top_linux.go | 4 ++-- libpod/kube.go | 18 +++++++++--------- libpod/networking_common.go | 4 ++-- libpod/runtime_ctr.go | 6 +++--- libpod/runtime_pod.go | 4 ++-- pkg/bindings/test/common_test.go | 11 ----------- pkg/bindings/test/networks_test.go | 3 ++- pkg/bindings/test/pods_test.go | 11 ++++++----- pkg/bindings/test/volumes_test.go | 3 ++- pkg/domain/filters/containers.go | 3 ++- pkg/domain/filters/pods.go | 7 ++++--- pkg/domain/infra/abi/images_list.go | 4 ++-- pkg/domain/infra/abi/network.go | 6 +++--- pkg/machine/e2e/config_test.go | 4 ++-- pkg/machine/e2e/list_test.go | 8 ++++---- pkg/specgen/container_validate.go | 6 +++--- pkg/specgen/generate/kube/kube.go | 3 +-- pkg/specgen/generate/ports.go | 7 +++---- pkg/specgen/generate/security_linux.go | 6 +++--- pkg/specgen/namespaces.go | 6 +++--- pkg/util/utils.go | 17 ----------------- pkg/util/utils_test.go | 13 ------------- test/e2e/common_test.go | 4 ++-- test/utils/common_function_test.go | 7 ------- test/utils/utils.go | 10 ---------- 34 files changed, 79 insertions(+), 133 deletions(-) diff --git a/cmd/podman/containers/create.go b/cmd/podman/containers/create.go index 6d97ea7d65..b48b096878 100644 --- a/cmd/podman/containers/create.go +++ b/cmd/podman/containers/create.go @@ -11,7 +11,6 @@ import ( "github.com/containers/buildah/pkg/cli" "github.com/containers/common/pkg/auth" "github.com/containers/common/pkg/config" - cutil "github.com/containers/common/pkg/util" "github.com/containers/image/v5/transports/alltransports" "github.com/containers/image/v5/types" "github.com/containers/podman/v4/cmd/podman/common" @@ -24,6 +23,7 @@ import ( "github.com/containers/podman/v4/pkg/util" "github.com/sirupsen/logrus" "github.com/spf13/cobra" + "golang.org/x/exp/slices" "golang.org/x/term" ) @@ -134,7 +134,7 @@ func create(cmd *cobra.Command, args []string) error { if !cmd.Flags().Changed("pod") { return errors.New("must specify pod value with init-ctr") } - if !cutil.StringInSlice(initctr, []string{define.AlwaysInitContainer, define.OneShotInitContainer}) { + if !slices.Contains([]string{define.AlwaysInitContainer, define.OneShotInitContainer}, initctr) { return fmt.Errorf("init-ctr value must be '%s' or '%s'", define.AlwaysInitContainer, define.OneShotInitContainer) } cliVals.InitContainerType = initctr diff --git a/cmd/podman/farm/create.go b/cmd/podman/farm/create.go index b9986b8118..8f10e2bb63 100644 --- a/cmd/podman/farm/create.go +++ b/cmd/podman/farm/create.go @@ -6,8 +6,8 @@ import ( "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/config" "github.com/containers/podman/v4/cmd/podman/registry" - "github.com/containers/podman/v4/pkg/util" "github.com/spf13/cobra" + "golang.org/x/exp/slices" ) var ( @@ -55,7 +55,7 @@ func create(cmd *cobra.Command, args []string) error { for _, c := range connections { if _, ok := cfg.Engine.ServiceDestinations[c]; ok { - if util.StringInSlice(c, cfg.Farms.List[farmName]) { + if slices.Contains(cfg.Farms.List[farmName], c) { // Don't add duplicate connections to a farm continue } diff --git a/cmd/podman/farm/update.go b/cmd/podman/farm/update.go index 0bfa8081d8..55c6a8d998 100644 --- a/cmd/podman/farm/update.go +++ b/cmd/podman/farm/update.go @@ -8,8 +8,8 @@ import ( "github.com/containers/common/pkg/config" "github.com/containers/podman/v4/cmd/podman/common" "github.com/containers/podman/v4/cmd/podman/registry" - "github.com/containers/podman/v4/pkg/util" "github.com/spf13/cobra" + "golang.org/x/exp/slices" ) var ( @@ -91,7 +91,7 @@ func farmUpdate(cmd *cobra.Command, args []string) error { for _, cRemove := range updateOpts.Remove { connections := cfg.Farms.List[farmName] - if util.StringInSlice(cRemove, connections) { + if slices.Contains(connections, cRemove) { delete(cMap, cRemove) } else { return fmt.Errorf("cannot remove from farm, %q is not a connection in the farm", cRemove) diff --git a/cmd/podman/images/save.go b/cmd/podman/images/save.go index 46376c2a14..1c6dbd5229 100644 --- a/cmd/podman/images/save.go +++ b/cmd/podman/images/save.go @@ -8,13 +8,13 @@ import ( "strings" "github.com/containers/common/pkg/completion" - "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/cmd/podman/common" "github.com/containers/podman/v4/cmd/podman/parse" "github.com/containers/podman/v4/cmd/podman/registry" "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/pkg/domain/entities" "github.com/spf13/cobra" + "golang.org/x/exp/slices" "golang.org/x/term" ) @@ -38,7 +38,7 @@ var ( if err != nil { return err } - if !util.StringInSlice(format, common.ValidSaveFormats) { + if !slices.Contains(common.ValidSaveFormats, format) { return fmt.Errorf("format value must be one of %s", strings.Join(common.ValidSaveFormats, " ")) } return nil diff --git a/cmd/podman/images/trust_set.go b/cmd/podman/images/trust_set.go index 2ed91d9c46..cd88514fee 100644 --- a/cmd/podman/images/trust_set.go +++ b/cmd/podman/images/trust_set.go @@ -6,11 +6,11 @@ import ( "regexp" "github.com/containers/common/pkg/completion" - "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/cmd/podman/common" "github.com/containers/podman/v4/cmd/podman/registry" "github.com/containers/podman/v4/pkg/domain/entities" "github.com/spf13/cobra" + "golang.org/x/exp/slices" ) var ( @@ -60,7 +60,7 @@ func setTrust(cmd *cobra.Command, args []string) error { return err } - if !util.StringInSlice(setOptions.Type, validTrustTypes) { + if !slices.Contains(validTrustTypes, setOptions.Type) { return fmt.Errorf("invalid choice: %s (choose from 'accept', 'reject', 'signedBy', 'sigstoreSigned')", setOptions.Type) } return registry.ImageEngine().SetTrust(registry.Context(), args, setOptions) diff --git a/cmd/podman/system/connection/list.go b/cmd/podman/system/connection/list.go index 3c1a424537..ea6f822a9d 100644 --- a/cmd/podman/system/connection/list.go +++ b/cmd/podman/system/connection/list.go @@ -8,12 +8,12 @@ import ( "github.com/containers/common/pkg/completion" "github.com/containers/common/pkg/config" "github.com/containers/common/pkg/report" - "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/cmd/podman/common" "github.com/containers/podman/v4/cmd/podman/registry" "github.com/containers/podman/v4/cmd/podman/system" "github.com/containers/podman/v4/cmd/podman/validate" "github.com/spf13/cobra" + "golang.org/x/exp/slices" ) var ( @@ -89,7 +89,7 @@ func inspect(cmd *cobra.Command, args []string) error { } rows := make([]namedDestination, 0) for k, v := range cfg.Engine.ServiceDestinations { - if args != nil && !util.StringInSlice(k, args) { + if args != nil && !slices.Contains(args, k) { continue } diff --git a/cmd/podman/system/connection/remove.go b/cmd/podman/system/connection/remove.go index 72b24c10a8..1e6ac183fa 100644 --- a/cmd/podman/system/connection/remove.go +++ b/cmd/podman/system/connection/remove.go @@ -7,8 +7,8 @@ import ( "github.com/containers/podman/v4/cmd/podman/common" "github.com/containers/podman/v4/cmd/podman/registry" "github.com/containers/podman/v4/cmd/podman/system" - "github.com/containers/podman/v4/pkg/util" "github.com/spf13/cobra" + "golang.org/x/exp/slices" ) var ( @@ -80,7 +80,7 @@ func rm(cmd *cobra.Command, args []string) error { // If there are existing farm, remove the deleted connection that might be part of a farm for k, v := range cfg.Farms.List { - index := util.IndexOfStringInSlice(args[0], v) + index := slices.Index(v, args[0]) if index > -1 { cfg.Farms.List[k] = append(v[:index], v[index+1:]...) } diff --git a/libpod/container_internal.go b/libpod/container_internal.go index 8e583de4c0..361a342f3f 100644 --- a/libpod/container_internal.go +++ b/libpod/container_internal.go @@ -47,6 +47,7 @@ import ( "github.com/opencontainers/runtime-tools/generate" "github.com/opencontainers/selinux/go-selinux/label" "github.com/sirupsen/logrus" + "golang.org/x/exp/slices" "golang.org/x/sys/unix" ) @@ -1794,7 +1795,7 @@ func (c *Container) mountNamedVolume(v *ContainerNamedVolume, mountpoint string) return nil, err } _, hasNoCopy := vol.config.Options["nocopy"] - if vol.state.NeedsCopyUp && !cutil.StringInSlice("nocopy", v.Options) && !hasNoCopy { + if vol.state.NeedsCopyUp && !slices.Contains(v.Options, "nocopy") && !hasNoCopy { logrus.Debugf("Copying up contents from container %s to volume %s", c.ID(), vol.Name()) srcDir, err := securejoin.SecureJoin(mountpoint, v.Dest) diff --git a/libpod/container_internal_common.go b/libpod/container_internal_common.go index 75660f7cbe..3d91f653bd 100644 --- a/libpod/container_internal_common.go +++ b/libpod/container_internal_common.go @@ -32,7 +32,6 @@ import ( "github.com/containers/common/pkg/config" "github.com/containers/common/pkg/subscriptions" "github.com/containers/common/pkg/umask" - cutil "github.com/containers/common/pkg/util" is "github.com/containers/image/v5/storage" "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/libpod/events" @@ -54,6 +53,7 @@ import ( "github.com/opencontainers/selinux/go-selinux" "github.com/opencontainers/selinux/go-selinux/label" "github.com/sirupsen/logrus" + "golang.org/x/exp/slices" "golang.org/x/sys/unix" cdi "tags.cncf.io/container-device-interface/pkg/cdi" ) @@ -193,7 +193,7 @@ func (c *Container) generateSpec(ctx context.Context) (s *spec.Spec, cleanupFunc overrides := c.getUserOverrides() execUser, err := lookup.GetUserGroupInfo(c.state.Mountpoint, c.config.User, overrides) if err != nil { - if cutil.StringInSlice(c.config.User, c.config.HostUsers) { + if slices.Contains(c.config.HostUsers, c.config.User) { execUser, err = lookupHostUser(c.config.User) } if err != nil { @@ -2495,7 +2495,7 @@ func (c *Container) setHomeEnvIfNeeded() error { overrides := c.getUserOverrides() execUser, err := lookup.GetUserGroupInfo(c.state.Mountpoint, c.config.User, overrides) if err != nil { - if cutil.StringInSlice(c.config.User, c.config.HostUsers) { + if slices.Contains(c.config.HostUsers, c.config.User) { execUser, err = lookupHostUser(c.config.User) } diff --git a/libpod/container_top_linux.go b/libpod/container_top_linux.go index d8591e98e2..7807eeff23 100644 --- a/libpod/container_top_linux.go +++ b/libpod/container_top_linux.go @@ -16,13 +16,13 @@ import ( "syscall" "unsafe" - "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/pkg/rootless" "github.com/containers/psgo" "github.com/containers/storage/pkg/reexec" "github.com/google/shlex" "github.com/sirupsen/logrus" + "golang.org/x/exp/slices" "golang.org/x/sys/unix" ) @@ -231,7 +231,7 @@ func (c *Container) Top(descriptors []string) ([]string, error) { // Only use ps(1) from the host when we know the container was not started with CAP_SYS_PTRACE, // with it the container can access /proc/$pid/ files and potentially escape the container fs. if c.config.Spec.Process.Capabilities != nil && - !util.StringInSlice("CAP_SYS_PTRACE", c.config.Spec.Process.Capabilities.Effective) { + !slices.Contains(c.config.Spec.Process.Capabilities.Effective, "CAP_SYS_PTRACE") { var retry bool output, retry, err = c.execPS(psDescriptors) if err != nil { diff --git a/libpod/kube.go b/libpod/kube.go index 104b9f1d5a..12895e4c30 100644 --- a/libpod/kube.go +++ b/libpod/kube.go @@ -17,7 +17,6 @@ import ( "github.com/containers/common/libnetwork/types" "github.com/containers/common/pkg/config" - cutil "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/pkg/annotations" "github.com/containers/podman/v4/pkg/domain/entities" @@ -32,6 +31,7 @@ import ( "github.com/containers/podman/v4/pkg/util" "github.com/opencontainers/runtime-spec/specs-go" "github.com/sirupsen/logrus" + "golang.org/x/exp/slices" ) // GenerateForKube takes a slice of libpod containers and generates @@ -729,7 +729,7 @@ func simplePodWithV1Containers(ctx context.Context, ctrs []*Container, getServic for _, ulimit := range ctr.config.Spec.Process.Rlimits { finalUlimit := strings.ToLower(strings.ReplaceAll(ulimit.Type, "RLIMIT_", "")) + "=" + strconv.Itoa(int(ulimit.Soft)) + ":" + strconv.Itoa(int(ulimit.Hard)) // compare ulimit with default list so we don't add it twice - if cutil.StringInSlice(finalUlimit, defaultUlimits) { + if slices.Contains(defaultUlimits, finalUlimit) { continue } @@ -768,7 +768,7 @@ func simplePodWithV1Containers(ctx context.Context, ctrs []*Container, getServic podDNS.Nameservers = make([]string, 0) } for _, s := range servers { - if !cutil.StringInSlice(s, podDNS.Nameservers) { // only append if it does not exist + if !slices.Contains(podDNS.Nameservers, s) { // only append if it does not exist podDNS.Nameservers = append(podDNS.Nameservers, s) } } @@ -779,7 +779,7 @@ func simplePodWithV1Containers(ctx context.Context, ctrs []*Container, getServic podDNS.Searches = make([]string, 0) } for _, d := range domains { - if !cutil.StringInSlice(d, podDNS.Searches) { // only append if it does not exist + if !slices.Contains(podDNS.Searches, d) { // only append if it does not exist podDNS.Searches = append(podDNS.Searches, d) } } @@ -796,7 +796,7 @@ func simplePodWithV1Containers(ctx context.Context, ctrs []*Container, getServic podName := removeUnderscores(ctrs[0].Name()) // Check if the pod name and container name will end up conflicting // Append -pod if so - if cutil.StringInSlice(podName, ctrNames) { + if slices.Contains(ctrNames, podName) { podName += "-pod" } @@ -1114,7 +1114,7 @@ func libpodMountsToKubeVolumeMounts(c *Container) ([]v1.VolumeMount, []v1.Volume // generateKubePersistentVolumeClaim converts a ContainerNamedVolume to a Kubernetes PersistentVolumeClaim func generateKubePersistentVolumeClaim(v *ContainerNamedVolume) (v1.VolumeMount, v1.Volume) { - ro := cutil.StringInSlice("ro", v.Options) + ro := slices.Contains(v.Options, "ro") // To avoid naming conflicts with any host path mounts, add a unique suffix to the volume's name. name := v.Name + "-pvc" @@ -1175,7 +1175,7 @@ func generateKubeVolumeMount(m specs.Mount) (v1.VolumeMount, v1.Volume, error) { } vm.Name = name vm.MountPath = m.Destination - if cutil.StringInSlice("ro", m.Options) { + if slices.Contains(m.Options, "ro") { vm.ReadOnly = true } @@ -1216,7 +1216,7 @@ func determineCapAddDropFromCapabilities(defaultCaps, containerCaps []string) *v // Find caps in the defaultCaps but not in the container's // those indicate a dropped cap for _, capability := range defaultCaps { - if !cutil.StringInSlice(capability, containerCaps) { + if !slices.Contains(containerCaps, capability) { if _, ok := dedupDrop[capability]; !ok { drop = append(drop, v1.Capability(capability)) dedupDrop[capability] = true @@ -1226,7 +1226,7 @@ func determineCapAddDropFromCapabilities(defaultCaps, containerCaps []string) *v // Find caps in the container but not in the defaults; those indicate // an added cap for _, capability := range containerCaps { - if !cutil.StringInSlice(capability, defaultCaps) { + if !slices.Contains(defaultCaps, capability) { if _, ok := dedupAdd[capability]; !ok { add = append(add, v1.Capability(capability)) dedupAdd[capability] = true diff --git a/libpod/networking_common.go b/libpod/networking_common.go index 3cf235b043..dc188b3fa4 100644 --- a/libpod/networking_common.go +++ b/libpod/networking_common.go @@ -12,13 +12,13 @@ import ( "github.com/containers/common/libnetwork/types" "github.com/containers/common/pkg/config" "github.com/containers/common/pkg/machine" - "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/libpod/events" "github.com/containers/podman/v4/pkg/namespaces" "github.com/containers/podman/v4/pkg/rootless" "github.com/containers/storage/pkg/lockfile" "github.com/sirupsen/logrus" + "golang.org/x/exp/slices" ) // convertPortMappings will remove the HostIP part from the ports when running inside podman machine. @@ -597,7 +597,7 @@ func getFreeInterfaceName(networks map[string]types.PerNetworkOptions) string { } for i := 0; i < 100000; i++ { ifName := fmt.Sprintf("eth%d", i) - if !util.StringInSlice(ifName, ifNames) { + if !slices.Contains(ifNames, ifName) { return ifName } } diff --git a/libpod/runtime_ctr.go b/libpod/runtime_ctr.go index 944191accd..481d1b7c94 100644 --- a/libpod/runtime_ctr.go +++ b/libpod/runtime_ctr.go @@ -17,7 +17,6 @@ import ( "github.com/containers/common/libnetwork/types" "github.com/containers/common/pkg/cgroups" "github.com/containers/common/pkg/config" - cutil "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/libpod/events" "github.com/containers/podman/v4/libpod/shutdown" @@ -31,6 +30,7 @@ import ( spec "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/runtime-tools/generate" "github.com/sirupsen/logrus" + "golang.org/x/exp/slices" ) // Contains the public Runtime API for containers @@ -256,7 +256,7 @@ func (r *Runtime) setupContainer(ctx context.Context, ctr *Container) (_ *Contai for _, opts := range ctr.config.Networks { if opts.InterfaceName != "" { // check that no name is assigned to more than network - if cutil.StringInSlice(opts.InterfaceName, usedIfNames) { + if slices.Contains(usedIfNames, opts.InterfaceName) { return nil, fmt.Errorf("network interface name %q is already assigned to another network", opts.InterfaceName) } usedIfNames = append(usedIfNames, opts.InterfaceName) @@ -272,7 +272,7 @@ func (r *Runtime) setupContainer(ctx context.Context, ctr *Container) (_ *Contai if opts.InterfaceName == "" { for i < 100000 { ifName := fmt.Sprintf("eth%d", i) - if !cutil.StringInSlice(ifName, usedIfNames) { + if !slices.Contains(usedIfNames, ifName) { opts.InterfaceName = ifName usedIfNames = append(usedIfNames, ifName) break diff --git a/libpod/runtime_pod.go b/libpod/runtime_pod.go index 2b335fecce..3dfbec004c 100644 --- a/libpod/runtime_pod.go +++ b/libpod/runtime_pod.go @@ -8,8 +8,8 @@ import ( "fmt" "time" - "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/libpod/define" + "golang.org/x/exp/slices" ) // Contains the public Runtime API for pods @@ -145,7 +145,7 @@ func (r *Runtime) GetRunningPods() ([]*Pod, error) { } // Assemble running pods for _, c := range containers { - if !util.StringInSlice(c.PodID(), pods) { + if !slices.Contains(pods, c.PodID()) { pods = append(pods, c.PodID()) pod, err := r.GetPod(c.PodID()) if err != nil { diff --git a/pkg/bindings/test/common_test.go b/pkg/bindings/test/common_test.go index c499b66c05..acc9a62cf7 100644 --- a/pkg/bindings/test/common_test.go +++ b/pkg/bindings/test/common_test.go @@ -246,17 +246,6 @@ func (b *bindingTest) PodcreateAndExpose(name *string, port *string) { b.runPodman(command).Wait(45) } -// StringInSlice returns a boolean based on whether a given -// string is in a given slice -func StringInSlice(s string, sl []string) bool { - for _, val := range sl { - if s == val { - return true - } - } - return false -} - var _ = ginkgo.SynchronizedBeforeSuite(func() []byte { // make cache dir err := os.MkdirAll(ImageCacheDir, 0777) diff --git a/pkg/bindings/test/networks_test.go b/pkg/bindings/test/networks_test.go index d790db1a82..55db4e7a5b 100644 --- a/pkg/bindings/test/networks_test.go +++ b/pkg/bindings/test/networks_test.go @@ -13,6 +13,7 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" + "golang.org/x/exp/slices" ) var _ = Describe("Podman networks", func() { @@ -148,7 +149,7 @@ var _ = Describe("Podman networks", func() { Expect(len(list)).To(BeNumerically(">=", 5)) for _, n := range list { if n.Name != "podman" { - Expect(StringInSlice(n.Name, netNames)).To(BeTrue()) + Expect(slices.Contains(netNames, n.Name)).To(BeTrue()) } } diff --git a/pkg/bindings/test/pods_test.go b/pkg/bindings/test/pods_test.go index 8627877d1e..7e559714bd 100644 --- a/pkg/bindings/test/pods_test.go +++ b/pkg/bindings/test/pods_test.go @@ -16,6 +16,7 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" + "golang.org/x/exp/slices" ) var _ = Describe("Podman pods", func() { @@ -85,8 +86,8 @@ var _ = Describe("Podman pods", func() { for _, i := range podSummary { names = append(names, i.Name) } - Expect(StringInSlice(newpod, names)).To(BeTrue()) - Expect(StringInSlice("newpod2", names)).To(BeTrue()) + Expect(slices.Contains(names, newpod)).To(BeTrue()) + Expect(slices.Contains(names, "newpod2")).To(BeTrue()) }) // The test validates the list pod endpoint with passing filters as the params. @@ -130,7 +131,7 @@ var _ = Describe("Podman pods", func() { for _, i := range filteredPods { names = append(names, i.Name) } - Expect(StringInSlice("newpod2", names)).To(BeTrue()) + Expect(slices.Contains(names, "newpod2")).To(BeTrue()) // Validate list pod with id filter filters = make(map[string][]string) @@ -146,7 +147,7 @@ var _ = Describe("Podman pods", func() { for _, i := range filteredPods { names = append(names, i.Name) } - Expect(StringInSlice("newpod", names)).To(BeTrue()) + Expect(slices.Contains(names, "newpod")).To(BeTrue()) // Using multiple filters filters["name"] = []string{newpod} @@ -158,7 +159,7 @@ var _ = Describe("Podman pods", func() { for _, i := range filteredPods { names = append(names, i.Name) } - Expect(StringInSlice("newpod", names)).To(BeTrue()) + Expect(slices.Contains(names, "newpod")).To(BeTrue()) }) // The test validates if the exists responds diff --git a/pkg/bindings/test/volumes_test.go b/pkg/bindings/test/volumes_test.go index a54c56178f..62950d3fd0 100644 --- a/pkg/bindings/test/volumes_test.go +++ b/pkg/bindings/test/volumes_test.go @@ -14,6 +14,7 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" + "golang.org/x/exp/slices" ) var _ = Describe("Podman volumes", func() { @@ -117,7 +118,7 @@ var _ = Describe("Podman volumes", func() { Expect(err).ToNot(HaveOccurred()) Expect(vols).To(HaveLen(5)) for _, v := range vols { - Expect(StringInSlice(v.Name, volNames)).To(BeTrue()) + Expect(slices.Contains(volNames, v.Name)).To(BeTrue()) } // list with bad filter should be 500 diff --git a/pkg/domain/filters/containers.go b/pkg/domain/filters/containers.go index 2fd97b717d..52ddc746d4 100644 --- a/pkg/domain/filters/containers.go +++ b/pkg/domain/filters/containers.go @@ -13,6 +13,7 @@ import ( "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/libpod" "github.com/containers/podman/v4/libpod/define" + "golang.org/x/exp/slices" ) // GenerateContainerFilterFuncs return ContainerFilter functions based of filter. @@ -263,7 +264,7 @@ func GenerateContainerFilterFuncs(filter string, filterValues []string, r *libpo return false } for _, net := range networks { - if util.StringInSlice(net, inputNetNames) { + if slices.Contains(inputNetNames, net) { return true } } diff --git a/pkg/domain/filters/pods.go b/pkg/domain/filters/pods.go index 77de6cb430..9943ab7e57 100644 --- a/pkg/domain/filters/pods.go +++ b/pkg/domain/filters/pods.go @@ -12,6 +12,7 @@ import ( "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/libpod" "github.com/containers/podman/v4/libpod/define" + "golang.org/x/exp/slices" ) // GeneratePodFilterFunc takes a filter and filtervalue (key, value) @@ -63,7 +64,7 @@ func GeneratePodFilterFunc(filter string, filterValues []string, r *libpod.Runti }, nil case "ctr-status": for _, filterValue := range filterValues { - if !util.StringInSlice(filterValue, []string{"created", "running", "paused", "stopped", "exited", "unknown"}) { + if !slices.Contains([]string{"created", "running", "paused", "stopped", "exited", "unknown"}, filterValue) { return nil, fmt.Errorf("%s is not a valid status", filterValue) } } @@ -100,7 +101,7 @@ func GeneratePodFilterFunc(filter string, filterValues []string, r *libpod.Runti }, nil case "status": for _, filterValue := range filterValues { - if !util.StringInSlice(filterValue, []string{"stopped", "running", "paused", "exited", "dead", "created", "degraded"}) { + if !slices.Contains([]string{"stopped", "running", "paused", "exited", "dead", "created", "degraded"}, filterValue) { return nil, fmt.Errorf("%s is not a valid pod status", filterValue) } } @@ -161,7 +162,7 @@ func GeneratePodFilterFunc(filter string, filterValues []string, r *libpod.Runti return false } for _, net := range networks { - if util.StringInSlice(net, inputNetNames) { + if slices.Contains(inputNetNames, net) { return true } } diff --git a/pkg/domain/infra/abi/images_list.go b/pkg/domain/infra/abi/images_list.go index d70fca268b..706c40a22f 100644 --- a/pkg/domain/infra/abi/images_list.go +++ b/pkg/domain/infra/abi/images_list.go @@ -7,7 +7,7 @@ import ( "github.com/containers/common/libimage" "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/pkg/domain/entities" - "github.com/containers/podman/v4/pkg/util" + "golang.org/x/exp/slices" ) func (ir *ImageEngine) List(ctx context.Context, opts entities.ImageListOptions) ([]*entities.ImageSummary, error) { @@ -15,7 +15,7 @@ func (ir *ImageEngine) List(ctx context.Context, opts entities.ImageListOptions) Filters: opts.Filter, SetListData: true, } - if !opts.All && !util.StringInSlice("intermediate=true", listImagesOptions.Filters) { + if !opts.All && !slices.Contains(listImagesOptions.Filters, "intermediate=true") { // Filter intermediate images unless we want to list *all*. // NOTE: it's a positive filter, so `intermediate=false` means // to display non-intermediate images. diff --git a/pkg/domain/infra/abi/network.go b/pkg/domain/infra/abi/network.go index b51ba764bd..166176b4ea 100644 --- a/pkg/domain/infra/abi/network.go +++ b/pkg/domain/infra/abi/network.go @@ -8,9 +8,9 @@ import ( "github.com/containers/common/libnetwork/types" netutil "github.com/containers/common/libnetwork/util" - "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/pkg/domain/entities" + "golang.org/x/exp/slices" ) func (ic *ContainerEngine) NetworkUpdate(ctx context.Context, netName string, options entities.NetworkUpdateOptions) error { @@ -121,7 +121,7 @@ func (ic *ContainerEngine) NetworkRm(ctx context.Context, namesOrIds []string, o if err != nil { return reports, err } - if util.StringInSlice(name, networks) { + if slices.Contains(networks, name) { // if user passes force, we nuke containers and pods if !options.Force { // Without the force option, we return an error @@ -151,7 +151,7 @@ func (ic *ContainerEngine) NetworkRm(ctx context.Context, namesOrIds []string, o func (ic *ContainerEngine) NetworkCreate(ctx context.Context, network types.Network, createOptions *types.NetworkCreateOptions) (*types.Network, error) { // TODO (5.0): Stop accepting "pasta" as value here - if util.StringInSlice(network.Name, []string{"none", "host", "bridge", "private", "slirp4netns", "container", "ns", "default"}) { + if slices.Contains([]string{"none", "host", "bridge", "private", "slirp4netns", "container", "ns", "default"}, network.Name) { return nil, fmt.Errorf("cannot create network with name %q because it conflicts with a valid network mode", network.Name) } network, err := ic.Libpod.Network().NetworkCreate(network, createOptions) diff --git a/pkg/machine/e2e/config_test.go b/pkg/machine/e2e/config_test.go index 18b961a0d5..354b3be742 100644 --- a/pkg/machine/e2e/config_test.go +++ b/pkg/machine/e2e/config_test.go @@ -12,13 +12,13 @@ import ( "github.com/containers/podman/v4/pkg/machine" "github.com/containers/podman/v4/pkg/machine/define" - "github.com/containers/podman/v4/pkg/util" "github.com/containers/storage/pkg/stringid" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/format" . "github.com/onsi/gomega/gexec" "github.com/onsi/gomega/types" + "golang.org/x/exp/slices" ) var originalHomeDir = os.Getenv("HOME") @@ -122,7 +122,7 @@ func (m *machineTestBuilder) setName(name string) *machineTestBuilder { // representation of the podman machine command func (m *machineTestBuilder) setCmd(mc machineCommand) *machineTestBuilder { // If no name for the machine exists, we set a random name. - if !util.StringInSlice(m.name, m.names) { + if !slices.Contains(m.names, m.name) { if len(m.name) < 1 { m.name = randomString() } diff --git a/pkg/machine/e2e/list_test.go b/pkg/machine/e2e/list_test.go index 4cdef055e9..2a8f51f13b 100644 --- a/pkg/machine/e2e/list_test.go +++ b/pkg/machine/e2e/list_test.go @@ -4,12 +4,12 @@ import ( "strings" "time" - "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/pkg/domain/entities" jsoniter "github.com/json-iterator/go" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" + "golang.org/x/exp/slices" ) var _ = Describe("podman machine list", func() { @@ -75,8 +75,8 @@ var _ = Describe("podman machine list", func() { listNames := secondList.outputToStringSlice() stripAsterisk(listNames) - Expect(util.StringInSlice(name1, listNames)).To(BeTrue()) - Expect(util.StringInSlice(name2, listNames)).To(BeTrue()) + Expect(slices.Contains(listNames, name1)).To(BeTrue()) + Expect(slices.Contains(listNames, name2)).To(BeTrue()) }) It("list machine: check if running while starting", func() { @@ -136,7 +136,7 @@ var _ = Describe("podman machine list", func() { listNames := listSession.outputToStringSlice() stripAsterisk(listNames) - Expect(util.StringInSlice(name1, listNames)).To(BeTrue()) + Expect(slices.Contains(listNames, name1)).To(BeTrue()) // --format json list2 := new(listMachine) diff --git a/pkg/specgen/container_validate.go b/pkg/specgen/container_validate.go index c6a8baddd7..2371434656 100644 --- a/pkg/specgen/container_validate.go +++ b/pkg/specgen/container_validate.go @@ -5,8 +5,8 @@ import ( "fmt" "strings" - "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/libpod/define" + "golang.org/x/exp/slices" ) var ( @@ -59,7 +59,7 @@ func (s *SpecGenerator) Validate() error { return fmt.Errorf("cannot set hostname when running in the host UTS namespace: %w", ErrInvalidSpecConfig) } // systemd values must be true, false, or always - if len(s.ContainerBasicConfig.Systemd) > 0 && !util.StringInSlice(strings.ToLower(s.ContainerBasicConfig.Systemd), SystemDValues) { + if len(s.ContainerBasicConfig.Systemd) > 0 && !slices.Contains(SystemDValues, strings.ToLower(s.ContainerBasicConfig.Systemd)) { return fmt.Errorf("--systemd values must be one of %q: %w", strings.Join(SystemDValues, ", "), ErrInvalidSpecConfig) } @@ -75,7 +75,7 @@ func (s *SpecGenerator) Validate() error { return exclusiveOptions("rootfs", "image") } // imagevolumemode must be one of ignore, tmpfs, or anonymous if given - if len(s.ContainerStorageConfig.ImageVolumeMode) > 0 && !util.StringInSlice(strings.ToLower(s.ContainerStorageConfig.ImageVolumeMode), ImageVolumeModeValues) { + if len(s.ContainerStorageConfig.ImageVolumeMode) > 0 && !slices.Contains(ImageVolumeModeValues, strings.ToLower(s.ContainerStorageConfig.ImageVolumeMode)) { return fmt.Errorf("invalid ImageVolumeMode %q, value must be one of %s", s.ContainerStorageConfig.ImageVolumeMode, strings.Join(ImageVolumeModeValues, ",")) } diff --git a/pkg/specgen/generate/kube/kube.go b/pkg/specgen/generate/kube/kube.go index bae88407f3..930f1497f0 100644 --- a/pkg/specgen/generate/kube/kube.go +++ b/pkg/specgen/generate/kube/kube.go @@ -21,7 +21,6 @@ import ( "github.com/containers/common/pkg/config" "github.com/containers/common/pkg/parse" "github.com/containers/common/pkg/secrets" - cutil "github.com/containers/common/pkg/util" "github.com/containers/image/v5/manifest" itypes "github.com/containers/image/v5/types" "github.com/containers/podman/v4/libpod/define" @@ -487,7 +486,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener // Make sure the z/Z option is not already there (from editing the YAML) if k == define.BindMountPrefix { lastIndex := strings.LastIndex(v, ":") - if lastIndex != -1 && v[:lastIndex] == volumeSource.Source && !cutil.StringInSlice("z", options) && !cutil.StringInSlice("Z", options) { + if lastIndex != -1 && v[:lastIndex] == volumeSource.Source && !slices.Contains(options, "z") && !slices.Contains(options, "Z") { options = append(options, v[lastIndex+1:]) } } diff --git a/pkg/specgen/generate/ports.go b/pkg/specgen/generate/ports.go index 1d0d9c2059..3284d9181e 100644 --- a/pkg/specgen/generate/ports.go +++ b/pkg/specgen/generate/ports.go @@ -10,12 +10,11 @@ import ( "github.com/containers/common/libimage" "github.com/containers/common/libnetwork/types" - "github.com/containers/podman/v4/utils" - - "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/pkg/specgen" "github.com/containers/podman/v4/pkg/specgenutil" + "github.com/containers/podman/v4/utils" "github.com/sirupsen/logrus" + "golang.org/x/exp/slices" ) const ( @@ -332,7 +331,7 @@ func ParsePortMapping(portMappings []types.PortMapping, exposePorts map[uint16][ func appendProtocolsNoDuplicates(slice []string, protocols []string) []string { for _, proto := range protocols { - if util.StringInSlice(proto, slice) { + if slices.Contains(slice, proto) { continue } slice = append(slice, proto) diff --git a/pkg/specgen/generate/security_linux.go b/pkg/specgen/generate/security_linux.go index 92a2362870..ff288285f1 100644 --- a/pkg/specgen/generate/security_linux.go +++ b/pkg/specgen/generate/security_linux.go @@ -10,7 +10,6 @@ import ( "github.com/containers/common/pkg/apparmor" "github.com/containers/common/pkg/capabilities" "github.com/containers/common/pkg/config" - cutil "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/libpod" "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/pkg/specgen" @@ -18,6 +17,7 @@ import ( "github.com/opencontainers/runtime-tools/generate" "github.com/opencontainers/selinux/go-selinux/label" "github.com/sirupsen/logrus" + "golang.org/x/exp/slices" ) // setLabelOpts sets the label options of the SecurityConfig according to the @@ -123,7 +123,7 @@ func securityConfigureGenerator(s *specgen.SpecGenerator, g *generate.Generator, // capabilities, required to run the container. var capsRequiredRequested []string for key, val := range s.Labels { - if cutil.StringInSlice(key, capabilities.ContainerImageLabels) { + if slices.Contains(capabilities.ContainerImageLabels, key) { capsRequiredRequested = strings.Split(val, ",") } } @@ -137,7 +137,7 @@ func securityConfigureGenerator(s *specgen.SpecGenerator, g *generate.Generator, } // Verify all capRequired are in the capList for _, cap := range capsRequired { - if !cutil.StringInSlice(cap, caplist) { + if !slices.Contains(caplist, cap) { privCapsRequired = append(privCapsRequired, cap) } } diff --git a/pkg/specgen/namespaces.go b/pkg/specgen/namespaces.go index 94c96794a3..04d4b08f43 100644 --- a/pkg/specgen/namespaces.go +++ b/pkg/specgen/namespaces.go @@ -9,7 +9,6 @@ import ( "github.com/containers/common/libnetwork/types" "github.com/containers/common/pkg/cgroups" - cutil "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/pkg/namespaces" "github.com/containers/podman/v4/pkg/rootless" @@ -17,6 +16,7 @@ import ( "github.com/containers/storage" spec "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/runtime-tools/generate" + "golang.org/x/exp/slices" ) type NamespaceMode string @@ -445,8 +445,8 @@ func ParseNetworkFlag(networks []string, pastaNetworkNameExists bool) (Namespace return toReturn, nil, nil, fmt.Errorf("network name cannot be empty: %w", define.ErrInvalidArg) } // TODO (5.0): Don't accept string(Pasta) here once we drop pastaNetworkNameExists - if cutil.StringInSlice(parts[0], []string{string(Bridge), string(Slirp), string(FromPod), string(NoNetwork), - string(Default), string(Private), string(Path), string(FromContainer), string(Host)}) { + if slices.Contains([]string{string(Bridge), string(Slirp), string(FromPod), string(NoNetwork), + string(Default), string(Private), string(Path), string(FromContainer), string(Host)}, parts[0]) { return toReturn, nil, nil, fmt.Errorf("can only set extra network names, selected mode %s conflicts with bridge: %w", parts[0], define.ErrInvalidArg) } netOpts := types.PerNetworkOptions{} diff --git a/pkg/util/utils.go b/pkg/util/utils.go index 04abffa36f..0b1abeea3b 100644 --- a/pkg/util/utils.go +++ b/pkg/util/utils.go @@ -18,7 +18,6 @@ import ( "github.com/BurntSushi/toml" "github.com/containers/common/pkg/config" - "github.com/containers/common/pkg/util" "github.com/containers/image/v5/types" "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/pkg/errorhandling" @@ -161,11 +160,6 @@ func ParseRegistryCreds(creds string) (*types.DockerAuthConfig, error) { }, nil } -// StringInSlice is deprecated, use containers/common/pkg/util/StringInSlice -func StringInSlice(s string, sl []string) bool { - return util.StringInSlice(s, sl) -} - // StringMatchRegexSlice determines if a given string matches one of the given regexes, returns bool func StringMatchRegexSlice(s string, re []string) bool { for _, r := range re { @@ -177,17 +171,6 @@ func StringMatchRegexSlice(s string, re []string) bool { return false } -// IndexOfStringInSlice returns the index if a string is in a slice, otherwise -// it returns -1 if the string is not found -func IndexOfStringInSlice(s string, sl []string) int { - for i := range sl { - if sl[i] == s { - return i - } - } - return -1 -} - // ParseSignal parses and validates a signal name or number. func ParseSignal(rawSignal string) (syscall.Signal, error) { // Strip off leading dash, to allow -1 or -HUP diff --git a/pkg/util/utils_test.go b/pkg/util/utils_test.go index e3c303a6e9..3d01be5dd8 100644 --- a/pkg/util/utils_test.go +++ b/pkg/util/utils_test.go @@ -13,10 +13,6 @@ import ( "github.com/stretchr/testify/assert" ) -var ( - sliceData = []string{"one", "two", "three", "four"} -) - func BreakInsert(mapping []idtools.IDMap, extension idtools.IDMap) (result []idtools.IDMap) { result = breakInsert(mapping, extension) result = sortAndMergeConsecutiveMappings(result) @@ -485,15 +481,6 @@ func TestGetAvailableIDRanges(t *testing.T) { assert.Equal(t, expectedResult, result) } -func TestStringInSlice(t *testing.T) { - // string is in the slice - assert.True(t, StringInSlice("one", sliceData)) - // string is not in the slice - assert.False(t, StringInSlice("five", sliceData)) - // string is not in empty slice - assert.False(t, StringInSlice("one", []string{})) -} - func TestValidateSysctls(t *testing.T) { strSlice := []string{"net.core.test1=4", "kernel.msgmax=2"} result, _ := ValidateSysctls(strSlice) diff --git a/test/e2e/common_test.go b/test/e2e/common_test.go index 56a26b35be..f3f02da3d8 100644 --- a/test/e2e/common_test.go +++ b/test/e2e/common_test.go @@ -23,7 +23,6 @@ import ( "github.com/containers/common/pkg/cgroups" "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/pkg/inspect" - "github.com/containers/podman/v4/pkg/util" . "github.com/containers/podman/v4/test/utils" "github.com/containers/storage/pkg/lockfile" "github.com/containers/storage/pkg/reexec" @@ -33,6 +32,7 @@ import ( . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" "github.com/sirupsen/logrus" + "golang.org/x/exp/slices" "golang.org/x/sys/unix" ) @@ -1043,7 +1043,7 @@ func (p *PodmanTestIntegration) PodmanNoEvents(args []string) *PodmanSessionInte // MakeOptions assembles all the podman main options func (p *PodmanTestIntegration) makeOptions(args []string, noEvents, noCache bool) []string { if p.RemoteTest { - if !util.StringInSlice("--remote", args) { + if !slices.Contains(args, "--remote") { return append([]string{"--remote", "--url", p.RemoteSocket}, args...) } return args diff --git a/test/utils/common_function_test.go b/test/utils/common_function_test.go index 805c8e1bc9..77a9b15ae2 100644 --- a/test/utils/common_function_test.go +++ b/test/utils/common_function_test.go @@ -38,13 +38,6 @@ var _ = Describe("Common functions test", func() { Expect(session.Command.Process).ShouldNot(BeNil(), "SystemExec cannot start a process") }) - It("Test StringInSlice", func() { - testSlice := []string{"apple", "peach", "pear"} - Expect(StringInSlice("apple", testSlice)).To(BeTrue(), "apple should in ['apple', 'peach', 'pear']") - Expect(StringInSlice("banana", testSlice)).ShouldNot(BeTrue(), "banana should not in ['apple', 'peach', 'pear']") - Expect(StringInSlice("anything", []string{})).ShouldNot(BeTrue(), "anything should not in empty slice") - }) - DescribeTable("Test GetHostDistributionInfo", func(path, id, ver string, empty bool) { txt := fmt.Sprintf("ID=%s\nVERSION_ID=%s", id, ver) diff --git a/test/utils/utils.go b/test/utils/utils.go index 205c4edd89..b3f0a17fca 100644 --- a/test/utils/utils.go +++ b/test/utils/utils.go @@ -404,16 +404,6 @@ func StartSystemExec(command string, args []string) *PodmanSession { return &PodmanSession{session} } -// StringInSlice determines if a string is in a string slice, returns bool -func StringInSlice(s string, sl []string) bool { - for _, i := range sl { - if i == s { - return true - } - } - return false -} - // tagOutPutToMap parses each string in imagesOutput and returns // a map whose key is a repo, and value is another map whose keys // are the tags found for that repo. Notice, the first array item will