Skip to content

Commit

Permalink
linting: Consider pre-allocating sliceVar (prealloc)
Browse files Browse the repository at this point in the history
While updating, also addressed some redundant fmt.Sprintf()

    opts/throttledevice.go:86:2: Consider pre-allocating `out` (prealloc)
        var out []string
        ^
    opts/ulimit.go:37:2: Consider pre-allocating `out` (prealloc)
        var out []string
        ^
    opts/ulimit.go:47:2: Consider pre-allocating `ulimits` (prealloc)
        var ulimits []*units.Ulimit
        ^
    opts/weightdevice.go:68:2: Consider pre-allocating `out` (prealloc)
        var out []string
        ^
    cli/context/store/metadatastore.go:96:2: Consider pre-allocating `res` (prealloc)
        var res []Metadata
        ^
    cli/context/store/store.go:127:2: Consider pre-allocating `names` (prealloc)
        var names []string
        ^
    cli/compose/loader/loader.go:223:2: Consider pre-allocating `keys` (prealloc)
        var keys []string
        ^
    cli/compose/loader/loader.go:397:2: Consider pre-allocating `services` (prealloc)
        var services []types.ServiceConfig
        ^
    cli/command/stack/loader/loader.go:63:2: Consider pre-allocating `msgs` (prealloc)
        var msgs []string
        ^
    cli/command/stack/loader/loader.go:118:2: Consider pre-allocating `configFiles` (prealloc)
        var configFiles []composetypes.ConfigFile
        ^
    cli/command/formatter/container.go:245:2: Consider pre-allocating `joinLabels` (prealloc)
        var joinLabels []string
        ^
    cli/command/formatter/container.go:265:2: Consider pre-allocating `mounts` (prealloc)
        var mounts []string
        ^
    cli/command/formatter/container.go:316:2: Consider pre-allocating `result` (prealloc)
        var result []string
        ^
    cli/command/formatter/displayutils.go:43:2: Consider pre-allocating `display` (prealloc)
        var (
        ^
    cli/command/formatter/volume.go:103:2: Consider pre-allocating `joinLabels` (prealloc)
        var joinLabels []string
        ^
    cli-plugins/manager/manager_test.go:49:2: Consider pre-allocating `dirs` (prealloc)
        var dirs []string
        ^
    cli/command/swarm/init.go:69:2: Consider pre-allocating `defaultAddrPool` (prealloc)
        var defaultAddrPool []string
        ^
    cli/command/manifest/push.go:195:2: Consider pre-allocating `blobReqs` (prealloc)
        var blobReqs []manifestBlob
        ^
    cli/command/secret/formatter.go:111:2: Consider pre-allocating `joinLabels` (prealloc)
        var joinLabels []string
        ^
    cli/command/network/formatter.go:104:2: Consider pre-allocating `joinLabels` (prealloc)
        var joinLabels []string
        ^
    cli/command/context/list.go:52:2: Consider pre-allocating `contexts` (prealloc)
        var contexts []*formatter.ClientContext
        ^
    cli/command/config/formatter.go:104:2: Consider pre-allocating `joinLabels` (prealloc)
        var joinLabels []string
        ^
    cli/command/trust/common_test.go:23:2: Consider pre-allocating `targetNames` (prealloc)
        var targetNames []string
        ^
    cli/command/service/generic_resource_opts.go:55:2: Consider pre-allocating `generic` (prealloc)
        var generic []swarm.GenericResource
        ^
    cli/command/service/generic_resource_opts.go:98:2: Consider pre-allocating `l` (prealloc)
        var l []swarm.GenericResource
        ^
    cli/command/service/opts.go:378:2: Consider pre-allocating `netAttach` (prealloc)
        var netAttach []swarm.NetworkAttachmentConfig
        ^
    cli/command/service/update.go:731:2: Consider pre-allocating `limits` (prealloc)
        var limits []*units.Ulimit
        ^
    cli/command/service/update.go:1315:2: Consider pre-allocating `newNetworks` (prealloc)
        var newNetworks []swarm.NetworkAttachmentConfig
        ^
    cli/command/service/update.go:1514:2: Consider pre-allocating `out` (prealloc)
        var out []string
        ^
    cli/compose/convert/service.go:713:2: Consider pre-allocating `ulimits` (prealloc)
        var ulimits []*units.Ulimit
        ^
    cli/compose/convert/volume.go:13:2: Consider pre-allocating `mounts` (prealloc)
        var mounts []mount.Mount
        ^
    cli/command/stack/swarm/list.go:39:2: Consider pre-allocating `stacks` (prealloc)
        var stacks []*formatter.Stack
        ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
  • Loading branch information
thaJeztah committed Nov 20, 2023
1 parent efbcdce commit d0dee3c
Show file tree
Hide file tree
Showing 26 changed files with 60 additions and 51 deletions.
2 changes: 1 addition & 1 deletion cli-plugins/manager/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func TestListPluginCandidates(t *testing.T) {
)
defer dir.Remove()

var dirs []string
dirs := make([]string, 0, 6)
for _, d := range []string{"plugins1", "nonexistent", "plugins2", "plugins3", "plugins4", "plugins5"} {
dirs = append(dirs, dir.Join(d))
}
Expand Down
2 changes: 1 addition & 1 deletion cli/command/config/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ func (c *configContext) Labels() string {
if mapLabels == nil {
return ""
}
var joinLabels []string
joinLabels := make([]string, 0, len(mapLabels))
for k, v := range mapLabels {
joinLabels = append(joinLabels, k+"="+v)
}
Expand Down
2 changes: 1 addition & 1 deletion cli/command/context/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func runList(dockerCli command.Cli, opts *listOptions) error {
var (
curContext = dockerCli.CurrentContext()
curFound bool
contexts []*formatter.ClientContext
contexts = make([]*formatter.ClientContext, 0, len(contextMap))
)
for _, rawMeta := range contextMap {
isCurrent := rawMeta.Name == curContext
Expand Down
14 changes: 7 additions & 7 deletions cli/command/formatter/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ func (c *ContainerContext) Labels() string {
return ""
}

var joinLabels []string
joinLabels := make([]string, 0, len(c.c.Labels))
for k, v := range c.c.Labels {
joinLabels = append(joinLabels, k+"="+v)
}
Expand All @@ -265,7 +265,7 @@ func (c *ContainerContext) Label(name string) string {
// If the trunc option is set, names can be truncated (ellipsized).
func (c *ContainerContext) Mounts() string {
var name string
var mounts []string
mounts := make([]string, 0, len(c.c.Mounts))
for _, m := range c.c.Mounts {
if m.Name == "" {
name = m.Source
Expand All @@ -289,7 +289,7 @@ func (c *ContainerContext) LocalVolumes() string {
}
}

return fmt.Sprintf("%d", count)
return strconv.Itoa(count)
}

// Networks returns a comma-separated string of networks that the container is
Expand All @@ -299,7 +299,7 @@ func (c *ContainerContext) Networks() string {
return ""
}

networks := []string{}
networks := make([]string, 0, len(c.c.NetworkSettings.Networks))
for k := range c.c.NetworkSettings.Networks {
networks = append(networks, k)
}
Expand All @@ -316,7 +316,7 @@ func DisplayablePorts(ports []types.Port) string {
last uint16
}
groupMap := make(map[string]*portGroup)
var result []string
var result []string //nolint:prealloc
var hostMappings []string
var groupMapKeys []string
sort.Slice(ports, func(i, j int) bool {
Expand All @@ -331,7 +331,7 @@ func DisplayablePorts(ports []types.Port) string {
hostMappings = append(hostMappings, fmt.Sprintf("%s:%d->%d/%s", port.IP, port.PublicPort, port.PrivatePort, port.Type))
continue
}
portKey = fmt.Sprintf("%s/%s", port.IP, port.Type)
portKey = port.IP + "/" + port.Type
}
group := groupMap[portKey]

Expand Down Expand Up @@ -372,7 +372,7 @@ func formGroup(key string, start, last uint16) string {
if ip != "" {
group = fmt.Sprintf("%s:%s->%s", ip, group, group)
}
return fmt.Sprintf("%s/%s", group, groupType)
return group + "/" + groupType
}

func comparePorts(i, j types.Port) bool {
Expand Down
2 changes: 1 addition & 1 deletion cli/command/formatter/displayutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func Ellipsis(s string, maxDisplayWidth int) string {
}

var (
display []int
display = make([]int, 0, len(rs))
displayWidth int
)
for _, r := range rs {
Expand Down
2 changes: 1 addition & 1 deletion cli/command/formatter/volume.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func (c *volumeContext) Labels() string {
return ""
}

var joinLabels []string
joinLabels := make([]string, 0, len(c.v.Labels))
for k, v := range c.v.Labels {
joinLabels = append(joinLabels, k+"="+v)
}
Expand Down
6 changes: 3 additions & 3 deletions cli/command/manifest/push.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,9 @@ func buildManifestDescriptor(targetRepo *registry.RepositoryInfo, imageManifest
}

func buildBlobRequestList(imageManifest types.ImageManifest, repoName reference.Named) ([]manifestBlob, error) {
var blobReqs []manifestBlob

for _, blobDigest := range imageManifest.Blobs() {
blobs := imageManifest.Blobs()
blobReqs := make([]manifestBlob, 0, len(blobs))
for _, blobDigest := range blobs {
canonical, err := reference.WithDigest(repoName, blobDigest)
if err != nil {
return nil, err
Expand Down
2 changes: 1 addition & 1 deletion cli/command/network/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ func (c *networkContext) Labels() string {
return ""
}

var joinLabels []string
joinLabels := make([]string, 0, len(c.n.Labels))
for k, v := range c.n.Labels {
joinLabels = append(joinLabels, k+"="+v)
}
Expand Down
2 changes: 1 addition & 1 deletion cli/command/secret/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ func (c *secretContext) Labels() string {
if mapLabels == nil {
return ""
}
var joinLabels []string
joinLabels := make([]string, 0, len(mapLabels))
for k, v := range mapLabels {
joinLabels = append(joinLabels, k+"="+v)
}
Expand Down
4 changes: 2 additions & 2 deletions cli/command/service/generic_resource_opts.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func ParseGenericResources(value []string) ([]swarm.GenericResource, error) {

// genericResourcesFromGRPC converts a GRPC GenericResource to a GenericResource
func genericResourcesFromGRPC(genericRes []*swarmapi.GenericResource) []swarm.GenericResource {
var generic []swarm.GenericResource
generic := make([]swarm.GenericResource, 0, len(genericRes))
for _, res := range genericRes {
var current swarm.GenericResource

Expand Down Expand Up @@ -95,7 +95,7 @@ func buildGenericResourceMap(genericRes []swarm.GenericResource) (map[string]swa
}

func buildGenericResourceList(genericRes map[string]swarm.GenericResource) []swarm.GenericResource {
var l []swarm.GenericResource
l := make([]swarm.GenericResource, 0, len(genericRes))

for _, res := range genericRes {
l = append(l, res)
Expand Down
5 changes: 3 additions & 2 deletions cli/command/service/opts.go
Original file line number Diff line number Diff line change
Expand Up @@ -378,8 +378,9 @@ func resolveNetworkID(ctx context.Context, apiClient client.NetworkAPIClient, ne
}

func convertNetworks(networks opts.NetworkOpt) []swarm.NetworkAttachmentConfig {
var netAttach []swarm.NetworkAttachmentConfig
for _, net := range networks.Value() {
nws := networks.Value()
netAttach := make([]swarm.NetworkAttachmentConfig, 0, len(nws))
for _, net := range nws {
netAttach = append(netAttach, swarm.NetworkAttachmentConfig{
Target: net.Target,
Aliases: net.Aliases,
Expand Down
13 changes: 9 additions & 4 deletions cli/command/service/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -727,8 +727,10 @@ func updateUlimits(flags *pflag.FlagSet, ulimits []*units.Ulimit) []*units.Ulimi
newUlimits[ulimit.Name] = ulimit
}
}

var limits []*units.Ulimit
if len(newUlimits) == 0 {
return nil
}
limits := make([]*units.Ulimit, 0, len(newUlimits))
for _, ulimit := range newUlimits {
limits = append(limits, ulimit)
}
Expand Down Expand Up @@ -1307,7 +1309,7 @@ func updateNetworks(ctx context.Context, apiClient client.NetworkAPIClient, flag
}

existingNetworks := make(map[string]struct{})
var newNetworks []swarm.NetworkAttachmentConfig
var newNetworks []swarm.NetworkAttachmentConfig //nolint:prealloc
for _, network := range specNetworks {
if _, exists := idsToRemove[network.Target]; exists {
continue
Expand Down Expand Up @@ -1503,10 +1505,13 @@ func updateCapabilities(flags *pflag.FlagSet, containerSpec *swarm.ContainerSpec
}

func capsList(caps map[string]bool) []string {
if len(caps) == 0 {
return nil
}
if caps[opts.AllCapabilities] {
return []string{opts.AllCapabilities}
}
var out []string
out := make([]string, 0, len(caps))
for c := range caps {
out = append(out, c)
}
Expand Down
4 changes: 2 additions & 2 deletions cli/command/stack/loader/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func getDictsFrom(configFiles []composetypes.ConfigFile) []map[string]interface{
}

func propertyWarnings(properties map[string]string) string {
var msgs []string
msgs := make([]string, 0, len(properties))
for name, description := range properties {
msgs = append(msgs, fmt.Sprintf("%s: %s", name, description))
}
Expand Down Expand Up @@ -129,7 +129,7 @@ func buildEnvironment(env []string) (map[string]string, error) {
}

func loadConfigFiles(filenames []string, stdin io.Reader) ([]composetypes.ConfigFile, error) {
var configFiles []composetypes.ConfigFile
configFiles := make([]composetypes.ConfigFile, 0, len(filenames))

for _, filename := range filenames {
configFile, err := loadConfigFile(filename, stdin)
Expand Down
2 changes: 1 addition & 1 deletion cli/command/stack/swarm/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func GetStacks(dockerCli command.Cli) ([]*formatter.Stack, error) {
ztack.Services++
}
}
var stacks []*formatter.Stack
stacks := make([]*formatter.Stack, 0, len(m))
for _, stack := range m {
stacks = append(stacks, stack)
}
Expand Down
3 changes: 1 addition & 2 deletions cli/command/swarm/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,10 @@ func newInitCommand(dockerCli command.Cli) *cobra.Command {
}

func runInit(dockerCli command.Cli, flags *pflag.FlagSet, opts initOptions) error {
var defaultAddrPool []string

client := dockerCli.Client()
ctx := context.Background()

defaultAddrPool := make([]string, 0, len(opts.defaultAddrPools))
for _, p := range opts.defaultAddrPools {
defaultAddrPool = append(defaultAddrPool, p.String())
}
Expand Down
2 changes: 1 addition & 1 deletion cli/command/system/events_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
)

func TestEventsFormat(t *testing.T) {
var evts []events.Message
var evts []events.Message //nolint:prealloc
for i, action := range []events.Action{events.ActionCreate, events.ActionStart, events.ActionAttach, events.ActionDie} {
evts = append(evts, events.Message{
Status: string(action),
Expand Down
2 changes: 1 addition & 1 deletion cli/command/trust/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func TestMatchReleasedSignaturesSortOrder(t *testing.T) {

rows := matchReleasedSignatures(targets)

var targetNames []string
targetNames := make([]string, 0, len(rows))
for _, r := range rows {
targetNames = append(targetNames, r.SignedTag)
}
Expand Down
2 changes: 1 addition & 1 deletion cli/compose/convert/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,7 @@ func convertUlimits(origUlimits map[string]*composetypes.UlimitsConfig) []*units
}
}
}
var ulimits []*units.Ulimit
ulimits := make([]*units.Ulimit, 0, len(newUlimits))
for _, ulimit := range newUlimits {
ulimits = append(ulimits, ulimit)
}
Expand Down
7 changes: 3 additions & 4 deletions cli/compose/convert/volume.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,13 @@ type volumes map[string]composetypes.VolumeConfig

// Volumes from compose-file types to engine api types
func Volumes(serviceVolumes []composetypes.ServiceVolumeConfig, stackVolumes volumes, namespace Namespace) ([]mount.Mount, error) {
var mounts []mount.Mount

mounts := make([]mount.Mount, 0, len(serviceVolumes))
for _, volumeConfig := range serviceVolumes {
mount, err := convertVolumeToMount(volumeConfig, stackVolumes, namespace)
mnt, err := convertVolumeToMount(volumeConfig, stackVolumes, namespace)
if err != nil {
return nil, err
}
mounts = append(mounts, mount)
mounts = append(mounts, mnt)
}
return mounts, nil
}
Expand Down
4 changes: 2 additions & 2 deletions cli/compose/loader/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ func GetUnsupportedProperties(configDicts ...map[string]interface{}) []string {
}

func sortedKeys(set map[string]bool) []string {
var keys []string
keys := make([]string, 0, len(set))
for key := range set {
keys = append(keys, key)
}
Expand Down Expand Up @@ -394,7 +394,7 @@ func formatInvalidKeyError(keyPrefix string, key interface{}) error {
// LoadServices produces a ServiceConfig map from a compose file Dict
// the servicesDict is not validated if directly used. Use Load() to enable validation
func LoadServices(servicesDict map[string]interface{}, workingDir string, lookupEnv template.Mapping) ([]types.ServiceConfig, error) {
var services []types.ServiceConfig
services := make([]types.ServiceConfig, 0, len(servicesDict))

for name, serviceDef := range servicesDict {
serviceConfig, err := LoadService(name, serviceDef.(map[string]interface{}), workingDir, lookupEnv)
Expand Down
2 changes: 1 addition & 1 deletion cli/context/store/metadatastore.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func (s *metadataStore) list() ([]Metadata, error) {
}
return nil, err
}
var res []Metadata
res := make([]Metadata, 0, len(ctxDirs))
for _, dir := range ctxDirs {
c, err := s.getByID(contextdir(dir))
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cli/context/store/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func Names(s Lister) ([]string, error) {
if err != nil {
return nil, err
}
var names []string
names := make([]string, 0, len(list))
for _, item := range list {
names = append(names, item.Name)
}
Expand Down
10 changes: 7 additions & 3 deletions cli/manifest/types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,18 @@ func PlatformSpecFromOCI(p *ocispec.Platform) *manifestlist.PlatformSpec {

// Blobs returns the digests for all the blobs referenced by this manifest
func (i ImageManifest) Blobs() []digest.Digest {
digests := []digest.Digest{}
var digests []digest.Digest
switch {
case i.SchemaV2Manifest != nil:
for _, descriptor := range i.SchemaV2Manifest.References() {
refs := i.SchemaV2Manifest.References()
digests = make([]digest.Digest, 0, len(refs))
for _, descriptor := range refs {
digests = append(digests, descriptor.Digest)
}
case i.OCIManifest != nil:
for _, descriptor := range i.OCIManifest.References() {
refs := i.OCIManifest.References()
digests = make([]digest.Digest, 0, len(refs))
for _, descriptor := range refs {
digests = append(digests, descriptor.Digest)
}
}
Expand Down
9 changes: 5 additions & 4 deletions opts/throttledevice.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,8 @@ type ThrottledeviceOpt struct {

// NewThrottledeviceOpt creates a new ThrottledeviceOpt
func NewThrottledeviceOpt(validator ValidatorThrottleFctType) ThrottledeviceOpt {
values := []*blkiodev.ThrottleDevice{}
return ThrottledeviceOpt{
values: values,
values: []*blkiodev.ThrottleDevice{},
validator: validator,
}
}
Expand All @@ -85,7 +84,7 @@ func (opt *ThrottledeviceOpt) Set(val string) error {

// String returns ThrottledeviceOpt values as a string.
func (opt *ThrottledeviceOpt) String() string {
var out []string
out := make([]string, 0, len(opt.values))
for _, v := range opt.values {
out = append(out, v.String())
}
Expand All @@ -95,7 +94,9 @@ func (opt *ThrottledeviceOpt) String() string {

// GetList returns a slice of pointers to ThrottleDevices.
func (opt *ThrottledeviceOpt) GetList() []*blkiodev.ThrottleDevice {
return append([]*blkiodev.ThrottleDevice{}, opt.values...)
out := make([]*blkiodev.ThrottleDevice, 0, len(opt.values))
copy(out, opt.values)
return out
}

// Type returns the option type
Expand Down
4 changes: 2 additions & 2 deletions opts/ulimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func (o *UlimitOpt) Set(val string) error {

// String returns Ulimit values as a string. Values are sorted by name.
func (o *UlimitOpt) String() string {
var out []string
out := make([]string, 0, len(*o.values))
for _, v := range *o.values {
out = append(out, v.String())
}
Expand All @@ -44,7 +44,7 @@ func (o *UlimitOpt) String() string {

// GetList returns a slice of pointers to Ulimits. Values are sorted by name.
func (o *UlimitOpt) GetList() []*units.Ulimit {
var ulimits []*units.Ulimit
ulimits := make([]*units.Ulimit, 0, len(*o.values))
for _, v := range *o.values {
ulimits = append(ulimits, v)
}
Expand Down
Loading

0 comments on commit d0dee3c

Please sign in to comment.