Refactor: replace StringInSlice with slices.Contains

Signed-off-by: Oleksandr Redko <Oleksandr_Redko@epam.com>
This commit is contained in:
Oleksandr Redko
2024-01-05 14:48:12 +02:00
parent 82125f14b0
commit 8bdf77aa20
34 changed files with 79 additions and 133 deletions

View File

@ -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

View File

@ -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
}

View File

@ -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)

View File

@ -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

View File

@ -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)

View File

@ -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
}

View File

@ -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:]...)
}

View File

@ -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)

View File

@ -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)
}

View File

@ -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 {

View File

@ -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

View File

@ -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
}
}

View File

@ -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

View File

@ -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 {

View File

@ -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)

View File

@ -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())
}
}

View File

@ -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

View File

@ -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

View File

@ -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
}
}

View File

@ -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
}
}

View File

@ -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.

View File

@ -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)

View File

@ -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()
}

View File

@ -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)

View File

@ -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, ","))
}

View File

@ -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:])
}
}

View File

@ -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)

View File

@ -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)
}
}

View File

@ -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{}

View File

@ -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

View File

@ -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)

View File

@ -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

View File

@ -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)

View File

@ -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