Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: replace raw loops with funcs from slices and maps #1784

Merged
merged 1 commit into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ require (
github.com/vishvananda/netlink v1.2.1-beta.2
go.etcd.io/bbolt v1.3.8
golang.org/x/crypto v0.17.0
golang.org/x/exp v0.0.0-20231006140011-7918f672742d
golang.org/x/sync v0.6.0
golang.org/x/sys v0.15.0
golang.org/x/term v0.15.0
Expand Down Expand Up @@ -127,7 +128,6 @@ require (
go.mongodb.org/mongo-driver v1.13.1 // indirect
go.mozilla.org/pkcs7 v0.0.0-20210826202110-33d05740a352 // indirect
go.opencensus.io v0.24.0 // indirect
golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect
golang.org/x/mod v0.13.0 // indirect
golang.org/x/net v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
Expand Down
8 changes: 4 additions & 4 deletions libnetwork/cni/cni_conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import (
internalutil "github.com/containers/common/libnetwork/internal/util"
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/libnetwork/util"
pkgutil "github.com/containers/common/pkg/util"
"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
"golang.org/x/sys/unix"
)

Expand Down Expand Up @@ -358,7 +358,7 @@ func convertSpecgenPortsToCNIPorts(ports []types.PortMapping) ([]cniPortMapEntry
protocols := strings.Split(port.Protocol, ",")

for _, protocol := range protocols {
if !pkgutil.StringInSlice(protocol, []string{"tcp", "udp", "sctp"}) {
if !slices.Contains([]string{"tcp", "udp", "sctp"}, protocol) {
return nil, fmt.Errorf("unknown port protocol %s", protocol)
}
cniPort := cniPortMapEntry{
Expand Down Expand Up @@ -420,11 +420,11 @@ func parseOptions(networkOptions map[string]string, networkDriver string) (*opti
case types.ModeOption:
switch networkDriver {
case types.MacVLANNetworkDriver:
if !pkgutil.StringInSlice(v, types.ValidMacVLANModes) {
if !slices.Contains(types.ValidMacVLANModes, v) {
return nil, fmt.Errorf("unknown macvlan mode %q", v)
}
case types.IPVLANNetworkDriver:
if !pkgutil.StringInSlice(v, types.ValidIPVLANModes) {
if !slices.Contains(types.ValidIPVLANModes, v) {
return nil, fmt.Errorf("unknown ipvlan mode %q", v)
}
default:
Expand Down
4 changes: 2 additions & 2 deletions libnetwork/cni/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (

internalutil "github.com/containers/common/libnetwork/internal/util"
"github.com/containers/common/libnetwork/types"
pkgutil "github.com/containers/common/pkg/util"
"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
)

func (n *cniNetwork) NetworkUpdate(_ string, _ types.NetworkUpdateOptions) error {
Expand Down Expand Up @@ -205,7 +205,7 @@ func createIPMACVLAN(network *types.Network) error {
if err != nil {
return err
}
if !pkgutil.StringInSlice(network.NetworkInterface, interfaceNames) {
if !slices.Contains(interfaceNames, network.NetworkInterface) {
return fmt.Errorf("parent interface %s does not exist", network.NetworkInterface)
}
}
Expand Down
4 changes: 2 additions & 2 deletions libnetwork/etchosts/hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"strings"

"github.com/containers/common/pkg/config"
"github.com/containers/common/pkg/util"
"golang.org/x/exp/slices"
)

const (
Expand Down Expand Up @@ -220,7 +220,7 @@ func checkIfEntryExists(current HostEntry, entries HostEntries) bool {
if current.IP == rm.IP {
// it is enough if one of the names match, in this case we remove the full entry
for _, name := range current.Names {
if util.StringInSlice(name, rm.Names) {
if slices.Contains(rm.Names, name) {
return true
}
}
Expand Down
4 changes: 2 additions & 2 deletions libnetwork/internal/util/bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ import (
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/libnetwork/util"
"github.com/containers/common/pkg/config"
pkgutil "github.com/containers/common/pkg/util"
"golang.org/x/exp/slices"
)

func CreateBridge(n NetUtil, network *types.Network, usedNetworks []*net.IPNet, subnetPools []config.SubnetPool) error {
if network.NetworkInterface != "" {
bridges := GetBridgeInterfaceNames(n)
if pkgutil.StringInSlice(network.NetworkInterface, bridges) {
if slices.Contains(bridges, network.NetworkInterface) {
return fmt.Errorf("bridge name %s already in use", network.NetworkInterface)
}
if !types.NameRegex.MatchString(network.NetworkInterface) {
Expand Down
4 changes: 2 additions & 2 deletions libnetwork/internal/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import (

"github.com/containers/common/libnetwork/types"
"github.com/containers/common/pkg/config"
"github.com/containers/common/pkg/util"
"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
)

// GetBridgeInterfaceNames returns all bridge interface names
Expand Down Expand Up @@ -51,7 +51,7 @@ func GetFreeDeviceName(n NetUtil) (string, error) {
// Start by 1, 0 is reserved for the default network
for i := 1; i < 1000000; i++ {
deviceName := fmt.Sprintf("%s%d", n.DefaultInterfaceName(), i)
if !util.StringInSlice(deviceName, names) {
if !slices.Contains(names, deviceName) {
logrus.Debugf("found free device name %s", deviceName)
return deviceName, nil
}
Expand Down
14 changes: 7 additions & 7 deletions libnetwork/netavark/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ import (

internalutil "github.com/containers/common/libnetwork/internal/util"
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/pkg/util"
"github.com/containers/storage/pkg/stringid"
"golang.org/x/exp/slices"
)

func sliceRemoveDuplicates(strList []string) []string {
list := make([]string, 0, len(strList))
for _, item := range strList {
if !util.StringInSlice(item, list) {
if !slices.Contains(list, item) {
list = append(list, item)
}
}
Expand Down Expand Up @@ -70,7 +70,7 @@ func (n *netavarkNetwork) NetworkUpdate(name string, options types.NetworkUpdate
networkDNSServersBefore := network.NetworkDNSServers
networkDNSServersAfter := []string{}
for _, server := range networkDNSServersBefore {
if util.StringInSlice(server, options.RemoveDNSServers) {
if slices.Contains(options.RemoveDNSServers, server) {
continue
}
networkDNSServersAfter = append(networkDNSServersAfter, server)
Expand Down Expand Up @@ -272,7 +272,7 @@ func createIpvlanOrMacvlan(network *types.Network) error {
if err != nil {
return err
}
if !util.StringInSlice(network.NetworkInterface, interfaceNames) {
if !slices.Contains(interfaceNames, network.NetworkInterface) {
return fmt.Errorf("parent interface %s does not exist", network.NetworkInterface)
}
}
Expand Down Expand Up @@ -318,11 +318,11 @@ func createIpvlanOrMacvlan(network *types.Network) error {
switch key {
case types.ModeOption:
if isMacVlan {
if !util.StringInSlice(value, types.ValidMacVLANModes) {
if !slices.Contains(types.ValidMacVLANModes, value) {
return fmt.Errorf("unknown macvlan mode %q", value)
}
} else {
if !util.StringInSlice(value, types.ValidIPVLANModes) {
if !slices.Contains(types.ValidIPVLANModes, value) {
return fmt.Errorf("unknown ipvlan mode %q", value)
}
}
Expand Down Expand Up @@ -472,7 +472,7 @@ func getAllPlugins(dirs []string) []string {
if err == nil {
for _, entry := range entries {
name := entry.Name()
if !util.StringInSlice(name, plugins) {
if !slices.Contains(plugins, name) {
plugins = append(plugins, name)
}
}
Expand Down
4 changes: 2 additions & 2 deletions libnetwork/netavark/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (

"github.com/containers/common/libnetwork/internal/util"
"github.com/containers/common/libnetwork/types"
pkgutil "github.com/containers/common/pkg/util"
"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
)

type netavarkOptions struct {
Expand Down Expand Up @@ -174,7 +174,7 @@ func (n *netavarkNetwork) convertNetOpts(opts types.NetworkOptions) (*netavarkOp
return nil, false, err
}
netavarkOptions.Networks[network] = net
if !pkgutil.StringInSlice(net.Driver, builtinDrivers) {
if !slices.Contains(builtinDrivers, net.Driver) {
needsPlugin = true
}
}
Expand Down
6 changes: 3 additions & 3 deletions libnetwork/resolvconf/resolv.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import (
"path/filepath"
"strings"

"github.com/containers/common/pkg/util"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
)

const (
Expand Down Expand Up @@ -111,7 +111,7 @@ func getDefaultResolvConf(params *Params) ([]byte, bool, error) {

// unsetSearchDomainsIfNeeded removes the search domain when they contain a single dot as element.
func unsetSearchDomainsIfNeeded(searches []string) []string {
if util.StringInSlice(".", searches) {
if slices.Contains(searches, ".") {
return nil
}
return searches
Expand Down Expand Up @@ -173,7 +173,7 @@ func Remove(path string, nameservers []string) error {
oldNameservers := getNameservers(contents)
newNameserver := make([]string, 0, len(oldNameservers))
for _, ns := range oldNameservers {
if !util.StringInSlice(ns, nameservers) {
if !slices.Contains(nameservers, ns) {
newNameserver = append(newNameserver, ns)
}
}
Expand Down
3 changes: 2 additions & 1 deletion libnetwork/util/filters.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/pkg/filters"
"github.com/containers/common/pkg/util"
"golang.org/x/exp/slices"
)

func GenerateNetworkFilters(f map[string][]string) ([]types.FilterFunc, error) {
Expand All @@ -32,7 +33,7 @@ func createFilterFuncs(key string, filterValues []string) (types.FilterFunc, err
case types.Driver:
// matches network driver
return func(net types.Network) bool {
return util.StringInSlice(net.Driver, filterValues)
return slices.Contains(filterValues, net.Driver)
}, nil

case "id":
Expand Down
29 changes: 10 additions & 19 deletions pkg/capabilities/capabilities.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"sync"

"github.com/syndtr/gocapability/capability"
"golang.org/x/exp/slices"
)

var (
Expand Down Expand Up @@ -54,16 +55,6 @@ func init() {
}
}

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

var (
boundingSetOnce sync.Once
boundingSetRet []string
Expand Down Expand Up @@ -115,7 +106,7 @@ func NormalizeCapabilities(caps []string) ([]string, error) {
if !strings.HasPrefix(c, "CAP_") {
c = "CAP_" + c
}
if !stringInSlice(c, capabilityList) {
if !slices.Contains(capabilityList, c) {
return nil, fmt.Errorf("%q: %w", c, ErrUnknownCapability)
}
normalized = append(normalized, c)
Expand All @@ -127,7 +118,7 @@ func NormalizeCapabilities(caps []string) ([]string, error) {
// ValidateCapabilities validates if caps only contains valid capabilities.
func ValidateCapabilities(caps []string) error {
for _, c := range caps {
if !stringInSlice(c, capabilityList) {
if !slices.Contains(capabilityList, c) {
return fmt.Errorf("%q: %w", c, ErrUnknownCapability)
}
}
Expand Down Expand Up @@ -159,47 +150,47 @@ func MergeCapabilities(base, adds, drops []string) ([]string, error) {
return nil, err
}

if stringInSlice(All, capDrop) {
if stringInSlice(All, capAdd) {
if slices.Contains(capDrop, All) {
if slices.Contains(capAdd, All) {
return nil, errors.New("adding all caps and removing all caps not allowed")
}
// "Drop" all capabilities; return what's in capAdd instead
sort.Strings(capAdd)
return capAdd, nil
}

if stringInSlice(All, capAdd) {
if slices.Contains(capAdd, All) {
base, err = BoundingSet()
if err != nil {
return nil, err
}
capAdd = []string{}
} else {
for _, add := range capAdd {
if stringInSlice(add, capDrop) {
if slices.Contains(capDrop, add) {
return nil, fmt.Errorf("capability %q cannot be dropped and added", add)
}
}
}

for _, drop := range capDrop {
if stringInSlice(drop, capAdd) {
if slices.Contains(capAdd, drop) {
return nil, fmt.Errorf("capability %q cannot be dropped and added", drop)
}
}

caps := make([]string, 0, len(base)+len(capAdd))
// Drop any capabilities in capDrop that are in base
for _, cap := range base {
if stringInSlice(cap, capDrop) {
if slices.Contains(capDrop, cap) {
continue
}
caps = append(caps, cap)
}

// Add any capabilities in capAdd that are not in base
for _, cap := range capAdd {
if stringInSlice(cap, base) {
if slices.Contains(base, cap) {
continue
}
caps = append(caps, cap)
Expand Down
4 changes: 2 additions & 2 deletions pkg/capabilities/capabilities_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ func TestMergeCapabilitiesAddAll(t *testing.T) {
caps, err = MergeCapabilities(base, adds, drops)
require.Nil(t, err)
assert.NotEqual(t, caps, allCaps)
assert.False(t, stringInSlice("CAP_SETUID", caps))
assert.False(t, stringInSlice("CAP_CHOWN", caps))
assert.NotContains(t, caps, "CAP_SETUID")
assert.NotContains(t, caps, "CAP_CHOWN")
}

func TestMergeCapabilitiesAddAllDropAll(t *testing.T) {
Expand Down
6 changes: 2 additions & 4 deletions pkg/cgroups/cgroups_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"github.com/opencontainers/runc/libcontainer/cgroups/fs2"
"github.com/opencontainers/runc/libcontainer/configs"
"github.com/sirupsen/logrus"
"golang.org/x/exp/maps"
)

var (
Expand Down Expand Up @@ -491,10 +492,7 @@ func (c *CgroupControl) AddPid(pid int) error {
return fs2.CreateCgroupPath(path, c.config)
}

names := make([]string, 0, len(handlers))
for n := range handlers {
names = append(names, n)
}
names := maps.Keys(handlers)

for _, c := range c.additionalControllers {
if !c.symlink {
Expand Down
4 changes: 2 additions & 2 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ import (
"github.com/containers/common/internal/attributedstring"
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/pkg/capabilities"
"github.com/containers/common/pkg/util"
"github.com/containers/storage/pkg/ioutils"
"github.com/containers/storage/pkg/unshare"
units "github.com/docker/go-units"
selinux "github.com/opencontainers/selinux/go-selinux"
"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
)

const (
Expand Down Expand Up @@ -1228,7 +1228,7 @@ func ValidateImageVolumeMode(mode string) error {
if mode == "" {
return nil
}
if util.StringInSlice(mode, validImageVolumeModes) {
if slices.Contains(validImageVolumeModes, mode) {
return nil
}

Expand Down
Loading