modernize: Use maps.Copy instead of for loops

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
This commit is contained in:
Paweł Gronowski
2025-12-15 18:18:12 +01:00
parent ff33808a79
commit cdce8f4f92
28 changed files with 66 additions and 123 deletions

View File

@@ -3,6 +3,7 @@ package dockerfile
import (
"fmt"
"io"
"maps"
"sort"
)
@@ -47,12 +48,8 @@ func NewBuildArgs(argsFromOptions map[string]*string) *BuildArgs {
// Clone returns a copy of the BuildArgs type
func (b *BuildArgs) Clone() *BuildArgs {
result := NewBuildArgs(b.argsFromOptions)
for k, v := range b.allowedBuildArgs {
result.allowedBuildArgs[k] = v
}
for k, v := range b.allowedMetaArgs {
result.allowedMetaArgs[k] = v
}
maps.Copy(result.allowedBuildArgs, b.allowedBuildArgs)
maps.Copy(result.allowedMetaArgs, b.allowedMetaArgs)
for k := range b.referencedArgs {
result.referencedArgs[k] = struct{}{}
}

View File

@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"maps"
"math"
"net"
"net/netip"
@@ -261,15 +262,11 @@ func (c *containerConfig) labels() map[string]string {
)
// base labels are those defined in the spec.
for k, v := range c.spec().Labels {
labels[k] = v
}
maps.Copy(labels, c.spec().Labels)
// we then apply the overrides from the task, which may be set via the
// orchestrator.
for k, v := range c.task.Annotations.Labels {
labels[k] = v
}
maps.Copy(labels, c.task.Annotations.Labels)
// finally, we apply the system labels, which override all labels.
for k, v := range system {
@@ -367,9 +364,7 @@ func convertMount(m api.Mount) enginemount.Mount {
}
if m.VolumeOptions.Labels != nil {
mount.VolumeOptions.Labels = make(map[string]string, len(m.VolumeOptions.Labels))
for k, v := range m.VolumeOptions.Labels {
mount.VolumeOptions.Labels[k] = v
}
maps.Copy(mount.VolumeOptions.Labels, m.VolumeOptions.Labels)
}
if m.VolumeOptions.DriverConfig != nil {
mount.VolumeOptions.DriverConfig = &enginemount.Driver{
@@ -377,9 +372,7 @@ func convertMount(m api.Mount) enginemount.Mount {
}
if m.VolumeOptions.DriverConfig.Options != nil {
mount.VolumeOptions.DriverConfig.Options = make(map[string]string, len(m.VolumeOptions.DriverConfig.Options))
for k, v := range m.VolumeOptions.DriverConfig.Options {
mount.VolumeOptions.DriverConfig.Options[k] = v
}
maps.Copy(mount.VolumeOptions.DriverConfig.Options, m.VolumeOptions.DriverConfig.Options)
}
}
}

View File

@@ -3,6 +3,7 @@ package daemon
import (
"context"
"fmt"
"maps"
"runtime"
"strings"
"time"
@@ -109,9 +110,7 @@ func merge(userConf, imageConf *containertypes.Config) error {
if len(userConf.Volumes) == 0 {
userConf.Volumes = imageConf.Volumes
} else {
for k, v := range imageConf.Volumes {
userConf.Volumes[k] = v
}
maps.Copy(userConf.Volumes, imageConf.Volumes)
}
if userConf.StopSignal == "" {

View File

@@ -5,6 +5,7 @@ import (
"encoding/json"
stderrors "errors"
"fmt"
"maps"
"net"
"net/netip"
"net/url"
@@ -587,9 +588,7 @@ func configValuesSet(config map[string]any) map[string]any {
flatten := make(map[string]any)
for k, v := range config {
if m, isMap := v.(map[string]any); isMap && !flatOptions[k] {
for km, vm := range m {
flatten[km] = vm
}
maps.Copy(flatten, m)
continue
}

View File

@@ -2,6 +2,7 @@ package container
import (
"context"
"maps"
"runtime"
"sync"
@@ -91,9 +92,7 @@ func NewExecStore() *ExecStore {
func (e *ExecStore) Commands() map[string]*ExecConfig {
e.mu.RLock()
byID := make(map[string]*ExecConfig, len(e.byID))
for id, config := range e.byID {
byID[id] = config
}
maps.Copy(byID, e.byID)
e.mu.RUnlock()
return byID
}

View File

@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"maps"
"net/netip"
"os"
"runtime"
@@ -413,9 +414,7 @@ func (daemon *Daemon) allocateNetwork(ctx context.Context, cfg *config.Config, c
// An intermediate map is necessary because "connectToNetwork" modifies "container.NetworkSettings.Networks"
networks := make(map[string]*network.EndpointSettings)
for n, epConf := range ctr.NetworkSettings.Networks {
networks[n] = epConf
}
maps.Copy(networks, ctr.NetworkSettings.Networks)
for netName, epConf := range networks {
cleanOperationalData(epConf)
if err := daemon.connectToNetwork(ctx, cfg, ctr, netName, epConf); err != nil {

View File

@@ -2,6 +2,7 @@ package containerd
import (
"context"
"maps"
c8dimages "github.com/containerd/containerd/v2/core/images"
"github.com/moby/moby/api/types/events"
@@ -45,7 +46,5 @@ func copyAttributes(attributes, labels map[string]string) {
if labels == nil {
return
}
for k, v := range labels {
attributes[k] = v
}
maps.Copy(attributes, labels)
}

View File

@@ -2,6 +2,7 @@ package daemon
import (
"context"
"maps"
"strconv"
"strings"
"time"
@@ -94,9 +95,7 @@ func copyAttributes(attributes, labels map[string]string) {
if labels == nil {
return
}
for k, v := range labels {
attributes[k] = v
}
maps.Copy(attributes, labels)
}
// ProcessClusterNotifications gets changes from store and add them to event list

View File

@@ -2,6 +2,7 @@ package images
import (
"context"
"maps"
"github.com/moby/moby/api/types/events"
"github.com/moby/moby/v2/daemon/server/imagebackend"
@@ -32,7 +33,5 @@ func copyAttributes(attributes, labels map[string]string) {
if labels == nil {
return
}
for k, v := range labels {
attributes[k] = v
}
maps.Copy(attributes, labels)
}

View File

@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"maps"
"runtime"
"time"
@@ -35,9 +36,7 @@ func (daemon *Daemon) ContainerInspect(ctx context.Context, name string, options
// TODO(thaJeztah): do we need a deep copy here? Otherwise we could use maps.Clone (see https://github.com/moby/moby/commit/7917a36cc787ada58987320e67cc6d96858f3b55)
ports := make(networktypes.PortMap, len(ctr.NetworkSettings.Ports))
for k, pm := range ctr.NetworkSettings.Ports {
ports[k] = pm
}
maps.Copy(ports, ctr.NetworkSettings.Ports)
apiNetworks := make(map[string]*networktypes.EndpointSettings)
for nwName, epConf := range ctr.NetworkSettings.Networks {

View File

@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
"maps"
"net/netip"
"strconv"
"strings"
@@ -213,9 +214,7 @@ func (b *Builder) Prune(ctx context.Context, opts buildbackend.CachePruneOptions
validFilters["until"] = true
validFilters["label"] = true // TODO(tiborvass): handle label
validFilters["label!"] = true // TODO(tiborvass): handle label!
for k, v := range cacheFields {
validFilters[k] = v
}
maps.Copy(validFilters, cacheFields)
if err := opts.Filters.Validate(validFilters); err != nil {
return 0, nil, err
}

View File

@@ -6,6 +6,7 @@ package filters
import (
"encoding/json"
"maps"
"regexp"
"strings"
)
@@ -280,9 +281,7 @@ func (args Args) Clone() (newArgs Args) {
var mm map[string]bool
if m != nil {
mm = make(map[string]bool, len(m))
for kk, v := range m {
mm[kk] = v
}
maps.Copy(mm, m)
}
newArgs.fields[k] = mm
}

View File

@@ -3,6 +3,7 @@ package cnmallocator
import (
"context"
"fmt"
"maps"
"net"
"net/netip"
"slices"
@@ -725,14 +726,10 @@ func (na *cnmNetworkAllocator) allocateDriverState(d *networkDriver, n *api.Netw
// reconcile the driver specific options from the network spec
// and from the operational state retrieved from the store
if n.Spec.DriverConfig != nil {
for k, v := range n.Spec.DriverConfig.Options {
options[k] = v
}
maps.Copy(options, n.Spec.DriverConfig.Options)
}
if n.DriverState != nil {
for k, v := range n.DriverState.Options {
options[k] = v
}
maps.Copy(options, n.DriverState.Options)
}
// Construct IPAM data for driver consumption.

View File

@@ -1036,9 +1036,7 @@ func (ep *Endpoint) getEtcHostsAddrs() []netip.Addr {
// in a Dictionary of Key-Value pair
func EndpointOptionGeneric(generic map[string]any) EndpointOption {
return func(ep *Endpoint) {
for k, v := range generic {
ep.generic[k] = v
}
maps.Copy(ep.generic, generic)
}
}

View File

@@ -476,9 +476,7 @@ func (n *Network) applyConfigurationTo(to *Network) error {
}
if len(n.generic) > 0 {
to.generic = options.Generic{}
for k, v := range n.generic {
to.generic[k] = v
}
maps.Copy(to.generic, n.generic)
}
// Network drivers only see generic flags. So, make sure they match.
@@ -525,15 +523,11 @@ func (n *Network) CopyTo(o datastore.KVObject) error {
if dstN.labels == nil {
dstN.labels = make(map[string]string, len(n.labels))
}
for k, v := range n.labels {
dstN.labels[k] = v
}
maps.Copy(dstN.labels, n.labels)
if n.ipamOptions != nil {
dstN.ipamOptions = make(map[string]string, len(n.ipamOptions))
for k, v := range n.ipamOptions {
dstN.ipamOptions[k] = v
}
maps.Copy(dstN.ipamOptions, n.ipamOptions)
}
for _, c := range n.ipamV4Config {
@@ -553,9 +547,7 @@ func (n *Network) CopyTo(o datastore.KVObject) error {
}
dstN.generic = options.Generic{}
for k, v := range n.generic {
dstN.generic[k] = v
}
maps.Copy(dstN.generic, n.generic)
return nil
}
@@ -793,9 +785,7 @@ func NetworkOptionGeneric(generic map[string]any) NetworkOption {
if val, ok := generic[netlabel.Internal]; ok {
n.internal = val.(bool)
}
for k, v := range generic {
n.generic[k] = v
}
maps.Copy(n.generic, generic)
}
}
@@ -1875,9 +1865,7 @@ func (n *Network) Labels() map[string]string {
defer n.mu.Unlock()
lbls := make(map[string]string, len(n.labels))
for k, v := range n.labels {
lbls[k] = v
}
maps.Copy(lbls, n.labels)
return lbls
}

View File

@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"maps"
"net"
"net/netip"
"slices"
@@ -126,9 +127,7 @@ func (sb *Sandbox) Labels() map[string]any {
sb.mu.Lock()
defer sb.mu.Unlock()
opts := make(map[string]any, len(sb.config.generic))
for k, v := range sb.config.generic {
opts[k] = v
}
maps.Copy(opts, sb.config.generic)
return opts
}
@@ -280,9 +279,7 @@ func (sb *Sandbox) UpdateLabels(labels map[string]any) {
if sb.config.generic == nil {
sb.config.generic = make(map[string]any, len(labels))
}
for k, v := range labels {
sb.config.generic[k] = v
}
maps.Copy(sb.config.generic, labels)
}
func (sb *Sandbox) MarshalJSON() ([]byte, error) {

View File

@@ -4,6 +4,7 @@ package fluentd
import (
"context"
"maps"
"math"
"net/url"
"strconv"
@@ -120,9 +121,7 @@ func (f *fluentd) Log(msg *logger.Message) error {
"source": msg.Source,
"log": string(msg.Line),
}
for k, v := range f.extra {
data[k] = v
}
maps.Copy(data, f.extra)
if msg.PLogMetaData != nil {
data["partial_message"] = "true"
data["partial_id"] = msg.PLogMetaData.ID

View File

@@ -3,6 +3,7 @@ package fluentd
import (
"bufio"
"context"
"maps"
"net"
"path/filepath"
"runtime"
@@ -350,9 +351,7 @@ func TestReadWriteTimeoutsAreEffective(t *testing.T) {
"fluentd-buffer-limit": "1",
}
// Update the config with test specific configs.
for k, v := range tc.cfg {
cfg[k] = v
}
maps.Copy(cfg, tc.cfg)
f, err := New(logger.Info{
ContainerName: "/test-container",

View File

@@ -5,6 +5,7 @@ package journald
import (
"errors"
"fmt"
"maps"
"strconv"
"sync/atomic"
"time"
@@ -129,9 +130,7 @@ func newJournald(info logger.Info) (*journald, error) {
if err != nil {
return nil, err
}
for k, v := range extraAttrs {
vars[k] = v
}
maps.Copy(vars, extraAttrs)
return &journald{
epoch: epoch,
vars: vars,
@@ -159,9 +158,7 @@ func validateLogOpt(cfg map[string]string) error {
func (s *journald) Log(msg *logger.Message) error {
vars := map[string]string{}
for k, v := range s.vars {
vars[k] = v
}
maps.Copy(vars, s.vars)
if !msg.Timestamp.IsZero() {
vars[fieldSyslogTimestamp] = msg.Timestamp.Format(time.RFC3339Nano)
}

View File

@@ -1,5 +1,7 @@
package logger
import "maps"
var externalValidators []LogOptValidator
// RegisterExternalValidator adds the validator to the list of external validators.
@@ -14,9 +16,7 @@ func RegisterExternalValidator(v LogOptValidator) {
// not be exposed as a usable log driver to the API.
// This should only be called on package initialization.
func AddBuiltinLogOpts(opts map[string]bool) {
for k, v := range opts {
builtInLogOpts[k] = v
}
maps.Copy(builtInLogOpts, opts)
}
func validateExternal(cfg map[string]string) error {

View File

@@ -304,9 +304,7 @@ func (daemon *Daemon) createNetwork(ctx context.Context, cfg *config.Config, cre
}
networkOptions := make(map[string]string)
for k, v := range create.Options {
networkOptions[k] = v
}
maps.Copy(networkOptions, create.Options)
if defaultOpts, ok := cfg.DefaultNetworkOpts[driver]; create.ConfigFrom == nil && ok {
for k, v := range defaultOpts {
if _, ok := networkOptions[k]; !ok {

View File

@@ -3,6 +3,7 @@ package daemon
import (
"context"
"fmt"
"maps"
"os"
"path/filepath"
"strconv"
@@ -985,9 +986,7 @@ func WithSysctls(c *container.Container) coci.SpecOpts {
}
// We merge the sysctls injected above with the HostConfig (latter takes
// precedence for backwards-compatibility reasons).
for k, v := range c.HostConfig.Sysctls {
s.Linux.Sysctl[k] = v
}
maps.Copy(s.Linux.Sysctl, c.HostConfig.Sysctls)
return nil
}
}

View File

@@ -102,9 +102,7 @@ func newServiceConfig(options ServiceOptions) (*serviceConfig, error) {
// copy constructs a new ServiceConfig with a copy of the configuration in config.
func (config *serviceConfig) copy() *registry.ServiceConfig {
ic := make(map[string]*registry.IndexInfo)
for key, value := range config.IndexConfigs {
ic[key] = value
}
maps.Copy(ic, config.IndexConfigs)
return &registry.ServiceConfig{
InsecureRegistryCIDRs: slices.Clone(config.InsecureRegistryCIDRs),
IndexConfigs: ic,

View File

@@ -1,6 +1,7 @@
package container
import (
"maps"
"strings"
"testing"
@@ -315,9 +316,7 @@ func TestHandleSysctlBC(t *testing.T) {
NetworkMode: container.NetworkMode(tc.networkMode),
Sysctls: map[string]string{},
}
for k, v := range tc.sysctls {
hostCfg.Sysctls[k] = v
}
maps.Copy(hostCfg.Sysctls, tc.sysctls)
netCfg := &network.NetworkingConfig{
EndpointsConfig: tc.epConfig,
}

View File

@@ -3,6 +3,7 @@ package drivers
import (
"context"
"errors"
"maps"
"strings"
"time"
@@ -169,8 +170,6 @@ func (a *volumeAdapter) CreatedAt() (time.Time, error) {
func (a *volumeAdapter) Status() map[string]any {
out := make(map[string]any, len(a.status))
for k, v := range a.status {
out[k] = v
}
maps.Copy(out, a.status)
return out
}

View File

@@ -3,6 +3,7 @@ package service
import (
"context"
"fmt"
"maps"
"net"
"os"
"path/filepath"
@@ -39,9 +40,7 @@ func (v volumeWrapper) Options() map[string]string {
return nil
}
options := make(map[string]string, len(v.options))
for key, value := range v.options {
options[key] = value
}
maps.Copy(options, v.options)
return options
}
@@ -51,9 +50,7 @@ func (v volumeWrapper) Labels() map[string]string {
}
labels := make(map[string]string, len(v.labels))
for key, value := range v.labels {
labels[key] = value
}
maps.Copy(labels, v.labels)
return labels
}

View File

@@ -3,6 +3,7 @@ package daemon
import (
"context"
"encoding/hex"
"maps"
"os"
"path/filepath"
"sort"
@@ -97,9 +98,7 @@ func (daemon *Daemon) registerMountPoints(ctr *container.Container, defaultReadO
}
// 1. Read already configured mount points.
for destination, point := range ctr.MountPoints {
mountPoints[destination] = point
}
maps.Copy(mountPoints, ctr.MountPoints)
// 2. Read volumes from other containers.
for _, v := range ctr.HostConfig.VolumesFrom {

View File

@@ -1,6 +1,7 @@
package labelstore
import (
"maps"
"sync"
"github.com/opencontainers/go-digest"
@@ -40,9 +41,7 @@ func (s *InMemory) Update(dgst digest.Digest, update map[string]string) (map[str
if !ok {
labels = map[string]string{}
}
for k, v := range update {
labels[k] = v
}
maps.Copy(labels, update)
if s.labels == nil {
s.labels = map[digest.Digest]map[string]string{}
}