From dad9c40c736d55dee05d4b74e94db610dd119ce2 Mon Sep 17 00:00:00 2001 From: Dmitriy Matrenichev Date: Sat, 6 Jul 2024 11:31:55 +0300 Subject: [PATCH] chore: simplify code - replace `interface{}` with `any` using `gofmt -r 'interface{} -> any -w'` - replace `a = []T{}` with `var a []T` where possible. - replace `a = []T{}` with `a = make([]T, 0, len(b))` where possible. Signed-off-by: Dmitriy Matrenichev --- cmd/installer/pkg/install/manifest.go | 2 +- cmd/talosctl/cmd/mgmt/dhcpd_launch_linux.go | 2 +- cmd/talosctl/cmd/mgmt/gen/csr.go | 2 +- cmd/talosctl/cmd/mgmt/gen/keypair.go | 4 +- cmd/talosctl/cmd/talos/disks.go | 4 +- cmd/talosctl/cmd/talos/diskusage.go | 4 +- cmd/talosctl/cmd/talos/etcd.go | 12 ++-- cmd/talosctl/cmd/talos/events.go | 22 +++---- cmd/talosctl/cmd/talos/netstat.go | 16 ++--- cmd/talosctl/cmd/talos/output/json.go | 6 +- cmd/talosctl/cmd/talos/output/table.go | 6 +- cmd/talosctl/cmd/talos/processes.go | 2 +- cmd/talosctl/pkg/mgmt/helpers/wireguard.go | 3 +- cmd/talosctl/pkg/talos/helpers/error.go | 2 +- cmd/talosctl/pkg/talos/yamlstrip/yamlstrip.go | 3 +- hack/cloud-image-uploader/aws.go | 2 +- hack/docgen/main.go | 7 +- internal/app/init/main.go | 2 +- .../server/v1alpha1/v1alpha1_server.go | 7 +- .../machined/pkg/adapters/k8s/static_pod.go | 2 +- .../pkg/adapters/k8s/static_pod_status.go | 2 +- .../pkg/controllers/cluster/node_identity.go | 2 +- .../cri/seccomp_profile_file_test.go | 6 +- .../controllers/cri/seccomp_profile_test.go | 12 ++-- .../machined/pkg/controllers/files/etcfile.go | 4 +- .../serviceaccount/crd_controller.go | 10 +-- .../pkg/controllers/kubespan/identity.go | 2 +- .../pkg/controllers/network/address_event.go | 2 +- .../controllers/network/link_status_test.go | 2 +- .../controllers/network/platform_config.go | 66 +++++++++---------- .../pkg/controllers/runtime/events_sink.go | 3 +- .../runtime/extension_service_test.go | 7 +- .../pkg/controllers/runtime/kmsg_log.go | 2 +- .../controllers/runtime/kmsg_log_config.go | 2 +- .../pkg/controllers/runtime/kmsg_log_test.go | 2 +- .../app/machined/pkg/controllers/utils.go | 2 +- .../app/machined/pkg/runtime/controller.go | 2 +- internal/app/machined/pkg/runtime/logging.go | 2 +- .../machined/pkg/runtime/logging/circular.go | 4 +- .../machined/pkg/runtime/logging/extract.go | 2 +- .../pkg/runtime/logging/extract_test.go | 10 +-- .../pkg/runtime/logging/sender_jsonlines.go | 2 +- internal/app/machined/pkg/runtime/state.go | 2 +- .../pkg/runtime/v1alpha1/platform/aws/aws.go | 2 +- .../runtime/v1alpha1/platform/azure/azure.go | 2 +- .../platform/digitalocean/digitalocean.go | 2 +- .../v1alpha1/platform/equinixmetal/equinix.go | 2 +- .../v1alpha1/platform/hcloud/hcloud.go | 2 +- .../v1alpha1/platform/scaleway/scaleway.go | 2 +- .../runtime/v1alpha1/platform/vultr/vultr.go | 2 +- .../runtime/v1alpha1/v1alpha1_controller.go | 10 +-- .../v1alpha1/v1alpha1_controller_test.go | 10 +-- .../v1alpha1/v1alpha1_sequencer_tasks.go | 4 +- .../app/machined/pkg/system/events/events.go | 4 +- .../machined/pkg/system/events/events_test.go | 3 +- .../system/runner/containerd/containerd.go | 4 +- .../runner/containerd/containerd_test.go | 2 +- .../system/runner/goroutine/goroutine_test.go | 2 +- .../pkg/system/runner/process/process_test.go | 2 +- .../pkg/system/runner/restart/restart_test.go | 2 +- .../app/machined/pkg/system/service_runner.go | 4 +- .../pkg/system/service_runner_test.go | 2 +- .../app/machined/pkg/system/services/etcd.go | 2 +- .../machined/pkg/system/services/extension.go | 2 +- .../pkg/system/services/mocks/snapshotter.go | 40 +++++------ internal/app/syslogd/syslogd_test.go | 2 +- internal/integration/api/serviceaccount.go | 6 +- internal/integration/cli/diskusage.go | 2 +- internal/integration/cli/gen.go | 6 +- internal/integration/cli/machineconfig.go | 6 +- internal/integration/cli/patch.go | 4 +- internal/pkg/configuration/configuration.go | 2 +- internal/pkg/containers/container.go | 3 +- .../containers/containerd/containerd_test.go | 4 +- internal/pkg/containers/cri/cri.go | 2 +- internal/pkg/containers/cri/cri_test.go | 2 +- internal/pkg/cri/cri_test.go | 4 +- internal/pkg/discovery/registry/kubernetes.go | 4 +- internal/pkg/encryption/encryption.go | 2 +- internal/pkg/mount/system.go | 2 +- internal/pkg/secureboot/uki/assemble.go | 2 +- internal/pkg/tui/components/form.go | 12 ++-- internal/pkg/tui/components/table.go | 10 +-- internal/pkg/tui/installer/installer.go | 3 +- internal/pkg/tui/installer/state.go | 8 +-- pkg/argsbuilder/argsbuilder_args.go | 2 +- pkg/cli/output.go | 4 +- pkg/cluster/kubernetes/talos_managed.go | 6 +- pkg/cluster/kubernetes/upgrade.go | 2 +- pkg/grpc/codec/codec.go | 4 +- pkg/grpc/factory/factory.go | 2 +- pkg/grpc/middleware/auth/basic/token.go | 2 +- .../auth/basic/username_and_password.go | 2 +- pkg/grpc/middleware/authz/authorizer.go | 8 +-- pkg/grpc/middleware/authz/injector.go | 8 +-- pkg/grpc/middleware/authz/metadata.go | 2 +- pkg/grpc/middleware/log/log.go | 4 +- pkg/kubeconfig/generate.go | 2 +- pkg/machinery/client/client.go | 52 +++++++-------- pkg/machinery/client/config/config.go | 3 +- .../client/grpc_connection_wrapper.go | 2 +- pkg/machinery/client/inspect.go | 2 +- pkg/machinery/client/reply.go | 2 +- pkg/machinery/client/resources.go | 2 +- .../compatibility/talos12/talos12.go | 2 +- .../compatibility/talos13/talos13.go | 2 +- .../compatibility/talos14/talos14.go | 2 +- .../compatibility/talos15/talos15.go | 2 +- .../compatibility/talos16/talos16.go | 2 +- .../compatibility/talos17/talos17.go | 2 +- .../compatibility/talos18/talos18.go | 2 +- pkg/machinery/config/config/cluster.go | 4 +- pkg/machinery/config/config/machine.go | 8 +-- .../internal/decoder/unknown_keys.go | 18 ++--- pkg/machinery/config/configpatcher/load.go | 2 +- .../config/configpatcher/load_test.go | 4 +- pkg/machinery/config/encoder/documentation.go | 10 +-- pkg/machinery/config/encoder/encoder.go | 10 +-- pkg/machinery/config/encoder/encoder_test.go | 8 +-- pkg/machinery/config/generate/init.go | 12 ++-- .../v1alpha1/v1alpha1_admissionplugin.go | 2 +- .../v1alpha1/v1alpha1_apiserverconfig.go | 8 +-- .../types/v1alpha1/v1alpha1_examples.go | 38 +++++------ .../config/types/v1alpha1/v1alpha1_marshal.go | 4 +- .../types/v1alpha1/v1alpha1_provider.go | 12 ++-- .../config/types/v1alpha1/v1alpha1_types.go | 24 +++---- .../types/v1alpha1/v1alpha1_unstructured.go | 14 ++-- .../v1alpha1/v1alpha1_unstructured_test.go | 8 +-- .../v1alpha1/v1alpha1_validation_test.go | 2 +- pkg/machinery/formatters/formatters.go | 6 +- .../resources/config/machine_config.go | 2 +- .../resources/config/machine_type.go | 4 +- .../resources/cri/deep_copy.generated.go | 2 +- .../resources/cri/seccomp_profile.go | 4 +- .../resources/k8s/admissioncontrol_config.go | 4 +- .../resources/k8s/auditpolicy_config.go | 2 +- .../resources/k8s/deep_copy.generated.go | 6 +- pkg/machinery/resources/k8s/manifest.go | 4 +- pkg/machinery/resources/k8s/static_pod.go | 2 +- .../resources/k8s/static_pod_status.go | 2 +- .../resources/network/dns_upstream.go | 2 +- pkg/makefs/vfat.go | 2 +- pkg/provision/providers/docker/node.go | 3 +- pkg/provision/providers/vm/launch.go | 2 +- 144 files changed, 410 insertions(+), 403 deletions(-) diff --git a/cmd/installer/pkg/install/manifest.go b/cmd/installer/pkg/install/manifest.go index 099f0f1a0b..2cf68d38f6 100644 --- a/cmd/installer/pkg/install/manifest.go +++ b/cmd/installer/pkg/install/manifest.go @@ -129,7 +129,7 @@ func NewManifest(mode Mode, uefiOnlyBoot bool, bootLoaderPresent bool, opts *Opt manifest.Targets[opts.Disk] = []*Target{} } - targets := []*Target{} + var targets []*Target // create GRUB BIOS+UEFI partitions, or only one big EFI partition if not using GRUB if !uefiOnlyBoot { diff --git a/cmd/talosctl/cmd/mgmt/dhcpd_launch_linux.go b/cmd/talosctl/cmd/mgmt/dhcpd_launch_linux.go index ab31f1fd0f..20228b0db2 100644 --- a/cmd/talosctl/cmd/mgmt/dhcpd_launch_linux.go +++ b/cmd/talosctl/cmd/mgmt/dhcpd_launch_linux.go @@ -29,7 +29,7 @@ var dhcpdLaunchCmd = &cobra.Command{ Args: cobra.NoArgs, Hidden: true, RunE: func(cmd *cobra.Command, args []string) error { - ips := []net.IP{} + var ips []net.IP for _, ip := range strings.Split(dhcpdLaunchCmdFlags.addr, ",") { ips = append(ips, net.ParseIP(ip)) diff --git a/cmd/talosctl/cmd/mgmt/gen/csr.go b/cmd/talosctl/cmd/mgmt/gen/csr.go index 5efaa2eb4c..2f3a7048d6 100644 --- a/cmd/talosctl/cmd/mgmt/gen/csr.go +++ b/cmd/talosctl/cmd/mgmt/gen/csr.go @@ -49,7 +49,7 @@ var genCSRCmd = &cobra.Command{ return fmt.Errorf("error parsing ECDSA key: %s", err) } - opts := []x509.Option{} + var opts []x509.Option parsed := net.ParseIP(genCSRCmdFlags.ip) if parsed == nil { diff --git a/cmd/talosctl/cmd/mgmt/gen/keypair.go b/cmd/talosctl/cmd/mgmt/gen/keypair.go index 7ac8c8e488..88d29371a4 100644 --- a/cmd/talosctl/cmd/mgmt/gen/keypair.go +++ b/cmd/talosctl/cmd/mgmt/gen/keypair.go @@ -20,14 +20,14 @@ var genKeypairCmdFlags struct { organization string } -// genKeypairCmd represents the `gen keypair` command. var genKeypairCmd = &cobra.Command{ Use: "keypair", Short: "Generates an X.509 Ed25519 key pair", Long: ``, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - opts := []x509.Option{} + var opts []x509.Option + if genKeypairCmdFlags.ip != "" { parsed := net.ParseIP(genKeypairCmdFlags.ip) if parsed == nil { diff --git a/cmd/talosctl/cmd/talos/disks.go b/cmd/talosctl/cmd/talos/disks.go index 45d3ba3d02..b5b757cf7e 100644 --- a/cmd/talosctl/cmd/talos/disks.go +++ b/cmd/talosctl/cmd/talos/disks.go @@ -92,7 +92,7 @@ func printDisks(ctx context.Context, c *client.Client) error { } } - args := []interface{}{} + var args []any if node != "" { args = append(args, node) @@ -110,7 +110,7 @@ func printDisks(ctx context.Context, c *client.Client) error { isSystemDisk = "*" } - args = append(args, []interface{}{ + args = append(args, []any{ getWithPlaceholder(disk.DeviceName), getWithPlaceholder(disk.Model), getWithPlaceholder(disk.Serial), diff --git a/cmd/talosctl/cmd/talos/diskusage.go b/cmd/talosctl/cmd/talos/diskusage.go index 40dbe3493d..5a05f20003 100644 --- a/cmd/talosctl/cmd/talos/diskusage.go +++ b/cmd/talosctl/cmd/talos/diskusage.go @@ -89,7 +89,7 @@ var duCmd = &cobra.Command{ size := stringifySize(info.Size) - args := []interface{}{ + args := []any{ size, info.RelativeName, } @@ -109,7 +109,7 @@ var duCmd = &cobra.Command{ if multipleNodes { pattern = "%s\t%s\t%s\n" - args = append([]interface{}{node}, args...) + args = append([]any{node}, args...) } fmt.Fprintf(w, pattern, args...) diff --git a/cmd/talosctl/cmd/talos/etcd.go b/cmd/talosctl/cmd/talos/etcd.go index 021b77f7ae..d00c36c917 100644 --- a/cmd/talosctl/cmd/talos/etcd.go +++ b/cmd/talosctl/cmd/talos/etcd.go @@ -67,12 +67,12 @@ func displayAlarms(messages []alarmMessage) error { fmt.Fprintln(w, header) } - args := []interface{}{ + args := []any{ etcdresource.FormatMemberID(alarm.GetMemberId()), alarm.GetAlarm().String(), } if node != "" { - args = append([]interface{}{node}, args...) + args = append([]any{node}, args...) } fmt.Fprintf(w, pattern, args...) @@ -233,7 +233,7 @@ var etcdMemberListCmd = &cobra.Command{ } } - args := []interface{}{ + args := []any{ etcdresource.FormatMemberID(member.Id), member.Hostname, strings.Join(member.PeerUrls, ","), @@ -241,7 +241,7 @@ var etcdMemberListCmd = &cobra.Command{ member.IsLearner, } if node != "" { - args = append([]interface{}{node}, args...) + args = append([]any{node}, args...) } fmt.Fprintf(w, pattern, args...) @@ -292,7 +292,7 @@ var etcdStatusCmd = &cobra.Command{ ratio = float64(message.GetMemberStatus().GetDbSizeInUse()) / float64(message.GetMemberStatus().GetDbSize()) * 100.0 } - args := []interface{}{ + args := []any{ etcdresource.FormatMemberID(message.GetMemberStatus().GetMemberId()), humanize.Bytes(uint64(message.GetMemberStatus().GetDbSize())), humanize.Bytes(uint64(message.GetMemberStatus().GetDbSizeInUse())), @@ -305,7 +305,7 @@ var etcdStatusCmd = &cobra.Command{ strings.Join(message.GetMemberStatus().GetErrors(), ", "), } if node != "" { - args = append([]interface{}{node}, args...) + args = append([]any{node}, args...) } fmt.Fprintf(w, pattern, args...) diff --git a/cmd/talosctl/cmd/talos/events.go b/cmd/talosctl/cmd/talos/events.go index 86c4b3fdf1..217be5f6cb 100644 --- a/cmd/talosctl/cmd/talos/events.go +++ b/cmd/talosctl/cmd/talos/events.go @@ -38,7 +38,7 @@ var eventsCmd = &cobra.Command{ w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0) fmt.Fprintln(w, "NODE\tID\tEVENT\tACTOR\tSOURCE\tMESSAGE") - opts := []client.EventsOptionFunc{} + var opts []client.EventsOptionFunc if eventsCmdFlags.tailEvents != 0 { opts = append(opts, client.WithTailEvents(eventsCmdFlags.tailEvents)) @@ -73,30 +73,30 @@ var eventsCmd = &cobra.Command{ return err } - var args []interface{} + var args []any switch msg := event.Payload.(type) { case *machine.SequenceEvent: - args = []interface{}{msg.GetSequence()} + args = []any{msg.GetSequence()} if msg.Error != nil { args = append(args, "error:"+" "+msg.GetError().GetMessage()) } else { args = append(args, msg.GetAction().String()) } case *machine.PhaseEvent: - args = []interface{}{msg.GetPhase(), msg.GetAction().String()} + args = []any{msg.GetPhase(), msg.GetAction().String()} case *machine.TaskEvent: - args = []interface{}{msg.GetTask(), msg.GetAction().String()} + args = []any{msg.GetTask(), msg.GetAction().String()} case *machine.ServiceStateEvent: - args = []interface{}{msg.GetService(), fmt.Sprintf("%s: %s", msg.GetAction(), msg.GetMessage())} + args = []any{msg.GetService(), fmt.Sprintf("%s: %s", msg.GetAction(), msg.GetMessage())} case *machine.ConfigLoadErrorEvent: - args = []interface{}{"error", msg.GetError()} + args = []any{"error", msg.GetError()} case *machine.ConfigValidationErrorEvent: - args = []interface{}{"error", msg.GetError()} + args = []any{"error", msg.GetError()} case *machine.AddressEvent: - args = []interface{}{msg.GetHostname(), fmt.Sprintf("ADDRESSES: %s", strings.Join(msg.GetAddresses(), ","))} + args = []any{msg.GetHostname(), fmt.Sprintf("ADDRESSES: %s", strings.Join(msg.GetAddresses(), ","))} case *machine.MachineStatusEvent: - args = []interface{}{ + args = []any{ msg.GetStage().String(), fmt.Sprintf("ready: %v, unmet conditions: %v", msg.GetStatus().Ready, @@ -109,7 +109,7 @@ var eventsCmd = &cobra.Command{ } } - args = append([]interface{}{event.Node, event.ID, event.TypeURL, event.ActorID}, args...) + args = append([]any{event.Node, event.ID, event.TypeURL, event.ActorID}, args...) fmt.Fprintf(w, format, args...) return w.Flush() diff --git a/cmd/talosctl/cmd/talos/netstat.go b/cmd/talosctl/cmd/talos/netstat.go index 801cc334e5..ef81c07bc2 100644 --- a/cmd/talosctl/cmd/talos/netstat.go +++ b/cmd/talosctl/cmd/talos/netstat.go @@ -281,7 +281,7 @@ func (n *netstat) printNetstat(response *machine.NetstatResponse) error { } } - args := []interface{}{} + var args []any if node != "" { args = append(args, node) @@ -292,7 +292,7 @@ func (n *netstat) printNetstat(response *machine.NetstatResponse) error { state = record.State.String() } - args = append(args, []interface{}{ + args = append(args, []any{ record.L4Proto, strconv.FormatUint(record.Rxqueue, 10), strconv.FormatUint(record.Txqueue, 10), @@ -302,7 +302,7 @@ func (n *netstat) printNetstat(response *machine.NetstatResponse) error { }...) if netstatCmdFlags.extend { - args = append(args, []interface{}{ + args = append(args, []any{ strconv.FormatUint(uint64(record.Uid), 10), strconv.FormatUint(record.Inode, 10), }...) @@ -310,11 +310,11 @@ func (n *netstat) printNetstat(response *machine.NetstatResponse) error { if netstatCmdFlags.pid { if record.Process.Pid != 0 { - args = append(args, []interface{}{ + args = append(args, []any{ fmt.Sprintf("%d/%s", record.Process.Pid, record.Process.Name), }...) } else { - args = append(args, []interface{}{ + args = append(args, []any{ "-", }...) } @@ -322,11 +322,11 @@ func (n *netstat) printNetstat(response *machine.NetstatResponse) error { if netstatCmdFlags.pods { if record.Netns == "" || node == "" || n.NodeNetNSPods[node] == nil { - args = append(args, []interface{}{ + args = append(args, []any{ "-", }...) } else { - args = append(args, []interface{}{ + args = append(args, []any{ n.NodeNetNSPods[node][record.Netns], }...) } @@ -335,7 +335,7 @@ func (n *netstat) printNetstat(response *machine.NetstatResponse) error { if netstatCmdFlags.timers { timerwhen := strconv.FormatFloat(float64(record.Timerwhen)/100, 'f', 2, 64) - args = append(args, []interface{}{ + args = append(args, []any{ fmt.Sprintf("%s (%s/%d/%d)", strings.ToLower(record.Tr.String()), timerwhen, record.Retrnsmt, record.Timeout), }...) } diff --git a/cmd/talosctl/cmd/talos/output/json.go b/cmd/talosctl/cmd/talos/output/json.go index a3a3f37a5f..2cc7e99b48 100644 --- a/cmd/talosctl/cmd/talos/output/json.go +++ b/cmd/talosctl/cmd/talos/output/json.go @@ -38,7 +38,7 @@ func (j *JSON) WriteHeader(definition *meta.ResourceDefinition, withEvents bool) } // prepareEncodableData prepares the data of a resource to be encoded as JSON and populates it with some extra information. -func (j *JSON) prepareEncodableData(node string, r resource.Resource, event state.EventType) (map[string]interface{}, error) { +func (j *JSON) prepareEncodableData(node string, r resource.Resource, event state.EventType) (map[string]any, error) { if r.Metadata().Type() == config.MachineConfigType { r = &mcYamlRepr{r} } @@ -53,7 +53,7 @@ func (j *JSON) prepareEncodableData(node string, r resource.Resource, event stat return nil, err } - var data map[string]interface{} + var data map[string]any err = yaml.Unmarshal(yamlBytes, &data) if err != nil { @@ -69,7 +69,7 @@ func (j *JSON) prepareEncodableData(node string, r resource.Resource, event stat return data, nil } -func writeAsIndentedJSON(wr io.Writer, data interface{}) error { +func writeAsIndentedJSON(wr io.Writer, data any) error { enc := json.NewEncoder(wr) enc.SetIndent("", " ") diff --git a/cmd/talosctl/cmd/talos/output/table.go b/cmd/talosctl/cmd/talos/output/table.go index 7932a46a7e..12893162c6 100644 --- a/cmd/talosctl/cmd/talos/output/table.go +++ b/cmd/talosctl/cmd/talos/output/table.go @@ -27,7 +27,7 @@ type Table struct { dynamicColumns []dynamicColumn } -type dynamicColumn func(value interface{}) (string, error) +type dynamicColumn func(value any) (string, error) // NewTable initializes table resource output. func NewTable(writer io.Writer) *Table { @@ -60,7 +60,7 @@ func (table *Table) WriteHeader(definition *meta.ResourceDefinition, withEvents expr = expr.AllowMissingKeys(true) - table.dynamicColumns = append(table.dynamicColumns, func(val interface{}) (string, error) { + table.dynamicColumns = append(table.dynamicColumns, func(val any) (string, error) { var buf bytes.Buffer if e := expr.Execute(&buf, val); e != nil { @@ -104,7 +104,7 @@ func (table *Table) WriteResource(node string, r resource.Resource, event state. return err } - var unstructured interface{} + var unstructured any if err = yaml.Unmarshal(yml, &unstructured); err != nil { return err diff --git a/cmd/talosctl/cmd/talos/processes.go b/cmd/talosctl/cmd/talos/processes.go index 06a46f117a..293dadb2fa 100644 --- a/cmd/talosctl/cmd/talos/processes.go +++ b/cmd/talosctl/cmd/talos/processes.go @@ -188,7 +188,7 @@ func processesOutput(ctx context.Context, c *client.Client) (output string, err defaultNode := client.AddrFromPeer(&remotePeer) - s := []string{} + var s []string s = append(s, "NODE | PID | STATE | THREADS | CPU-TIME | VIRTMEM | RESMEM | LABEL | COMMAND") diff --git a/cmd/talosctl/pkg/mgmt/helpers/wireguard.go b/cmd/talosctl/pkg/mgmt/helpers/wireguard.go index 76e10936d8..c6b0e34d29 100644 --- a/cmd/talosctl/pkg/mgmt/helpers/wireguard.go +++ b/cmd/talosctl/pkg/mgmt/helpers/wireguard.go @@ -61,7 +61,8 @@ func NewWireguardConfigBundle(ips []netip.Addr, wireguardCidr string, listenPort config := &v1alpha1.DeviceWireguardConfig{} - currentPeers := []*v1alpha1.DeviceWireguardPeer{} + var currentPeers []*v1alpha1.DeviceWireguardPeer + // add all peers except self for _, peer := range peers { if peer.PublicKey() != keys[i].PublicKey().String() { diff --git a/cmd/talosctl/pkg/talos/helpers/error.go b/cmd/talosctl/pkg/talos/helpers/error.go index bb9a845353..3e8ed0b6ce 100644 --- a/cmd/talosctl/pkg/talos/helpers/error.go +++ b/cmd/talosctl/pkg/talos/helpers/error.go @@ -18,7 +18,7 @@ func AppendErrors(err error, errs ...error) error { res := multierror.Append(err, errs...) res.ErrorFormat = func(errs []error) string { - lines := []string{} + var lines []string for _, err := range errs { lines = append(lines, fmt.Sprintf(" %s", err.Error())) diff --git a/cmd/talosctl/pkg/talos/yamlstrip/yamlstrip.go b/cmd/talosctl/pkg/talos/yamlstrip/yamlstrip.go index a4902c2f36..5bcfe2981c 100644 --- a/cmd/talosctl/pkg/talos/yamlstrip/yamlstrip.go +++ b/cmd/talosctl/pkg/talos/yamlstrip/yamlstrip.go @@ -65,7 +65,8 @@ func removeComments(node *yaml.Node) { } func stripManual(b []byte) []byte { - stripped := []byte{} + var stripped []byte + lines := bytes.Split(b, []byte("\n")) for i, line := range lines { diff --git a/hack/cloud-image-uploader/aws.go b/hack/cloud-image-uploader/aws.go index 2ac2025250..2831d53e61 100644 --- a/hack/cloud-image-uploader/aws.go +++ b/hack/cloud-image-uploader/aws.go @@ -36,7 +36,7 @@ func GetAWSDefaultRegions() ([]string, error) { return nil, fmt.Errorf("failed getting list of regions: %w", err) } - regions := []string{} + var regions []string for _, r := range result.Regions { if r.OptInStatus != nil { diff --git a/hack/docgen/main.go b/hack/docgen/main.go index fbc186bb50..8afc5508df 100644 --- a/hack/docgen/main.go +++ b/hack/docgen/main.go @@ -198,7 +198,8 @@ type aliasType struct { } func collectStructs(node ast.Node) ([]*structType, map[string]aliasType) { - structs := []*structType{} + var structs []*structType + aliases := map[string]aliasType{} collectStructs := func(n ast.Node) bool { @@ -306,7 +307,7 @@ func parseComment(comment []byte) *Text { return text } -func getFieldType(p interface{}) string { +func getFieldType(p any) string { if m, ok := p.(*ast.MapType); ok { return getFieldType(m.Value) } @@ -325,7 +326,7 @@ func getFieldType(p interface{}) string { } } -func formatFieldType(p interface{}) string { +func formatFieldType(p any) string { if m, ok := p.(*ast.MapType); ok { return fmt.Sprintf("map[%s]%s", formatFieldType(m.Key), formatFieldType(m.Value)) } diff --git a/internal/app/init/main.go b/internal/app/init/main.go index 19e0a7c4e2..579c650ca8 100644 --- a/internal/app/init/main.go +++ b/internal/app/init/main.go @@ -145,7 +145,7 @@ func mountRootFS() error { image string } - layers := []layer{} + var layers []layer squashfs := mount.NewMountPoints() diff --git a/internal/app/machined/internal/server/v1alpha1/v1alpha1_server.go b/internal/app/machined/internal/server/v1alpha1/v1alpha1_server.go index 07a4f7d247..5b76963946 100644 --- a/internal/app/machined/internal/server/v1alpha1/v1alpha1_server.go +++ b/internal/app/machined/internal/server/v1alpha1/v1alpha1_server.go @@ -1055,7 +1055,8 @@ func (s *Server) Mounts(ctx context.Context, in *emptypb.Empty) (reply *machine. multiErr *multierror.Error ) - stats := []*machine.MountStat{} + var stats []*machine.MountStat + scanner := bufio.NewScanner(file) for scanner.Scan() { @@ -1409,7 +1410,7 @@ func (s *Server) Containers(ctx context.Context, in *machine.ContainersRequest) log.Println(err.Error()) } - containers := []*machine.ContainerInfo{} + var containers []*machine.ContainerInfo for _, pod := range pods { for _, container := range pod.Containers { @@ -1457,7 +1458,7 @@ func (s *Server) Stats(ctx context.Context, in *machine.StatsRequest) (reply *ma log.Println(err.Error()) } - stats := []*machine.Stat{} + var stats []*machine.Stat for _, pod := range pods { for _, container := range pod.Containers { diff --git a/internal/app/machined/pkg/adapters/k8s/static_pod.go b/internal/app/machined/pkg/adapters/k8s/static_pod.go index c545733b84..6fef695f07 100644 --- a/internal/app/machined/pkg/adapters/k8s/static_pod.go +++ b/internal/app/machined/pkg/adapters/k8s/static_pod.go @@ -46,7 +46,7 @@ func (a staticPod) SetPod(podSpec *v1.Pod) error { return err } - a.StaticPod.TypedSpec().Pod = map[string]interface{}{} + a.StaticPod.TypedSpec().Pod = map[string]any{} return json.Unmarshal(jsonSerialized, &a.StaticPod.TypedSpec().Pod) } diff --git a/internal/app/machined/pkg/adapters/k8s/static_pod_status.go b/internal/app/machined/pkg/adapters/k8s/static_pod_status.go index bdcea57d9f..fa3e4dbdb0 100644 --- a/internal/app/machined/pkg/adapters/k8s/static_pod_status.go +++ b/internal/app/machined/pkg/adapters/k8s/static_pod_status.go @@ -32,7 +32,7 @@ func (a staticPodStatus) SetStatus(status *v1.PodStatus) error { return err } - a.StaticPodStatus.TypedSpec().PodStatus = map[string]interface{}{} + a.StaticPodStatus.TypedSpec().PodStatus = map[string]any{} return json.Unmarshal(jsonSerialized, &a.StaticPodStatus.TypedSpec().PodStatus) } diff --git a/internal/app/machined/pkg/controllers/cluster/node_identity.go b/internal/app/machined/pkg/controllers/cluster/node_identity.go index 59d0a0b7d0..c19c3b2d75 100644 --- a/internal/app/machined/pkg/controllers/cluster/node_identity.go +++ b/internal/app/machined/pkg/controllers/cluster/node_identity.go @@ -93,7 +93,7 @@ func (ctrl *NodeIdentityController) Run(ctx context.Context, r controller.Runtim var localIdentity cluster.IdentitySpec - if err := controllers.LoadOrNewFromFile(filepath.Join(ctrl.StatePath, constants.NodeIdentityFilename), &localIdentity, func(v interface{}) error { + if err := controllers.LoadOrNewFromFile(filepath.Join(ctrl.StatePath, constants.NodeIdentityFilename), &localIdentity, func(v any) error { return clusteradapter.IdentitySpec(v.(*cluster.IdentitySpec)).Generate() }); err != nil { return fmt.Errorf("error caching node identity: %w", err) diff --git a/internal/app/machined/pkg/controllers/cri/seccomp_profile_file_test.go b/internal/app/machined/pkg/controllers/cri/seccomp_profile_file_test.go index ad171bb728..a7bd8f0eb0 100644 --- a/internal/app/machined/pkg/controllers/cri/seccomp_profile_file_test.go +++ b/internal/app/machined/pkg/controllers/cri/seccomp_profile_file_test.go @@ -28,17 +28,17 @@ func (suite *CRISeccompProfileFileSuite) TestReconcileSeccompProfileFile() { for _, tt := range []struct { seccompProfileName string - seccompProfileValue map[string]interface{} + seccompProfileValue map[string]any }{ { seccompProfileName: "audit.json", - seccompProfileValue: map[string]interface{}{ + seccompProfileValue: map[string]any{ "defaultAction": "SCMP_ACT_LOG", }, }, { seccompProfileName: "deny.json", - seccompProfileValue: map[string]interface{}{ + seccompProfileValue: map[string]any{ "defaultAction": "SCMP_ACT_ERRNO", }, }, diff --git a/internal/app/machined/pkg/controllers/cri/seccomp_profile_test.go b/internal/app/machined/pkg/controllers/cri/seccomp_profile_test.go index 054fc49ddb..98eb836e06 100644 --- a/internal/app/machined/pkg/controllers/cri/seccomp_profile_test.go +++ b/internal/app/machined/pkg/controllers/cri/seccomp_profile_test.go @@ -27,7 +27,7 @@ func (suite *CRISeccompProfileSuite) TestReconcileSeccompProfile() { { MachineSeccompProfileName: "audit.json", MachineSeccompProfileValue: v1alpha1.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "defaultAction": "SCMP_ACT_LOG", }, }, @@ -35,7 +35,7 @@ func (suite *CRISeccompProfileSuite) TestReconcileSeccompProfile() { { MachineSeccompProfileName: "deny.json", MachineSeccompProfileValue: v1alpha1.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "defaultAction": "SCMP_ACT_ERRNO", }, }, @@ -48,17 +48,17 @@ func (suite *CRISeccompProfileSuite) TestReconcileSeccompProfile() { for _, tt := range []struct { name string - value map[string]interface{} + value map[string]any }{ { name: "audit.json", - value: map[string]interface{}{ + value: map[string]any{ "defaultAction": "SCMP_ACT_LOG", }, }, { name: "deny.json", - value: map[string]interface{}{ + value: map[string]any{ "defaultAction": "SCMP_ACT_ERRNO", }, }, @@ -92,7 +92,7 @@ func (suite *CRISeccompProfileSuite) TestReconcileSeccompProfile() { { MachineSeccompProfileName: "audit.json", MachineSeccompProfileValue: v1alpha1.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "defaultAction": "SCMP_ACT_LOG", }, }, diff --git a/internal/app/machined/pkg/controllers/files/etcfile.go b/internal/app/machined/pkg/controllers/files/etcfile.go index 5a11f10a46..f0e16a03af 100644 --- a/internal/app/machined/pkg/controllers/files/etcfile.go +++ b/internal/app/machined/pkg/controllers/files/etcfile.go @@ -28,7 +28,7 @@ type EtcFileController struct { ShadowPath string // Cache of bind mounts created. - bindMounts map[string]interface{} + bindMounts map[string]any } // Name implements controller.Controller interface. @@ -62,7 +62,7 @@ func (ctrl *EtcFileController) Outputs() []controller.Output { //nolint:gocyclo,cyclop func (ctrl *EtcFileController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error { if ctrl.bindMounts == nil { - ctrl.bindMounts = make(map[string]interface{}) + ctrl.bindMounts = make(map[string]any) } for { diff --git a/internal/app/machined/pkg/controllers/kubeaccess/serviceaccount/crd_controller.go b/internal/app/machined/pkg/controllers/kubeaccess/serviceaccount/crd_controller.go index 0e06f221d3..3b79eec318 100644 --- a/internal/app/machined/pkg/controllers/kubeaccess/serviceaccount/crd_controller.go +++ b/internal/app/machined/pkg/controllers/kubeaccess/serviceaccount/crd_controller.go @@ -175,7 +175,7 @@ func NewCRDController( if _, err = informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: controller.enqueueTalosSA, - UpdateFunc: func(oldTalosSA, newTalosSA interface{}) { + UpdateFunc: func(oldTalosSA, newTalosSA any) { controller.enqueueTalosSA(newTalosSA) }, }); err != nil { @@ -184,7 +184,7 @@ func NewCRDController( if _, err = secrets.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: controller.handleSecret, - UpdateFunc: func(oldSec, newSec interface{}) { + UpdateFunc: func(oldSec, newSec any) { newSecret := newSec.(*corev1.Secret) //nolint:errcheck oldSecret := oldSec.(*corev1.Secret) //nolint:errcheck @@ -259,7 +259,7 @@ func (t *CRDController) processNextWorkItem(ctx context.Context) bool { return false } - err := func(obj interface{}) error { + err := func(obj any) error { defer t.queue.Done(obj) var key string @@ -428,7 +428,7 @@ func (t *CRDController) syncHandler(ctx context.Context, key string) error { return nil } -func (t *CRDController) enqueueTalosSA(obj interface{}) { +func (t *CRDController) enqueueTalosSA(obj any) { key, err := cache.MetaNamespaceKeyFunc(obj) if err != nil { utilruntime.HandleError(err) @@ -439,7 +439,7 @@ func (t *CRDController) enqueueTalosSA(obj interface{}) { t.queue.Add(key) } -func (t *CRDController) handleSecret(obj interface{}) { +func (t *CRDController) handleSecret(obj any) { var object metav1.Object var ok bool diff --git a/internal/app/machined/pkg/controllers/kubespan/identity.go b/internal/app/machined/pkg/controllers/kubespan/identity.go index 1443e94f82..46a19bc84d 100644 --- a/internal/app/machined/pkg/controllers/kubespan/identity.go +++ b/internal/app/machined/pkg/controllers/kubespan/identity.go @@ -107,7 +107,7 @@ func (ctrl *IdentityController) Run(ctx context.Context, r controller.Runtime, l if cfg != nil && firstMAC != nil && cfg.(*kubespan.Config).TypedSpec().Enabled { var localIdentity kubespan.IdentitySpec - if err = controllers.LoadOrNewFromFile(filepath.Join(ctrl.StatePath, constants.KubeSpanIdentityFilename), &localIdentity, func(v interface{}) error { + if err = controllers.LoadOrNewFromFile(filepath.Join(ctrl.StatePath, constants.KubeSpanIdentityFilename), &localIdentity, func(v any) error { return kubespanadapter.IdentitySpec(v.(*kubespan.IdentitySpec)).GenerateKey() }); err != nil { return fmt.Errorf("error caching kubespan identity: %w", err) diff --git a/internal/app/machined/pkg/controllers/network/address_event.go b/internal/app/machined/pkg/controllers/network/address_event.go index e0daaf6a60..b066f914e8 100644 --- a/internal/app/machined/pkg/controllers/network/address_event.go +++ b/internal/app/machined/pkg/controllers/network/address_event.go @@ -70,7 +70,7 @@ func (ctrl *AddressEventController) Run(ctx context.Context, r controller.Runtim case <-r.EventCh(): } - addresses := []string{} + var addresses []string nodeAddr, err := r.Get( ctx, diff --git a/internal/app/machined/pkg/controllers/network/link_status_test.go b/internal/app/machined/pkg/controllers/network/link_status_test.go index 5cb7b1b756..07a53aa328 100644 --- a/internal/app/machined/pkg/controllers/network/link_status_test.go +++ b/internal/app/machined/pkg/controllers/network/link_status_test.go @@ -156,7 +156,7 @@ func (suite *LinkStatusSuite) TestInterfaceHwInfo() { continue } - emptyFields := []string{} + var emptyFields []string for key, value := range map[string]string{ "hw addr": spec.HardwareAddr.String(), diff --git a/internal/app/machined/pkg/controllers/network/platform_config.go b/internal/app/machined/pkg/controllers/network/platform_config.go index ba29913d35..834ce3d7c4 100644 --- a/internal/app/machined/pkg/controllers/network/platform_config.go +++ b/internal/app/machined/pkg/controllers/network/platform_config.go @@ -217,18 +217,18 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru // handle all network specs in a loop as all specs can be handled in a similar way for _, specType := range []struct { length int - getter func(i int) interface{} - idBuilder func(spec interface{}) (resource.ID, error) + getter func(i int) any + idBuilder func(spec any) (resource.ID, error) resourceBuilder func(id string) resource.Resource - resourceModifier func(newSpec interface{}) func(r resource.Resource) error + resourceModifier func(newSpec any) func(r resource.Resource) error }{ // AddressSpec { length: len(networkConfig.Addresses), - getter: func(i int) interface{} { + getter: func(i int) any { return networkConfig.Addresses[i] }, - idBuilder: func(spec interface{}) (resource.ID, error) { + idBuilder: func(spec any) (resource.ID, error) { addressSpec := spec.(network.AddressSpecSpec) //nolint:errcheck,forcetypeassert return network.LayeredID(network.ConfigPlatform, network.AddressID(addressSpec.LinkName, addressSpec.Address)), nil @@ -236,7 +236,7 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru resourceBuilder: func(id string) resource.Resource { return network.NewAddressSpec(network.ConfigNamespaceName, id) }, - resourceModifier: func(newSpec interface{}) func(r resource.Resource) error { + resourceModifier: func(newSpec any) func(r resource.Resource) error { return func(r resource.Resource) error { spec := r.(*network.AddressSpec).TypedSpec() @@ -250,10 +250,10 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru // LinkSpec { length: len(networkConfig.Links), - getter: func(i int) interface{} { + getter: func(i int) any { return networkConfig.Links[i] }, - idBuilder: func(spec interface{}) (resource.ID, error) { + idBuilder: func(spec any) (resource.ID, error) { linkSpec := spec.(network.LinkSpecSpec) //nolint:errcheck,forcetypeassert return network.LayeredID(network.ConfigPlatform, network.LinkID(linkSpec.Name)), nil @@ -261,7 +261,7 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru resourceBuilder: func(id string) resource.Resource { return network.NewLinkSpec(network.ConfigNamespaceName, id) }, - resourceModifier: func(newSpec interface{}) func(r resource.Resource) error { + resourceModifier: func(newSpec any) func(r resource.Resource) error { return func(r resource.Resource) error { spec := r.(*network.LinkSpec).TypedSpec() @@ -275,10 +275,10 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru // RouteSpec { length: len(networkConfig.Routes), - getter: func(i int) interface{} { + getter: func(i int) any { return networkConfig.Routes[i] }, - idBuilder: func(spec interface{}) (resource.ID, error) { + idBuilder: func(spec any) (resource.ID, error) { routeSpec := spec.(network.RouteSpecSpec) //nolint:errcheck,forcetypeassert return network.LayeredID( @@ -289,7 +289,7 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru resourceBuilder: func(id string) resource.Resource { return network.NewRouteSpec(network.ConfigNamespaceName, id) }, - resourceModifier: func(newSpec interface{}) func(r resource.Resource) error { + resourceModifier: func(newSpec any) func(r resource.Resource) error { return func(r resource.Resource) error { spec := r.(*network.RouteSpec).TypedSpec() @@ -303,16 +303,16 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru // HostnameSpec { length: len(networkConfig.Hostnames), - getter: func(i int) interface{} { + getter: func(i int) any { return networkConfig.Hostnames[i] }, - idBuilder: func(spec interface{}) (resource.ID, error) { + idBuilder: func(spec any) (resource.ID, error) { return network.LayeredID(network.ConfigPlatform, network.HostnameID), nil }, resourceBuilder: func(id string) resource.Resource { return network.NewHostnameSpec(network.ConfigNamespaceName, id) }, - resourceModifier: func(newSpec interface{}) func(r resource.Resource) error { + resourceModifier: func(newSpec any) func(r resource.Resource) error { return func(r resource.Resource) error { spec := r.(*network.HostnameSpec).TypedSpec() @@ -326,16 +326,16 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru // ResolverSpec { length: len(networkConfig.Resolvers), - getter: func(i int) interface{} { + getter: func(i int) any { return networkConfig.Resolvers[i] }, - idBuilder: func(spec interface{}) (resource.ID, error) { + idBuilder: func(spec any) (resource.ID, error) { return network.LayeredID(network.ConfigPlatform, network.ResolverID), nil }, resourceBuilder: func(id string) resource.Resource { return network.NewResolverSpec(network.ConfigNamespaceName, id) }, - resourceModifier: func(newSpec interface{}) func(r resource.Resource) error { + resourceModifier: func(newSpec any) func(r resource.Resource) error { return func(r resource.Resource) error { spec := r.(*network.ResolverSpec).TypedSpec() @@ -349,16 +349,16 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru // TimeServerSpec { length: len(networkConfig.TimeServers), - getter: func(i int) interface{} { + getter: func(i int) any { return networkConfig.TimeServers[i] }, - idBuilder: func(spec interface{}) (resource.ID, error) { + idBuilder: func(spec any) (resource.ID, error) { return network.LayeredID(network.ConfigPlatform, network.TimeServerID), nil }, resourceBuilder: func(id string) resource.Resource { return network.NewTimeServerSpec(network.ConfigNamespaceName, id) }, - resourceModifier: func(newSpec interface{}) func(r resource.Resource) error { + resourceModifier: func(newSpec any) func(r resource.Resource) error { return func(r resource.Resource) error { spec := r.(*network.TimeServerSpec).TypedSpec() @@ -372,10 +372,10 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru // OperatorSpec { length: len(networkConfig.Operators), - getter: func(i int) interface{} { + getter: func(i int) any { return networkConfig.Operators[i] }, - idBuilder: func(spec interface{}) (resource.ID, error) { + idBuilder: func(spec any) (resource.ID, error) { operatorSpec := spec.(network.OperatorSpecSpec) //nolint:errcheck,forcetypeassert return network.LayeredID(network.ConfigPlatform, network.OperatorID(operatorSpec.Operator, operatorSpec.LinkName)), nil @@ -383,7 +383,7 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru resourceBuilder: func(id string) resource.Resource { return network.NewOperatorSpec(network.ConfigNamespaceName, id) }, - resourceModifier: func(newSpec interface{}) func(r resource.Resource) error { + resourceModifier: func(newSpec any) func(r resource.Resource) error { return func(r resource.Resource) error { spec := r.(*network.OperatorSpec).TypedSpec() @@ -397,10 +397,10 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru // ExternalIPs { length: len(networkConfig.ExternalIPs), - getter: func(i int) interface{} { + getter: func(i int) any { return networkConfig.ExternalIPs[i] }, - idBuilder: func(spec interface{}) (resource.ID, error) { + idBuilder: func(spec any) (resource.ID, error) { ipAddr := spec.(netip.Addr) //nolint:errcheck,forcetypeassert ipPrefix := netip.PrefixFrom(ipAddr, ipAddr.BitLen()) @@ -409,7 +409,7 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru resourceBuilder: func(id string) resource.Resource { return network.NewAddressStatus(network.NamespaceName, id) }, - resourceModifier: func(newSpec interface{}) func(r resource.Resource) error { + resourceModifier: func(newSpec any) func(r resource.Resource) error { return func(r resource.Resource) error { ipAddr := newSpec.(netip.Addr) //nolint:errcheck,forcetypeassert ipPrefix := netip.PrefixFrom(ipAddr, ipAddr.BitLen()) @@ -434,10 +434,10 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru // ProbeSpec { length: len(networkConfig.Probes), - getter: func(i int) interface{} { + getter: func(i int) any { return networkConfig.Probes[i] }, - idBuilder: func(spec interface{}) (resource.ID, error) { + idBuilder: func(spec any) (resource.ID, error) { probeSpec := spec.(network.ProbeSpecSpec) //nolint:errcheck,forcetypeassert return probeSpec.ID() @@ -445,7 +445,7 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru resourceBuilder: func(id string) resource.Resource { return network.NewProbeSpec(network.NamespaceName, id) }, - resourceModifier: func(newSpec interface{}) func(r resource.Resource) error { + resourceModifier: func(newSpec any) func(r resource.Resource) error { return func(r resource.Resource) error { spec := r.(*network.ProbeSpec).TypedSpec() @@ -459,16 +459,16 @@ func (ctrl *PlatformConfigController) apply(ctx context.Context, r controller.Ru // Platform metadata { length: metadataLength, - getter: func(i int) interface{} { + getter: func(i int) any { return networkConfig.Metadata }, - idBuilder: func(spec interface{}) (resource.ID, error) { + idBuilder: func(spec any) (resource.ID, error) { return runtimeres.PlatformMetadataID, nil }, resourceBuilder: func(id string) resource.Resource { return runtimeres.NewPlatformMetadataSpec(runtimeres.NamespaceName, id) }, - resourceModifier: func(newSpec interface{}) func(r resource.Resource) error { + resourceModifier: func(newSpec any) func(r resource.Resource) error { return func(r resource.Resource) error { metadata := newSpec.(*runtimeres.PlatformMetadataSpec) //nolint:errcheck,forcetypeassert diff --git a/internal/app/machined/pkg/controllers/runtime/events_sink.go b/internal/app/machined/pkg/controllers/runtime/events_sink.go index 762c5991e2..2a93e82bfd 100644 --- a/internal/app/machined/pkg/controllers/runtime/events_sink.go +++ b/internal/app/machined/pkg/controllers/runtime/events_sink.go @@ -178,7 +178,8 @@ func (ctrl *EventsSinkController) Run(ctx context.Context, r controller.Runtime, if watchCh == nil { watchCh = make(chan machinedruntime.EventInfo) - opts := []machinedruntime.WatchOptionFunc{} + var opts []machinedruntime.WatchOptionFunc + if ctrl.eventID.IsNil() { opts = append(opts, machinedruntime.WithTailEvents(-1)) } else { diff --git a/internal/app/machined/pkg/controllers/runtime/extension_service_test.go b/internal/app/machined/pkg/controllers/runtime/extension_service_test.go index 378c23e5f8..a43b092bc0 100644 --- a/internal/app/machined/pkg/controllers/runtime/extension_service_test.go +++ b/internal/app/machined/pkg/controllers/runtime/extension_service_test.go @@ -8,7 +8,6 @@ import ( "fmt" "reflect" "slices" - "sort" "sync" "testing" "time" @@ -38,7 +37,7 @@ func (mock *serviceMock) Load(services ...system.Service) []string { mock.mu.Lock() defer mock.mu.Unlock() - ids := []string{} + ids := make([]string, 0, len(services)) for _, svc := range services { mock.services[svc.ID(nil)] = svc @@ -90,13 +89,13 @@ func (mock *serviceMock) getIDs() []string { mock.mu.Lock() defer mock.mu.Unlock() - ids := []string{} + ids := make([]string, 0, len(mock.services)) for id := range mock.services { ids = append(ids, id) } - sort.Strings(ids) + slices.Sort(ids) return ids } diff --git a/internal/app/machined/pkg/controllers/runtime/kmsg_log.go b/internal/app/machined/pkg/controllers/runtime/kmsg_log.go index 0c28bdd86d..fe22cb88d4 100644 --- a/internal/app/machined/pkg/controllers/runtime/kmsg_log.go +++ b/internal/app/machined/pkg/controllers/runtime/kmsg_log.go @@ -196,7 +196,7 @@ func (ctrl *KmsgLogDeliveryController) deliverLogs(ctx context.Context, r contro Msg: msg.Message.Message, Time: msg.Message.Timestamp, Level: kmsgPriorityToLevel(msg.Message.Priority), - Fields: map[string]interface{}{ + Fields: map[string]any{ "facility": msg.Message.Facility.String(), "seq": msg.Message.SequenceNumber, "clock": msg.Message.Clock, diff --git a/internal/app/machined/pkg/controllers/runtime/kmsg_log_config.go b/internal/app/machined/pkg/controllers/runtime/kmsg_log_config.go index a8c9a103d4..e14568a04d 100644 --- a/internal/app/machined/pkg/controllers/runtime/kmsg_log_config.go +++ b/internal/app/machined/pkg/controllers/runtime/kmsg_log_config.go @@ -66,7 +66,7 @@ func (ctrl *KmsgLogConfigController) Run(ctx context.Context, r controller.Runti case <-r.EventCh(): } - destinations := []*url.URL{} + var destinations []*url.URL if ctrl.Cmdline != nil { if val := ctrl.Cmdline.Get(constants.KernelParamLoggingKernel).First(); val != nil { diff --git a/internal/app/machined/pkg/controllers/runtime/kmsg_log_test.go b/internal/app/machined/pkg/controllers/runtime/kmsg_log_test.go index 80eee0ea52..1fe1a46289 100644 --- a/internal/app/machined/pkg/controllers/runtime/kmsg_log_test.go +++ b/internal/app/machined/pkg/controllers/runtime/kmsg_log_test.go @@ -35,7 +35,7 @@ type logHandler struct { } // HandleLog implements logreceiver.Handler. -func (s *logHandler) HandleLog(srcAddr netip.Addr, msg map[string]interface{}) { +func (s *logHandler) HandleLog(srcAddr netip.Addr, msg map[string]any) { s.mu.Lock() defer s.mu.Unlock() diff --git a/internal/app/machined/pkg/controllers/utils.go b/internal/app/machined/pkg/controllers/utils.go index a511e4e48b..89e028a399 100644 --- a/internal/app/machined/pkg/controllers/utils.go +++ b/internal/app/machined/pkg/controllers/utils.go @@ -15,7 +15,7 @@ import ( ) // LoadOrNewFromFile either loads value from file.yaml or generates new values and saves as file.yaml. -func LoadOrNewFromFile(path string, empty interface{}, generate func(interface{}) error) error { +func LoadOrNewFromFile(path string, empty any, generate func(any) error) error { f, err := os.OpenFile(path, os.O_RDONLY, 0) if err != nil && !os.IsNotExist(err) { return fmt.Errorf("error reading state file: %w", err) diff --git a/internal/app/machined/pkg/runtime/controller.go b/internal/app/machined/pkg/runtime/controller.go index 6170fba5a6..4b527eadc6 100644 --- a/internal/app/machined/pkg/runtime/controller.go +++ b/internal/app/machined/pkg/runtime/controller.go @@ -53,7 +53,7 @@ func DefaultControllerOptions() LockOptions { type Controller interface { Runtime() Runtime Sequencer() Sequencer - Run(context.Context, Sequence, interface{}, ...LockOption) error + Run(context.Context, Sequence, any, ...LockOption) error V1Alpha2() V1Alpha2Controller } diff --git a/internal/app/machined/pkg/runtime/logging.go b/internal/app/machined/pkg/runtime/logging.go index 4836e4a8a6..fcac735ed7 100644 --- a/internal/app/machined/pkg/runtime/logging.go +++ b/internal/app/machined/pkg/runtime/logging.go @@ -66,7 +66,7 @@ type LogEvent struct { Msg string Time time.Time Level zapcore.Level - Fields map[string]interface{} + Fields map[string]any } // ErrDontRetry indicates that log event should not be resent. diff --git a/internal/app/machined/pkg/runtime/logging/circular.go b/internal/app/machined/pkg/runtime/logging/circular.go index c63ac8cc21..5e41cabc14 100644 --- a/internal/app/machined/pkg/runtime/logging/circular.go +++ b/internal/app/machined/pkg/runtime/logging/circular.go @@ -74,7 +74,7 @@ func (manager *CircularBufferLoggingManager) ServiceLog(id string) runtime.LogHa return &circularHandler{ manager: manager, id: id, - fields: map[string]interface{}{ + fields: map[string]any{ // use field name that is not used by anything else "talos-service": id, }, @@ -153,7 +153,7 @@ func (manager *CircularBufferLoggingManager) RegisteredLogs() []string { type circularHandler struct { manager *CircularBufferLoggingManager id string - fields map[string]interface{} + fields map[string]any buf *circular.Buffer } diff --git a/internal/app/machined/pkg/runtime/logging/extract.go b/internal/app/machined/pkg/runtime/logging/extract.go index cfd4d1102a..936cd17d97 100644 --- a/internal/app/machined/pkg/runtime/logging/extract.go +++ b/internal/app/machined/pkg/runtime/logging/extract.go @@ -102,7 +102,7 @@ func parseLogLine(l []byte, now time.Time) *runtime.LogEvent { return e } -func parseJSONLogLine(l []byte) (msg string, m map[string]interface{}) { +func parseJSONLogLine(l []byte) (msg string, m map[string]any) { // the whole line is valid JSON if err := json.Unmarshal(l, &m); err == nil { return diff --git a/internal/app/machined/pkg/runtime/logging/extract_test.go b/internal/app/machined/pkg/runtime/logging/extract_test.go index 7b4363773e..a7669baacf 100644 --- a/internal/app/machined/pkg/runtime/logging/extract_test.go +++ b/internal/app/machined/pkg/runtime/logging/extract_test.go @@ -37,7 +37,7 @@ func TestParseLogLine(t *testing.T) { Msg: `reconfigured wireguard link`, Time: now, Level: zapcore.InfoLevel, - Fields: map[string]interface{}{ + Fields: map[string]any{ "component": "controller-runtime", "controller": "network.LinkSpecController", "link": "kubespan", @@ -51,7 +51,7 @@ func TestParseLogLine(t *testing.T) { Msg: `finished scheduled compaction`, Time: time.Date(2021, 10, 19, 14, 53, 5, 815000000, time.UTC), Level: zapcore.InfoLevel, - Fields: map[string]interface{}{ + Fields: map[string]any{ "caller": "mvcc/kvstore_compaction.go:57", "compact-revision": float64(34567), "took": "21.041639ms", @@ -64,7 +64,7 @@ func TestParseLogLine(t *testing.T) { Msg: `cleanup warnings time="2021-10-19T14:52:20Z" level=info msg="starting signal loop" namespace=k8s.io pid=2629`, Time: time.Date(2021, 10, 19, 14, 52, 20, 578858689, time.UTC), Level: zapcore.WarnLevel, - Fields: map[string]interface{}{}, + Fields: map[string]any{}, }, }, "kubelet": { @@ -73,7 +73,7 @@ func TestParseLogLine(t *testing.T) { Msg: `RemoveContainer`, Time: time.Date(2021, 10, 26, 16, 46, 4, 792702913, time.UTC), Level: zapcore.InfoLevel, - Fields: map[string]interface{}{ + Fields: map[string]any{ "caller": "topologymanager/scope.go:110", "containerID": "0194fac91ac1d3949497f6912f3c7e73a062c3bf29b6d3da05557d4db2f8482b", "v": float64(0), @@ -87,7 +87,7 @@ func TestParseLogLine(t *testing.T) { Msg: `Failed creating a mirror pod for: pods "kube-controller-manager-talos-dev-qemu-master-1" already exists`, Time: time.Date(2021, 10, 26, 16, 45, 51, 595943212, time.UTC), Level: zapcore.WarnLevel, - Fields: map[string]interface{}{ + Fields: map[string]any{ "caller": "kubelet/kubelet.go:1703", "pod": "kube-system/kube-controller-manager-talos-dev-qemu-master-1", }, diff --git a/internal/app/machined/pkg/runtime/logging/sender_jsonlines.go b/internal/app/machined/pkg/runtime/logging/sender_jsonlines.go index 5e87ba91bd..bf7a21be38 100644 --- a/internal/app/machined/pkg/runtime/logging/sender_jsonlines.go +++ b/internal/app/machined/pkg/runtime/logging/sender_jsonlines.go @@ -50,7 +50,7 @@ func (j *jsonLinesSender) tryLock(ctx context.Context) (unlock func()) { } func (j *jsonLinesSender) marshalJSON(e *runtime.LogEvent) ([]byte, error) { - m := make(map[string]interface{}, len(e.Fields)+3) + m := make(map[string]any, len(e.Fields)+3) for k, v := range e.Fields { m[k] = v } diff --git a/internal/app/machined/pkg/runtime/state.go b/internal/app/machined/pkg/runtime/state.go index 66ae8be568..3d889130ed 100644 --- a/internal/app/machined/pkg/runtime/state.go +++ b/internal/app/machined/pkg/runtime/state.go @@ -56,7 +56,7 @@ type Meta interface { } // ClusterState defines the cluster state. -type ClusterState interface{} +type ClusterState any // V1Alpha2State defines the next generation (v2) interface binding into v1 runtime. type V1Alpha2State interface { diff --git a/internal/app/machined/pkg/runtime/v1alpha1/platform/aws/aws.go b/internal/app/machined/pkg/runtime/v1alpha1/platform/aws/aws.go index 1c4f407299..6d61effdc8 100644 --- a/internal/app/machined/pkg/runtime/v1alpha1/platform/aws/aws.go +++ b/internal/app/machined/pkg/runtime/v1alpha1/platform/aws/aws.go @@ -62,7 +62,7 @@ func (a *AWS) ParseMetadata(metadata *MetadataConfig) (*runtime.PlatformNetworkC networkConfig.Hostnames = append(networkConfig.Hostnames, hostnameSpec) } - publicIPs := []string{} + var publicIPs []string if metadata.PublicIPv4 != "" { publicIPs = append(publicIPs, metadata.PublicIPv4) diff --git a/internal/app/machined/pkg/runtime/v1alpha1/platform/azure/azure.go b/internal/app/machined/pkg/runtime/v1alpha1/platform/azure/azure.go index acd3651695..fbfe31eca6 100644 --- a/internal/app/machined/pkg/runtime/v1alpha1/platform/azure/azure.go +++ b/internal/app/machined/pkg/runtime/v1alpha1/platform/azure/azure.go @@ -92,7 +92,7 @@ func (a *Azure) ParseMetadata(metadata *ComputeMetadata, interfaceAddresses []Ne networkConfig.Hostnames = append(networkConfig.Hostnames, hostnameSpec) } - publicIPs := []string{} + var publicIPs []string // external IP for _, iface := range interfaceAddresses { diff --git a/internal/app/machined/pkg/runtime/v1alpha1/platform/digitalocean/digitalocean.go b/internal/app/machined/pkg/runtime/v1alpha1/platform/digitalocean/digitalocean.go index ca51234d0c..e37f47d7e8 100644 --- a/internal/app/machined/pkg/runtime/v1alpha1/platform/digitalocean/digitalocean.go +++ b/internal/app/machined/pkg/runtime/v1alpha1/platform/digitalocean/digitalocean.go @@ -73,7 +73,7 @@ func (d *DigitalOcean) ParseMetadata(metadata *MetadataConfig) (*runtime.Platfor ConfigLayer: network.ConfigPlatform, }) - publicIPs := []string{} + var publicIPs []string for _, iface := range metadata.Interfaces["public"] { if iface.IPv4 != nil { diff --git a/internal/app/machined/pkg/runtime/v1alpha1/platform/equinixmetal/equinix.go b/internal/app/machined/pkg/runtime/v1alpha1/platform/equinixmetal/equinix.go index 53d65d6fdf..2d2b879952 100644 --- a/internal/app/machined/pkg/runtime/v1alpha1/platform/equinixmetal/equinix.go +++ b/internal/app/machined/pkg/runtime/v1alpha1/platform/equinixmetal/equinix.go @@ -232,7 +232,7 @@ func (p *EquinixMetal) ParseMetadata(ctx context.Context, equinixMetadata *Metad // 2. addresses - publicIPs := []string{} + var publicIPs []string for _, addr := range equinixMetadata.Network.Addresses { if !(addr.Enabled && addr.Management) { diff --git a/internal/app/machined/pkg/runtime/v1alpha1/platform/hcloud/hcloud.go b/internal/app/machined/pkg/runtime/v1alpha1/platform/hcloud/hcloud.go index b37ce0b59b..041b6a64b4 100644 --- a/internal/app/machined/pkg/runtime/v1alpha1/platform/hcloud/hcloud.go +++ b/internal/app/machined/pkg/runtime/v1alpha1/platform/hcloud/hcloud.go @@ -52,7 +52,7 @@ func (h *Hcloud) ParseMetadata(unmarshalledNetworkConfig *NetworkConfig, metadat networkConfig.Hostnames = append(networkConfig.Hostnames, hostnameSpec) } - publicIPs := []string{} + var publicIPs []string if metadata.PublicIPv4 != "" { publicIPs = append(publicIPs, metadata.PublicIPv4) diff --git a/internal/app/machined/pkg/runtime/v1alpha1/platform/scaleway/scaleway.go b/internal/app/machined/pkg/runtime/v1alpha1/platform/scaleway/scaleway.go index 9cbb89ba2c..26a005d87b 100644 --- a/internal/app/machined/pkg/runtime/v1alpha1/platform/scaleway/scaleway.go +++ b/internal/app/machined/pkg/runtime/v1alpha1/platform/scaleway/scaleway.go @@ -53,7 +53,7 @@ func (s *Scaleway) ParseMetadata(metadata *instance.Metadata) (*runtime.Platform networkConfig.Hostnames = append(networkConfig.Hostnames, hostnameSpec) } - publicIPs := []string{} + var publicIPs []string if metadata.PublicIP.Address != "" { publicIPs = append(publicIPs, metadata.PublicIP.Address) diff --git a/internal/app/machined/pkg/runtime/v1alpha1/platform/vultr/vultr.go b/internal/app/machined/pkg/runtime/v1alpha1/platform/vultr/vultr.go index fef5e65d76..d047a03189 100644 --- a/internal/app/machined/pkg/runtime/v1alpha1/platform/vultr/vultr.go +++ b/internal/app/machined/pkg/runtime/v1alpha1/platform/vultr/vultr.go @@ -52,7 +52,7 @@ func (v *Vultr) ParseMetadata(metadata *metadata.MetaData) (*runtime.PlatformNet networkConfig.Hostnames = append(networkConfig.Hostnames, hostnameSpec) } - publicIPs := []string{} + var publicIPs []string for i, addr := range metadata.Interfaces { iface := fmt.Sprintf("eth%d", i) diff --git a/internal/app/machined/pkg/runtime/v1alpha1/v1alpha1_controller.go b/internal/app/machined/pkg/runtime/v1alpha1/v1alpha1_controller.go index 7dba09cbaf..7e6406ef04 100644 --- a/internal/app/machined/pkg/runtime/v1alpha1/v1alpha1_controller.go +++ b/internal/app/machined/pkg/runtime/v1alpha1/v1alpha1_controller.go @@ -104,7 +104,7 @@ func (c *Controller) setupLogging() error { // Run executes all phases known to the controller in serial. `Controller` // aborts immediately if any phase fails. -func (c *Controller) Run(ctx context.Context, seq runtime.Sequence, data interface{}, setters ...runtime.LockOption) error { +func (c *Controller) Run(ctx context.Context, seq runtime.Sequence, data any, setters ...runtime.LockOption) error { // We must ensure that the runtime is configured since all sequences depend // on the runtime. if c.r == nil { @@ -223,7 +223,7 @@ func (c *Controller) ListenForEvents(ctx context.Context) error { return err } -func (c *Controller) run(ctx context.Context, seq runtime.Sequence, phases []runtime.Phase, data interface{}) error { +func (c *Controller) run(ctx context.Context, seq runtime.Sequence, phases []runtime.Phase, data any) error { c.Runtime().Events().Publish(ctx, &machine.SequenceEvent{ Sequence: seq.String(), Action: machine.SequenceEvent_START, @@ -288,7 +288,7 @@ func (c *Controller) run(ctx context.Context, seq runtime.Sequence, phases []run return nil } -func (c *Controller) runPhase(ctx context.Context, phase runtime.Phase, seq runtime.Sequence, data interface{}) error { +func (c *Controller) runPhase(ctx context.Context, phase runtime.Phase, seq runtime.Sequence, data any) error { c.Runtime().Events().Publish(ctx, &machine.PhaseEvent{ Phase: phase.Name, Action: machine.PhaseEvent_START, @@ -319,7 +319,7 @@ func (c *Controller) runPhase(ctx context.Context, phase runtime.Phase, seq runt return eg.Wait() } -func (c *Controller) runTask(ctx context.Context, progress string, f runtime.TaskSetupFunc, seq runtime.Sequence, data interface{}) error { +func (c *Controller) runTask(ctx context.Context, progress string, f runtime.TaskSetupFunc, seq runtime.Sequence, data any) error { task, taskName := f(seq, data) if task == nil { return nil @@ -359,7 +359,7 @@ func (c *Controller) runTask(ctx context.Context, progress string, f runtime.Tas } //nolint:gocyclo -func (c *Controller) phases(seq runtime.Sequence, data interface{}) ([]runtime.Phase, error) { +func (c *Controller) phases(seq runtime.Sequence, data any) ([]runtime.Phase, error) { var phases []runtime.Phase switch seq { diff --git a/internal/app/machined/pkg/runtime/v1alpha1/v1alpha1_controller_test.go b/internal/app/machined/pkg/runtime/v1alpha1/v1alpha1_controller_test.go index fb07051365..db6a8508f3 100644 --- a/internal/app/machined/pkg/runtime/v1alpha1/v1alpha1_controller_test.go +++ b/internal/app/machined/pkg/runtime/v1alpha1/v1alpha1_controller_test.go @@ -67,8 +67,8 @@ func (m *mockSequencer) Upgrade(r runtime.Runtime, req *machine.UpgradeRequest) return m.phases[runtime.SequenceUpgrade] } -func (m *mockSequencer) trackCall(name string, doneCh chan struct{}) func(runtime.Sequence, interface{}) (runtime.TaskExecutionFunc, string) { - return func(seq runtime.Sequence, data interface{}) (runtime.TaskExecutionFunc, string) { +func (m *mockSequencer) trackCall(name string, doneCh chan struct{}) func(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) { + return func(seq runtime.Sequence, data any) (runtime.TaskExecutionFunc, string) { return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) error { if doneCh != nil { defer func() { @@ -97,8 +97,8 @@ func TestRun(t *testing.T) { from runtime.Sequence to runtime.Sequence expectError error - dataFrom interface{} - dataTo interface{} + dataFrom any + dataTo any }{ { name: "reboot should take over boot", @@ -202,7 +202,7 @@ func TestRun(t *testing.T) { } } -func wait(seq runtime.Sequence, data interface{}) (runtime.TaskExecutionFunc, string) { +func wait(seq runtime.Sequence, data any) (runtime.TaskExecutionFunc, string) { return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) error { select { case <-ctx.Done(): diff --git a/internal/app/machined/pkg/runtime/v1alpha1/v1alpha1_sequencer_tasks.go b/internal/app/machined/pkg/runtime/v1alpha1/v1alpha1_sequencer_tasks.go index 138e79449e..30338049df 100644 --- a/internal/app/machined/pkg/runtime/v1alpha1/v1alpha1_sequencer_tasks.go +++ b/internal/app/machined/pkg/runtime/v1alpha1/v1alpha1_sequencer_tasks.go @@ -642,7 +642,7 @@ func StartSyslogd(r runtime.Sequence, _ any) (runtime.TaskExecutionFunc, string) } // StartDashboard represents the task to start dashboard. -func StartDashboard(_ runtime.Sequence, _ interface{}) (runtime.TaskExecutionFunc, string) { +func StartDashboard(_ runtime.Sequence, _ any) (runtime.TaskExecutionFunc, string) { return func(_ context.Context, _ *log.Logger, r runtime.Runtime) error { system.Services(r).LoadAndStart(&services.Dashboard{}) @@ -726,7 +726,7 @@ func StartAllServices(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) svcs.LoadAndStart(serviceList...) - all := []conditions.Condition{} + var all []conditions.Condition logger.Printf("waiting for %d services", len(svcs.List())) diff --git a/internal/app/machined/pkg/system/events/events.go b/internal/app/machined/pkg/system/events/events.go index f7f8b28b6c..cf1ace0ddc 100644 --- a/internal/app/machined/pkg/system/events/events.go +++ b/internal/app/machined/pkg/system/events/events.go @@ -141,8 +141,8 @@ func (events *ServiceEvents) AsProto(count int) *machineapi.ServiceEvents { } // Recorder adds new event to the history of events, formatting message with args using Sprintf. -type Recorder func(newstate ServiceState, message string, args ...interface{}) +type Recorder func(newstate ServiceState, message string, args ...any) // NullRecorder discards events. -func NullRecorder(newstate ServiceState, message string, args ...interface{}) { +func NullRecorder(newstate ServiceState, message string, args ...any) { } diff --git a/internal/app/machined/pkg/system/events/events_test.go b/internal/app/machined/pkg/system/events/events_test.go index 2414db08a7..2132c8d49d 100644 --- a/internal/app/machined/pkg/system/events/events_test.go +++ b/internal/app/machined/pkg/system/events/events_test.go @@ -65,7 +65,8 @@ func (suite *EventsSuite) TestOverflow() { suite.Assert().Equal([]events.ServiceEvent(nil), e.Get(0)) suite.assertEvents([]string{strconv.Itoa(numEvents - 1)}, e.Get(1)) - expected := []string{} + var expected []string + for i := numEvents - events.MaxEventsToKeep; i < numEvents; i++ { expected = append(expected, strconv.Itoa(i)) } diff --git a/internal/app/machined/pkg/system/runner/containerd/containerd.go b/internal/app/machined/pkg/system/runner/containerd/containerd.go index 95856a6cc6..2f7053b0cc 100644 --- a/internal/app/machined/pkg/system/runner/containerd/containerd.go +++ b/internal/app/machined/pkg/system/runner/containerd/containerd.go @@ -268,7 +268,7 @@ func (c *containerdRunner) newContainerOpts( image containerd.Image, specOpts []oci.SpecOpts, ) []containerd.NewContainerOpts { - containerOpts := []containerd.NewContainerOpts{} + var containerOpts []containerd.NewContainerOpts if image != nil { containerOpts = append( @@ -292,7 +292,7 @@ func (c *containerdRunner) newContainerOpts( } func (c *containerdRunner) newOCISpecOpts(image oci.Image) []oci.SpecOpts { - specOpts := []oci.SpecOpts{} + var specOpts []oci.SpecOpts if image != nil { specOpts = append( diff --git a/internal/app/machined/pkg/system/runner/containerd/containerd_test.go b/internal/app/machined/pkg/system/runner/containerd/containerd_test.go index 77dbba2ce8..eaebcc5875 100644 --- a/internal/app/machined/pkg/system/runner/containerd/containerd_test.go +++ b/internal/app/machined/pkg/system/runner/containerd/containerd_test.go @@ -41,7 +41,7 @@ const ( busyboxImage = "docker.io/library/busybox:latest" ) -func MockEventSink(state events.ServiceState, message string, args ...interface{}) { +func MockEventSink(state events.ServiceState, message string, args ...any) { log.Printf("state %s: %s", state, fmt.Sprintf(message, args...)) } diff --git a/internal/app/machined/pkg/system/runner/goroutine/goroutine_test.go b/internal/app/machined/pkg/system/runner/goroutine/goroutine_test.go index afa6d238c2..526d70443c 100644 --- a/internal/app/machined/pkg/system/runner/goroutine/goroutine_test.go +++ b/internal/app/machined/pkg/system/runner/goroutine/goroutine_test.go @@ -27,7 +27,7 @@ import ( v1alpha1cfg "github.com/siderolabs/talos/pkg/machinery/config/types/v1alpha1" ) -func MockEventSink(state events.ServiceState, message string, args ...interface{}) { +func MockEventSink(state events.ServiceState, message string, args ...any) { log.Printf("state %s: %s", state, fmt.Sprintf(message, args...)) } diff --git a/internal/app/machined/pkg/system/runner/process/process_test.go b/internal/app/machined/pkg/system/runner/process/process_test.go index 5394647c2b..3ebb38a34c 100644 --- a/internal/app/machined/pkg/system/runner/process/process_test.go +++ b/internal/app/machined/pkg/system/runner/process/process_test.go @@ -25,7 +25,7 @@ import ( "github.com/siderolabs/talos/internal/app/machined/pkg/system/runner/restart" ) -func MockEventSink(state events.ServiceState, message string, args ...interface{}) { +func MockEventSink(state events.ServiceState, message string, args ...any) { log.Printf("state %s: %s", state, fmt.Sprintf(message, args...)) } diff --git a/internal/app/machined/pkg/system/runner/restart/restart_test.go b/internal/app/machined/pkg/system/runner/restart/restart_test.go index 047714b776..f95d545c41 100644 --- a/internal/app/machined/pkg/system/runner/restart/restart_test.go +++ b/internal/app/machined/pkg/system/runner/restart/restart_test.go @@ -69,7 +69,7 @@ func (m *MockRunner) String() string { return "MockRunner()" } -func MockEventSink(state events.ServiceState, message string, args ...interface{}) { +func MockEventSink(state events.ServiceState, message string, args ...any) { log.Printf("state %s: %s", state, fmt.Sprintf(message, args...)) } diff --git a/internal/app/machined/pkg/system/service_runner.go b/internal/app/machined/pkg/system/service_runner.go index 009e4bfc5d..9e7c6b9b68 100644 --- a/internal/app/machined/pkg/system/service_runner.go +++ b/internal/app/machined/pkg/system/service_runner.go @@ -70,7 +70,7 @@ func (svcrunner *ServiceRunner) GetState() events.ServiceState { } // UpdateState implements events.Recorder. -func (svcrunner *ServiceRunner) UpdateState(ctx context.Context, newstate events.ServiceState, message string, args ...interface{}) { +func (svcrunner *ServiceRunner) UpdateState(ctx context.Context, newstate events.ServiceState, message string, args ...any) { svcrunner.mu.Lock() event := events.ServiceEvent{ @@ -280,7 +280,7 @@ func (svcrunner *ServiceRunner) run(ctx context.Context, runnr runner.Runner) er errCh := make(chan error) go func() { - errCh <- runnr.Run(func(s events.ServiceState, msg string, args ...interface{}) { + errCh <- runnr.Run(func(s events.ServiceState, msg string, args ...any) { svcrunner.UpdateState(ctx, s, msg, args...) }) }() diff --git a/internal/app/machined/pkg/system/service_runner_test.go b/internal/app/machined/pkg/system/service_runner_test.go index 0b437ab34e..4429fed718 100644 --- a/internal/app/machined/pkg/system/service_runner_test.go +++ b/internal/app/machined/pkg/system/service_runner_test.go @@ -22,7 +22,7 @@ type ServiceRunnerSuite struct { } func (suite *ServiceRunnerSuite) assertStateSequence(expectedStates []events.ServiceState, sr *system.ServiceRunner) { - states := []events.ServiceState{} + states := make([]events.ServiceState, 0, 1000) for _, event := range sr.GetEventHistory(1000) { states = append(states, event.State) diff --git a/internal/app/machined/pkg/system/services/etcd.go b/internal/app/machined/pkg/system/services/etcd.go index 0bc7baf651..9224b27bd1 100644 --- a/internal/app/machined/pkg/system/services/etcd.go +++ b/internal/app/machined/pkg/system/services/etcd.go @@ -350,7 +350,7 @@ func buildInitialCluster(ctx context.Context, r runtime.Runtime, name string, pe return retry.ExpectedError(err) } - conf := []string{} + var conf []string for _, memb := range resp.Members { for _, u := range memb.PeerURLs { diff --git a/internal/app/machined/pkg/system/services/extension.go b/internal/app/machined/pkg/system/services/extension.go index 99b3fd3564..1d7dbc39ba 100644 --- a/internal/app/machined/pkg/system/services/extension.go +++ b/internal/app/machined/pkg/system/services/extension.go @@ -69,7 +69,7 @@ func (svc *Extension) PostFunc(r runtime.Runtime, state events.ServiceState) (er // Condition implements the Service interface. func (svc *Extension) Condition(r runtime.Runtime) conditions.Condition { - conds := []conditions.Condition{} + var conds []conditions.Condition if svc.Spec.Container.EnvironmentFile != "" { // add a dependency on the environment file diff --git a/internal/app/machined/pkg/system/services/mocks/snapshotter.go b/internal/app/machined/pkg/system/services/mocks/snapshotter.go index 1e33be4b65..aa6656f39c 100644 --- a/internal/app/machined/pkg/system/services/mocks/snapshotter.go +++ b/internal/app/machined/pkg/system/services/mocks/snapshotter.go @@ -57,7 +57,7 @@ func (mr *MockSnapshotterMockRecorder) Close() *gomock.Call { // Commit mocks base method. func (m *MockSnapshotter) Commit(ctx context.Context, name, key string, opts ...snapshots.Opt) error { m.ctrl.T.Helper() - varargs := []interface{}{ctx, name, key} + varargs := []any{ctx, name, key} for _, a := range opts { varargs = append(varargs, a) } @@ -67,9 +67,9 @@ func (m *MockSnapshotter) Commit(ctx context.Context, name, key string, opts ... } // Commit indicates an expected call of Commit. -func (mr *MockSnapshotterMockRecorder) Commit(ctx, name, key interface{}, opts ...interface{}) *gomock.Call { +func (mr *MockSnapshotterMockRecorder) Commit(ctx, name, key any, opts ...any) *gomock.Call { mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, name, key}, opts...) + varargs := append([]any{ctx, name, key}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Commit", reflect.TypeOf((*MockSnapshotter)(nil).Commit), varargs...) } @@ -83,7 +83,7 @@ func (m *MockSnapshotter) Mounts(ctx context.Context, key string) ([]mount.Mount } // Mounts indicates an expected call of Mounts. -func (mr *MockSnapshotterMockRecorder) Mounts(ctx, key interface{}) *gomock.Call { +func (mr *MockSnapshotterMockRecorder) Mounts(ctx, key any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Mounts", reflect.TypeOf((*MockSnapshotter)(nil).Mounts), ctx, key) } @@ -91,7 +91,7 @@ func (mr *MockSnapshotterMockRecorder) Mounts(ctx, key interface{}) *gomock.Call // Prepare mocks base method. func (m *MockSnapshotter) Prepare(ctx context.Context, key, parent string, opts ...snapshots.Opt) ([]mount.Mount, error) { m.ctrl.T.Helper() - varargs := []interface{}{ctx, key, parent} + varargs := []any{ctx, key, parent} for _, a := range opts { varargs = append(varargs, a) } @@ -102,9 +102,9 @@ func (m *MockSnapshotter) Prepare(ctx context.Context, key, parent string, opts } // Prepare indicates an expected call of Prepare. -func (mr *MockSnapshotterMockRecorder) Prepare(ctx, key, parent interface{}, opts ...interface{}) *gomock.Call { +func (mr *MockSnapshotterMockRecorder) Prepare(ctx, key, parent any, opts ...any) *gomock.Call { mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, key, parent}, opts...) + varargs := append([]any{ctx, key, parent}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Prepare", reflect.TypeOf((*MockSnapshotter)(nil).Prepare), varargs...) } @@ -117,7 +117,7 @@ func (m *MockSnapshotter) Remove(ctx context.Context, key string) error { } // Remove indicates an expected call of Remove. -func (mr *MockSnapshotterMockRecorder) Remove(ctx, key interface{}) *gomock.Call { +func (mr *MockSnapshotterMockRecorder) Remove(ctx, key any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockSnapshotter)(nil).Remove), ctx, key) } @@ -132,7 +132,7 @@ func (m *MockSnapshotter) Stat(ctx context.Context, key string) (snapshots.Info, } // Stat indicates an expected call of Stat. -func (mr *MockSnapshotterMockRecorder) Stat(ctx, key interface{}) *gomock.Call { +func (mr *MockSnapshotterMockRecorder) Stat(ctx, key any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stat", reflect.TypeOf((*MockSnapshotter)(nil).Stat), ctx, key) } @@ -140,7 +140,7 @@ func (mr *MockSnapshotterMockRecorder) Stat(ctx, key interface{}) *gomock.Call { // Update mocks base method. func (m *MockSnapshotter) Update(ctx context.Context, info snapshots.Info, fieldpaths ...string) (snapshots.Info, error) { m.ctrl.T.Helper() - varargs := []interface{}{ctx, info} + varargs := []any{ctx, info} for _, a := range fieldpaths { varargs = append(varargs, a) } @@ -151,9 +151,9 @@ func (m *MockSnapshotter) Update(ctx context.Context, info snapshots.Info, field } // Update indicates an expected call of Update. -func (mr *MockSnapshotterMockRecorder) Update(ctx, info interface{}, fieldpaths ...interface{}) *gomock.Call { +func (mr *MockSnapshotterMockRecorder) Update(ctx, info any, fieldpaths ...any) *gomock.Call { mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, info}, fieldpaths...) + varargs := append([]any{ctx, info}, fieldpaths...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockSnapshotter)(nil).Update), varargs...) } @@ -167,7 +167,7 @@ func (m *MockSnapshotter) Usage(ctx context.Context, key string) (snapshots.Usag } // Usage indicates an expected call of Usage. -func (mr *MockSnapshotterMockRecorder) Usage(ctx, key interface{}) *gomock.Call { +func (mr *MockSnapshotterMockRecorder) Usage(ctx, key any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Usage", reflect.TypeOf((*MockSnapshotter)(nil).Usage), ctx, key) } @@ -175,7 +175,7 @@ func (mr *MockSnapshotterMockRecorder) Usage(ctx, key interface{}) *gomock.Call // View mocks base method. func (m *MockSnapshotter) View(ctx context.Context, key, parent string, opts ...snapshots.Opt) ([]mount.Mount, error) { m.ctrl.T.Helper() - varargs := []interface{}{ctx, key, parent} + varargs := []any{ctx, key, parent} for _, a := range opts { varargs = append(varargs, a) } @@ -186,16 +186,16 @@ func (m *MockSnapshotter) View(ctx context.Context, key, parent string, opts ... } // View indicates an expected call of View. -func (mr *MockSnapshotterMockRecorder) View(ctx, key, parent interface{}, opts ...interface{}) *gomock.Call { +func (mr *MockSnapshotterMockRecorder) View(ctx, key, parent any, opts ...any) *gomock.Call { mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, key, parent}, opts...) + varargs := append([]any{ctx, key, parent}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "View", reflect.TypeOf((*MockSnapshotter)(nil).View), varargs...) } // Walk mocks base method. func (m *MockSnapshotter) Walk(ctx context.Context, fn snapshots.WalkFunc, filters ...string) error { m.ctrl.T.Helper() - varargs := []interface{}{ctx, fn} + varargs := []any{ctx, fn} for _, a := range filters { varargs = append(varargs, a) } @@ -205,9 +205,9 @@ func (m *MockSnapshotter) Walk(ctx context.Context, fn snapshots.WalkFunc, filte } // Walk indicates an expected call of Walk. -func (mr *MockSnapshotterMockRecorder) Walk(ctx, fn interface{}, filters ...interface{}) *gomock.Call { +func (mr *MockSnapshotterMockRecorder) Walk(ctx, fn any, filters ...any) *gomock.Call { mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, fn}, filters...) + varargs := append([]any{ctx, fn}, filters...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Walk", reflect.TypeOf((*MockSnapshotter)(nil).Walk), varargs...) } @@ -243,7 +243,7 @@ func (m *MockCleaner) Cleanup(ctx context.Context) error { } // Cleanup indicates an expected call of Cleanup. -func (mr *MockCleanerMockRecorder) Cleanup(ctx interface{}) *gomock.Call { +func (mr *MockCleanerMockRecorder) Cleanup(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Cleanup", reflect.TypeOf((*MockCleaner)(nil).Cleanup), ctx) } diff --git a/internal/app/syslogd/syslogd_test.go b/internal/app/syslogd/syslogd_test.go index 5f21913c96..08b14b1827 100644 --- a/internal/app/syslogd/syslogd_test.go +++ b/internal/app/syslogd/syslogd_test.go @@ -64,7 +64,7 @@ func TestParsing(t *testing.T) { select { case msg := <-ch.ch: - var parsed map[string]interface{} + var parsed map[string]any require.NoError(t, json.Unmarshal(msg, &parsed)) diff --git a/internal/integration/api/serviceaccount.go b/internal/integration/api/serviceaccount.go index 4cb35a8753..748af10423 100644 --- a/internal/integration/api/serviceaccount.go +++ b/internal/integration/api/serviceaccount.go @@ -216,13 +216,13 @@ func (suite *ServiceAccountSuite) getCRD() (*unstructured.Unstructured, error) { func (suite *ServiceAccountSuite) createServiceAccount(ns string, name string, roles []string) (*unstructured.Unstructured, error) { return suite.DynamicClient.Resource(serviceAccountGVR).Namespace(ns).Create(suite.ctx, &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": fmt.Sprintf("%s/%s", constants.ServiceAccountResourceGroup, constants.ServiceAccountResourceVersion), "kind": constants.ServiceAccountResourceKind, - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": name, }, - "spec": map[string]interface{}{ + "spec": map[string]any{ "roles": roles, }, }, diff --git a/internal/integration/cli/diskusage.go b/internal/integration/cli/diskusage.go index f9635e879b..3503c06ead 100644 --- a/internal/integration/cli/diskusage.go +++ b/internal/integration/cli/diskusage.go @@ -32,7 +32,7 @@ type duInfo struct { } func splitLine(line string) []string { - columns := []string{} + var columns []string parts := strings.Split(line, " ") for _, part := range parts { diff --git a/internal/integration/cli/gen.go b/internal/integration/cli/gen.go index 4fd9c90585..b765b192ea 100644 --- a/internal/integration/cli/gen.go +++ b/internal/integration/cli/gen.go @@ -132,7 +132,7 @@ func (suite *GenSuite) TestGenConfigURLValidation() { // TestGenConfigPatchJSON6902 verifies that gen config --config-patch works with JSON patches. func (suite *GenSuite) TestGenConfigPatchJSON6902() { - patch, err := json.Marshal([]map[string]interface{}{ + patch, err := json.Marshal([]map[string]any{ { "op": "replace", "path": "/cluster/clusterName", @@ -147,8 +147,8 @@ func (suite *GenSuite) TestGenConfigPatchJSON6902() { // TestGenConfigPatchStrategic verifies that gen config --config-patch works with strategic merge patches. func (suite *GenSuite) TestGenConfigPatchStrategic() { - patch, err := yaml.Marshal(map[string]interface{}{ - "cluster": map[string]interface{}{ + patch, err := yaml.Marshal(map[string]any{ + "cluster": map[string]any{ "clusterName": "bar", }, }) diff --git a/internal/integration/cli/machineconfig.go b/internal/integration/cli/machineconfig.go index 50bc0bcc27..89b70221f3 100644 --- a/internal/integration/cli/machineconfig.go +++ b/internal/integration/cli/machineconfig.go @@ -67,7 +67,7 @@ func (suite *MachineConfigSuite) TestGen() { // TestPatchPrintStdout tests the patch subcommand with output set to stdout // with multiple patches from the command line and from file. func (suite *MachineConfigSuite) TestPatchPrintStdout() { - patch1, err := json.Marshal([]map[string]interface{}{ + patch1, err := json.Marshal([]map[string]any{ { "op": "replace", "path": "/cluster/clusterName", @@ -76,7 +76,7 @@ func (suite *MachineConfigSuite) TestPatchPrintStdout() { }) suite.Require().NoError(err) - patch2, err := json.Marshal([]map[string]interface{}{ + patch2, err := json.Marshal([]map[string]any{ { "op": "replace", "path": "/cluster/controlPlane/endpoint", @@ -121,7 +121,7 @@ func (suite *MachineConfigSuite) TestPatchPrintStdout() { // TestPatchWriteToFile tests the patch subcommand with output set to a file. func (suite *MachineConfigSuite) TestPatchWriteToFile() { - patch1, err := json.Marshal([]map[string]interface{}{ + patch1, err := json.Marshal([]map[string]any{ { "op": "replace", "path": "/cluster/clusterName", diff --git a/internal/integration/cli/patch.go b/internal/integration/cli/patch.go index 96116f9bb8..5395e231d1 100644 --- a/internal/integration/cli/patch.go +++ b/internal/integration/cli/patch.go @@ -54,11 +54,11 @@ func (suite *PatchSuite) TestSuccess() { func (suite *PatchSuite) TestError() { node := suite.RandomDiscoveredNodeInternalIP(machine.TypeControlPlane) - patch := []map[string]interface{}{ + patch := []map[string]any{ { "op": "crash", "path": "/cluster/proxy", - "value": map[string]interface{}{ + "value": map[string]any{ "image": fmt.Sprintf("%s:v%s", constants.KubeProxyImage, constants.DefaultKubernetesVersion), }, }, diff --git a/internal/pkg/configuration/configuration.go b/internal/pkg/configuration/configuration.go index 4147abe102..2b54a0c81d 100644 --- a/internal/pkg/configuration/configuration.go +++ b/internal/pkg/configuration/configuration.go @@ -40,7 +40,7 @@ func Generate(ctx context.Context, in *machine.GenerateConfigurationRequest) (re case "v1alpha1": machineType := v1alpha1machine.Type(in.MachineConfig.Type) - options := []generate.Option{} + var options []generate.Option if in.MachineConfig.NetworkConfig != nil { networkConfig := &v1alpha1.NetworkConfig{ diff --git a/internal/pkg/containers/container.go b/internal/pkg/containers/container.go index b286a785a5..6c50994bae 100644 --- a/internal/pkg/containers/container.go +++ b/internal/pkg/containers/container.go @@ -89,7 +89,8 @@ func (c *Container) GetLogChunker(ctx context.Context, follow bool, tailLines in } } - chunkerOptions := []file.Option{} + var chunkerOptions []file.Option + if follow { chunkerOptions = append(chunkerOptions, file.WithFollow()) } diff --git a/internal/pkg/containers/containerd/containerd_test.go b/internal/pkg/containers/containerd/containerd_test.go index 5564dc5cf7..3b33a09d36 100644 --- a/internal/pkg/containers/containerd/containerd_test.go +++ b/internal/pkg/containers/containerd/containerd_test.go @@ -37,7 +37,7 @@ const ( busyboxImageDigest = "sha256:4b6ad3a68d34da29bf7c8ccb5d355ba8b4babcad1f99798204e7abb43e54ee3d" ) -func MockEventSink(state events.ServiceState, message string, args ...interface{}) { +func MockEventSink(state events.ServiceState, message string, args ...any) { } //nolint:maligned @@ -163,7 +163,7 @@ func (suite *ContainerdSuite) run(runners ...runner.Runner) { suite.containersWg.Add(1) go func(r runner.Runner) { - runningSink := func(state events.ServiceState, message string, args ...interface{}) { + runningSink := func(state events.ServiceState, message string, args ...any) { if state == events.StateRunning { runningCh <- true } diff --git a/internal/pkg/containers/cri/cri.go b/internal/pkg/containers/cri/cri.go index d9c5ed498f..c07e1b8507 100644 --- a/internal/pkg/containers/cri/cri.go +++ b/internal/pkg/containers/cri/cri.go @@ -271,7 +271,7 @@ func (i *inspector) buildContainer(container *runtimeapi.Container) (*ctrs.Conta } if info, ok := containerInfo["info"]; ok { - var verboseInfo map[string]interface{} + var verboseInfo map[string]any if err := json.Unmarshal([]byte(info), &verboseInfo); err == nil { if pid, ok := verboseInfo["pid"]; ok { diff --git a/internal/pkg/containers/cri/cri_test.go b/internal/pkg/containers/cri/cri_test.go index f3e0c0717f..850f0504c4 100644 --- a/internal/pkg/containers/cri/cri_test.go +++ b/internal/pkg/containers/cri/cri_test.go @@ -37,7 +37,7 @@ const ( // pauseImageDigest = "sha256:da86e6ba6ca197bf6bc5e9d900febd906b133eaa4750e6bed647b0fbe50ed43e". ) -func MockEventSink(state events.ServiceState, message string, args ...interface{}) { +func MockEventSink(state events.ServiceState, message string, args ...any) { } type CRISuite struct { diff --git a/internal/pkg/cri/cri_test.go b/internal/pkg/cri/cri_test.go index 9c9bfac2d5..9f4ad59274 100644 --- a/internal/pkg/cri/cri_test.go +++ b/internal/pkg/cri/cri_test.go @@ -31,8 +31,8 @@ const ( busyboxImage = "docker.io/library/busybox:1.30.1" ) -func MockEventSink(t *testing.T) func(state events.ServiceState, message string, args ...interface{}) { - return func(state events.ServiceState, message string, args ...interface{}) { +func MockEventSink(t *testing.T) func(state events.ServiceState, message string, args ...any) { + return func(state events.ServiceState, message string, args ...any) { t.Logf(message, args...) } } diff --git a/internal/pkg/discovery/registry/kubernetes.go b/internal/pkg/discovery/registry/kubernetes.go index f4f6fbc459..13a4ffccfe 100644 --- a/internal/pkg/discovery/registry/kubernetes.go +++ b/internal/pkg/discovery/registry/kubernetes.go @@ -269,7 +269,7 @@ func (r *Kubernetes) Watch(ctx context.Context, logger *zap.Logger) (<-chan stru notifyCh := make(chan struct{}, 1) - notify := func(_ interface{}) { + notify := func(_ any) { select { case notifyCh <- struct{}{}: default: @@ -287,7 +287,7 @@ func (r *Kubernetes) Watch(ctx context.Context, logger *zap.Logger) (<-chan stru if _, err := r.nodes.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: notify, DeleteFunc: notify, - UpdateFunc: func(_, _ interface{}) { notify(nil) }, + UpdateFunc: func(_, _ any) { notify(nil) }, }); err != nil { return nil, nil, fmt.Errorf("failed to add event handler: %w", err) } diff --git a/internal/pkg/encryption/encryption.go b/internal/pkg/encryption/encryption.go index 83c408e70a..0fb2391598 100644 --- a/internal/pkg/encryption/encryption.go +++ b/internal/pkg/encryption/encryption.go @@ -44,7 +44,7 @@ func NewHandler(device *blockdevice.BlockDevice, partition *gpt.Partition, encry return nil, err } - opts := []luks.Option{} + var opts []luks.Option if encryptionConfig.KeySize() != 0 { opts = append(opts, luks.WithKeySize(encryptionConfig.KeySize())) } diff --git a/internal/pkg/mount/system.go b/internal/pkg/mount/system.go index 732d660c5b..b0ccde996e 100644 --- a/internal/pkg/mount/system.go +++ b/internal/pkg/mount/system.go @@ -104,7 +104,7 @@ func SystemMountPointForLabel(ctx context.Context, device *blockdevice.BlockDevi o := NewDefaultOptions(opts...) - preMountHooks := []Hook{} + var preMountHooks []Hook if o.Encryption != nil { encryptionHandler, err := encryption.NewHandler( diff --git a/internal/pkg/secureboot/uki/assemble.go b/internal/pkg/secureboot/uki/assemble.go index 62286d2392..9d3627e30c 100644 --- a/internal/pkg/secureboot/uki/assemble.go +++ b/internal/pkg/secureboot/uki/assemble.go @@ -56,7 +56,7 @@ func (builder *Builder) assemble() error { } // create the output file - args := []string{} + args := make([]string, 0, len(builder.sections)+2) for _, section := range builder.sections { if !section.Append { diff --git a/internal/pkg/tui/components/form.go b/internal/pkg/tui/components/form.go index 2386e9cd0b..d1b20f84d6 100644 --- a/internal/pkg/tui/components/form.go +++ b/internal/pkg/tui/components/form.go @@ -44,20 +44,20 @@ func NewSeparator(description string) *Item { type Item struct { Name string description string - dest interface{} - options []interface{} + dest any + options []any } // TableHeaders represents table headers list for item options which are using table representation. -type TableHeaders []interface{} +type TableHeaders []any // NewTableHeaders creates TableHeaders object. -func NewTableHeaders(headers ...interface{}) TableHeaders { +func NewTableHeaders(headers ...any) TableHeaders { return TableHeaders(headers) } // NewItem creates new form item. -func NewItem(name, description string, dest interface{}, options ...interface{}) *Item { +func NewItem(name, description string, dest any, options ...any) *Item { return &Item{ Name: name, dest: dest, @@ -75,7 +75,7 @@ func (item *Item) assign(value string) error { // //nolint:gocyclo,cyclop func (item *Item) createFormItems() ([]tview.Primitive, error) { - res := []tview.Primitive{} + var res []tview.Primitive v := reflect.ValueOf(item.dest) if v.Kind() == reflect.Ptr { diff --git a/internal/pkg/tui/components/table.go b/internal/pkg/tui/components/table.go index 6590156172..5ac2e507ac 100644 --- a/internal/pkg/tui/components/table.go +++ b/internal/pkg/tui/components/table.go @@ -22,7 +22,7 @@ func NewTable() *Table { Table: tview.NewTable(), selectedRow: -1, hoveredRow: -1, - rows: [][]interface{}{}, + rows: [][]any{}, } hasFocus := false @@ -77,16 +77,16 @@ type Table struct { selectedRow int hoveredRow int onRowSelected func(row int) - rows [][]interface{} + rows [][]any } // SetHeader sets table header. -func (t *Table) SetHeader(keys ...interface{}) { +func (t *Table) SetHeader(keys ...any) { t.AddRow(keys...) } // AddRow adds a new row to the table. -func (t *Table) AddRow(columns ...interface{}) { +func (t *Table) AddRow(columns ...any) { row := t.GetRowCount() col := backgroundColor textColor := tview.Styles.PrimaryTextColor @@ -201,7 +201,7 @@ func (t *Table) SetRowSelectedFunc(callback func(row int)) { } // GetValue returns value in row/column. -func (t *Table) GetValue(row, column int) interface{} { +func (t *Table) GetValue(row, column int) any { if row < len(t.rows) && column < len(t.rows[row]) { return t.rows[row][column] } diff --git a/internal/pkg/tui/installer/installer.go b/internal/pkg/tui/installer/installer.go index 93fd90e11a..5d8e0afb47 100644 --- a/internal/pkg/tui/installer/installer.go +++ b/internal/pkg/tui/installer/installer.go @@ -176,7 +176,8 @@ func (installer *Installer) configure() error { ) currentPage := 0 - menuButtons := []*components.MenuButton{} + + var menuButtons []*components.MenuButton done := make(chan struct{}) state := installer.state diff --git a/internal/pkg/tui/installer/state.go b/internal/pkg/tui/installer/state.go index 3db83a7fb9..421bc6b162 100644 --- a/internal/pkg/tui/installer/state.go +++ b/internal/pkg/tui/installer/state.go @@ -62,7 +62,7 @@ func NewState(ctx context.Context, installer *Installer, conn *Connection) (*Sta opts.ClusterConfig.ControlPlane.Endpoint = fmt.Sprintf("https://%s", nethelpers.JoinHostPort(conn.nodeEndpoint, constants.DefaultControlPlanePort)) } - installDiskOptions := []interface{}{ + installDiskOptions := []any{ components.NewTableHeaders("DEVICE NAME", "MODEL NAME", "SIZE"), } @@ -81,16 +81,16 @@ func NewState(ctx context.Context, installer *Installer, conn *Connection) (*Sta } } - var machineTypes []interface{} + var machineTypes []any if conn.ExpandingCluster() { - machineTypes = []interface{}{ + machineTypes = []any{ " worker ", machineapi.MachineConfig_MachineType(machine.TypeWorker), " control plane ", machineapi.MachineConfig_MachineType(machine.TypeControlPlane), } opts.MachineConfig.Type = machineapi.MachineConfig_MachineType(machine.TypeControlPlane) } else { - machineTypes = []interface{}{ + machineTypes = []any{ " control plane ", machineapi.MachineConfig_MachineType(machine.TypeInit), } } diff --git a/pkg/argsbuilder/argsbuilder_args.go b/pkg/argsbuilder/argsbuilder_args.go index 128dd59dd9..136fc138d3 100644 --- a/pkg/argsbuilder/argsbuilder_args.go +++ b/pkg/argsbuilder/argsbuilder_args.go @@ -94,7 +94,7 @@ func (a Args) Args() []string { keys := maps.Keys(a) sort.Strings(keys) - args := []string{} + args := make([]string, 0, len(a)) for _, key := range keys { args = append(args, fmt.Sprintf("--%s=%s", key, a[key])) diff --git a/pkg/cli/output.go b/pkg/cli/output.go index ca18032c3e..65b0dc6157 100644 --- a/pkg/cli/output.go +++ b/pkg/cli/output.go @@ -11,7 +11,7 @@ import ( ) // Fatalf prints formatted message to stderr and aborts execution. -func Fatalf(message string, args ...interface{}) { +func Fatalf(message string, args ...any) { if !strings.HasSuffix(message, "\n") { message += "\n" } @@ -21,7 +21,7 @@ func Fatalf(message string, args ...interface{}) { } // Warning prints formatted message to stderr. -func Warning(message string, args ...interface{}) { +func Warning(message string, args ...any) { if !strings.HasSuffix(message, "\n") { message += "\n" } diff --git a/pkg/cluster/kubernetes/talos_managed.go b/pkg/cluster/kubernetes/talos_managed.go index e525d16319..f81a9b1612 100644 --- a/pkg/cluster/kubernetes/talos_managed.go +++ b/pkg/cluster/kubernetes/talos_managed.go @@ -469,9 +469,9 @@ func checkPodStatus(ctx context.Context, cluster UpgradeProvider, options Upgrad } if _, err := informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { channel.SendWithContext(ctx, notifyCh, obj.(*v1.Pod)) }, - DeleteFunc: func(_ interface{}) {}, - UpdateFunc: func(_, obj interface{}) { channel.SendWithContext(ctx, notifyCh, obj.(*v1.Pod)) }, + AddFunc: func(obj any) { channel.SendWithContext(ctx, notifyCh, obj.(*v1.Pod)) }, + DeleteFunc: func(_ any) {}, + UpdateFunc: func(_, obj any) { channel.SendWithContext(ctx, notifyCh, obj.(*v1.Pod)) }, }); err != nil { return fmt.Errorf("error adding watch event handler: %w", err) } diff --git a/pkg/cluster/kubernetes/upgrade.go b/pkg/cluster/kubernetes/upgrade.go index 980d2904f5..5879f35300 100644 --- a/pkg/cluster/kubernetes/upgrade.go +++ b/pkg/cluster/kubernetes/upgrade.go @@ -43,7 +43,7 @@ type UpgradeOptions struct { } // Log writes the line to logger or to stdout if no logger was provided. -func (options *UpgradeOptions) Log(line string, args ...interface{}) { +func (options *UpgradeOptions) Log(line string, args ...any) { if options.LogOutput != nil { options.LogOutput.Write([]byte(fmt.Sprintf(line, args...))) //nolint:errcheck diff --git a/pkg/grpc/codec/codec.go b/pkg/grpc/codec/codec.go index 02651ca8f0..5ab020dbe2 100644 --- a/pkg/grpc/codec/codec.go +++ b/pkg/grpc/codec/codec.go @@ -31,7 +31,7 @@ type gogoMessage interface { type Codec struct{} // Marshal implements encoding.Codec. -func (Codec) Marshal(v interface{}) ([]byte, error) { +func (Codec) Marshal(v any) ([]byte, error) { // some third-party types (like from etcd and containerd) implement gogoMessage if gm, ok := v.(gogoMessage); ok { return gm.Marshal() @@ -48,7 +48,7 @@ func (Codec) Marshal(v interface{}) ([]byte, error) { } // Unmarshal implements encoding.Codec. -func (Codec) Unmarshal(data []byte, v interface{}) error { +func (Codec) Unmarshal(data []byte, v any) error { // some third-party types (like from etcd and containerd) implement gogoMessage if gm, ok := v.(gogoMessage); ok { return gm.Unmarshal(data) diff --git a/pkg/grpc/factory/factory.go b/pkg/grpc/factory/factory.go index 212ed99fea..9e758f8187 100644 --- a/pkg/grpc/factory/factory.go +++ b/pkg/grpc/factory/factory.go @@ -130,7 +130,7 @@ func WithReflection() Option { } func recoveryHandler(logger *log.Logger) grpc_recovery.RecoveryHandlerFunc { - return func(p interface{}) error { + return func(p any) error { if logger != nil { logger.Printf("panic: %v\n%s", p, string(debug.Stack())) } diff --git a/pkg/grpc/middleware/auth/basic/token.go b/pkg/grpc/middleware/auth/basic/token.go index 00d3f319f2..938342dd04 100644 --- a/pkg/grpc/middleware/auth/basic/token.go +++ b/pkg/grpc/middleware/auth/basic/token.go @@ -78,7 +78,7 @@ func (b *TokenCredentials) authenticate(ctx context.Context) error { // UnaryInterceptor sets the UnaryServerInterceptor for the server and enforces // basic authentication. func (b *TokenCredentials) UnaryInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if err := b.authenticate(ctx); err != nil { return nil, err } diff --git a/pkg/grpc/middleware/auth/basic/username_and_password.go b/pkg/grpc/middleware/auth/basic/username_and_password.go index c2a6e95d72..9a4a23e254 100644 --- a/pkg/grpc/middleware/auth/basic/username_and_password.go +++ b/pkg/grpc/middleware/auth/basic/username_and_password.go @@ -63,7 +63,7 @@ func (b *UsernameAndPasswordCredentials) authorize(ctx context.Context) error { // UnaryInterceptor sets the UnaryServerInterceptor for the server and enforces // basic authentication. func (b *UsernameAndPasswordCredentials) UnaryInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { start := time.Now() if err := b.authorize(ctx); err != nil { diff --git a/pkg/grpc/middleware/authz/authorizer.go b/pkg/grpc/middleware/authz/authorizer.go index c69cce361a..6fff58b242 100644 --- a/pkg/grpc/middleware/authz/authorizer.go +++ b/pkg/grpc/middleware/authz/authorizer.go @@ -27,10 +27,10 @@ type Authorizer struct { FallbackRoles role.Set // Logger. - Logger func(format string, v ...interface{}) + Logger func(format string, v ...any) } -func (a *Authorizer) logf(format string, v ...interface{}) { +func (a *Authorizer) logf(format string, v ...any) { if a.Logger != nil { a.Logger(format, v...) } @@ -59,7 +59,7 @@ func (a *Authorizer) authorize(ctx context.Context, method string) error { // UnaryInterceptor returns grpc UnaryServerInterceptor. func (a *Authorizer) UnaryInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if err := a.authorize(ctx, info.FullMethod); err != nil { return nil, err } @@ -70,7 +70,7 @@ func (a *Authorizer) UnaryInterceptor() grpc.UnaryServerInterceptor { // StreamInterceptor returns grpc StreamServerInterceptor. func (a *Authorizer) StreamInterceptor() grpc.StreamServerInterceptor { - return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if err := a.authorize(stream.Context(), info.FullMethod); err != nil { return err } diff --git a/pkg/grpc/middleware/authz/injector.go b/pkg/grpc/middleware/authz/injector.go index 6f62921369..0806a360ed 100644 --- a/pkg/grpc/middleware/authz/injector.go +++ b/pkg/grpc/middleware/authz/injector.go @@ -58,10 +58,10 @@ type Injector struct { SideroLinkPeerCheckFunc SideroLinkPeerCheckFunc // Logger. - Logger func(format string, v ...interface{}) + Logger func(format string, v ...any) } -func (i *Injector) logf(format string, v ...interface{}) { +func (i *Injector) logf(format string, v ...any) { if i.Logger != nil { i.Logger(format, v...) } @@ -149,7 +149,7 @@ func (i *Injector) extractRoles(ctx context.Context) role.Set { // UnaryInterceptor returns grpc UnaryServerInterceptor. func (i *Injector) UnaryInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { ctx = ContextWithRoles(ctx, i.extractRoles(ctx)) return handler(ctx, req) @@ -158,7 +158,7 @@ func (i *Injector) UnaryInterceptor() grpc.UnaryServerInterceptor { // StreamInterceptor returns grpc StreamServerInterceptor. func (i *Injector) StreamInterceptor() grpc.StreamServerInterceptor { - return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { ctx := stream.Context() ctx = ContextWithRoles(ctx, i.extractRoles(ctx)) diff --git a/pkg/grpc/middleware/authz/metadata.go b/pkg/grpc/middleware/authz/metadata.go index 67e907fe00..a889526dca 100644 --- a/pkg/grpc/middleware/authz/metadata.go +++ b/pkg/grpc/middleware/authz/metadata.go @@ -23,7 +23,7 @@ func SetMetadata(md metadata.MD, roles role.Set) { } // getFromMetadata returns roles extracted from gRPC metadata. -func getFromMetadata(ctx context.Context, logf func(format string, v ...interface{})) (role.Set, bool) { +func getFromMetadata(ctx context.Context, logf func(format string, v ...any)) (role.Set, bool) { md, ok := metadata.FromIncomingContext(ctx) if !ok { panic("no request metadata") diff --git a/pkg/grpc/middleware/log/log.go b/pkg/grpc/middleware/log/log.go index 33a7a29373..1fb287cf0e 100644 --- a/pkg/grpc/middleware/log/log.go +++ b/pkg/grpc/middleware/log/log.go @@ -57,7 +57,7 @@ func ExtractMetadata(ctx context.Context) string { // UnaryInterceptor returns grpc UnaryServerInterceptor. func (m *Middleware) UnaryInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { startTime := time.Now() resp, err := handler(ctx, req) @@ -78,7 +78,7 @@ func (m *Middleware) UnaryInterceptor() grpc.UnaryServerInterceptor { // StreamInterceptor returns grpc StreamServerInterceptor. func (m *Middleware) StreamInterceptor() grpc.StreamServerInterceptor { - return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { startTime := time.Now() err := handler(srv, stream) diff --git a/pkg/kubeconfig/generate.go b/pkg/kubeconfig/generate.go index f04553c5ba..0191474c36 100644 --- a/pkg/kubeconfig/generate.go +++ b/pkg/kubeconfig/generate.go @@ -142,7 +142,7 @@ func Generate(in *GenerateInput, out io.Writer) error { }) } -func base64Encode(content interface{}) (string, error) { +func base64Encode(content any) (string, error) { str, ok := content.(string) if !ok { return "", fmt.Errorf("argument to base64 encode is not a string: %v", content) diff --git a/pkg/machinery/client/client.go b/pkg/machinery/client/client.go index d7443abca7..179e81c724 100644 --- a/pkg/machinery/client/client.go +++ b/pkg/machinery/client/client.go @@ -244,7 +244,7 @@ func (c *Client) Kubeconfig(ctx context.Context) ([]byte, error) { func (c *Client) ApplyConfiguration(ctx context.Context, req *machineapi.ApplyConfigurationRequest, callOptions ...grpc.CallOption) (resp *machineapi.ApplyConfigurationResponse, err error) { resp, err = c.MachineClient.ApplyConfiguration(ctx, req, callOptions...) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.ApplyConfigurationResponse) //nolint:errcheck @@ -255,7 +255,7 @@ func (c *Client) ApplyConfiguration(ctx context.Context, req *machineapi.ApplyCo func (c *Client) GenerateConfiguration(ctx context.Context, req *machineapi.GenerateConfigurationRequest, callOptions ...grpc.CallOption) (resp *machineapi.GenerateConfigurationResponse, err error) { resp, err = c.MachineClient.GenerateConfiguration(ctx, req, callOptions...) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.GenerateConfigurationResponse) //nolint:errcheck @@ -266,7 +266,7 @@ func (c *Client) GenerateConfiguration(ctx context.Context, req *machineapi.Gene func (c *Client) Disks(ctx context.Context, callOptions ...grpc.CallOption) (resp *storageapi.DisksResponse, err error) { resp, err = c.StorageClient.Disks(ctx, &emptypb.Empty{}, callOptions...) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*storageapi.DisksResponse) //nolint:errcheck @@ -283,7 +283,7 @@ func (c *Client) Stats(ctx context.Context, namespace string, driver common.Cont callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.StatsResponse) //nolint:errcheck @@ -301,7 +301,7 @@ func (c *Client) Containers(ctx context.Context, namespace string, driver common callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.ContainersResponse) //nolint:errcheck @@ -468,7 +468,7 @@ func (c *Client) LogsContainers(ctx context.Context, callOptions ...grpc.CallOpt callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.LogsContainersResponse) //nolint:errcheck @@ -483,7 +483,7 @@ func (c *Client) Version(ctx context.Context, callOptions ...grpc.CallOption) (r callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.VersionResponse) //nolint:errcheck @@ -498,7 +498,7 @@ func (c *Client) Processes(ctx context.Context, callOptions ...grpc.CallOption) callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.ProcessesResponse) //nolint:errcheck @@ -513,7 +513,7 @@ func (c *Client) Memory(ctx context.Context, callOptions ...grpc.CallOption) (re callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.MemoryResponse) //nolint:errcheck @@ -528,7 +528,7 @@ func (c *Client) Mounts(ctx context.Context, callOptions ...grpc.CallOption) (re callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.MountsResponse) //nolint:errcheck @@ -649,7 +649,7 @@ func (c *Client) ServiceList(ctx context.Context, callOptions ...grpc.CallOption callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.ServiceListResponse) //nolint:errcheck @@ -678,7 +678,7 @@ func (c *Client) ServiceInfo(ctx context.Context, id string, callOptions ...grpc return services, err } - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.ServiceListResponse) //nolint:errcheck @@ -710,7 +710,7 @@ func (c *Client) ServiceStart(ctx context.Context, id string, callOptions ...grp callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.ServiceStartResponse) //nolint:errcheck @@ -725,7 +725,7 @@ func (c *Client) ServiceStop(ctx context.Context, id string, callOptions ...grpc callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.ServiceStopResponse) //nolint:errcheck @@ -740,7 +740,7 @@ func (c *Client) ServiceRestart(ctx context.Context, id string, callOptions ...g callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.ServiceRestartResponse) //nolint:errcheck @@ -755,7 +755,7 @@ func (c *Client) Time(ctx context.Context, callOptions ...grpc.CallOption) (resp callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*timeapi.TimeResponse) //nolint:errcheck @@ -770,7 +770,7 @@ func (c *Client) TimeCheck(ctx context.Context, server string, callOptions ...gr callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*timeapi.TimeResponse) //nolint:errcheck @@ -824,7 +824,7 @@ func (c *Client) EtcdLeaveCluster(ctx context.Context, req *machineapi.EtcdLeave func (c *Client) EtcdForfeitLeadership(ctx context.Context, req *machineapi.EtcdForfeitLeadershipRequest, callOptions ...grpc.CallOption) (*machineapi.EtcdForfeitLeadershipResponse, error) { resp, err := c.MachineClient.EtcdForfeitLeadership(ctx, req, callOptions...) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.EtcdForfeitLeadershipResponse) //nolint:errcheck @@ -835,7 +835,7 @@ func (c *Client) EtcdForfeitLeadership(ctx context.Context, req *machineapi.Etcd func (c *Client) EtcdMemberList(ctx context.Context, req *machineapi.EtcdMemberListRequest, callOptions ...grpc.CallOption) (*machineapi.EtcdMemberListResponse, error) { resp, err := c.MachineClient.EtcdMemberList(ctx, req, callOptions...) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.EtcdMemberListResponse) //nolint:errcheck @@ -895,7 +895,7 @@ func (c *Client) EtcdRecover(ctx context.Context, snapshot io.Reader, callOption resp, err := cli.CloseAndRecv() - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.EtcdRecoverResponse) //nolint:errcheck @@ -908,7 +908,7 @@ func (c *Client) EtcdRecover(ctx context.Context, snapshot io.Reader, callOption func (c *Client) EtcdAlarmList(ctx context.Context, opts ...grpc.CallOption) (*machineapi.EtcdAlarmListResponse, error) { resp, err := c.MachineClient.EtcdAlarmList(ctx, &emptypb.Empty{}, opts...) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.EtcdAlarmListResponse) //nolint:errcheck @@ -921,7 +921,7 @@ func (c *Client) EtcdAlarmList(ctx context.Context, opts ...grpc.CallOption) (*m func (c *Client) EtcdAlarmDisarm(ctx context.Context, opts ...grpc.CallOption) (*machineapi.EtcdAlarmDisarmResponse, error) { resp, err := c.MachineClient.EtcdAlarmDisarm(ctx, &emptypb.Empty{}, opts...) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.EtcdAlarmDisarmResponse) //nolint:errcheck @@ -937,7 +937,7 @@ func (c *Client) EtcdAlarmDisarm(ctx context.Context, opts ...grpc.CallOption) ( func (c *Client) EtcdDefragment(ctx context.Context, opts ...grpc.CallOption) (*machineapi.EtcdDefragmentResponse, error) { resp, err := c.MachineClient.EtcdDefragment(ctx, &emptypb.Empty{}, opts...) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.EtcdDefragmentResponse) //nolint:errcheck @@ -950,7 +950,7 @@ func (c *Client) EtcdDefragment(ctx context.Context, opts ...grpc.CallOption) (* func (c *Client) EtcdStatus(ctx context.Context, opts ...grpc.CallOption) (*machineapi.EtcdStatusResponse, error) { resp, err := c.MachineClient.EtcdStatus(ctx, &emptypb.Empty{}, opts...) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.EtcdStatusResponse) //nolint:errcheck @@ -961,7 +961,7 @@ func (c *Client) EtcdStatus(ctx context.Context, opts ...grpc.CallOption) (*mach func (c *Client) GenerateClientConfiguration(ctx context.Context, req *machineapi.GenerateClientConfigurationRequest, callOptions ...grpc.CallOption) (resp *machineapi.GenerateClientConfigurationResponse, err error) { //nolint:lll resp, err = c.MachineClient.GenerateClientConfiguration(ctx, req, callOptions...) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.GenerateClientConfigurationResponse) //nolint:errcheck @@ -1046,7 +1046,7 @@ func (c *Client) Netstat(ctx context.Context, req *machineapi.NetstatRequest, ca callOptions..., ) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*machineapi.NetstatResponse) //nolint:errcheck diff --git a/pkg/machinery/client/config/config.go b/pkg/machinery/client/config/config.go index 39b7900b36..2f963d9e97 100644 --- a/pkg/machinery/client/config/config.go +++ b/pkg/machinery/client/config/config.go @@ -215,7 +215,8 @@ func (c *Config) Merge(cfg *Config) []Rename { } mappedContexts := map[string]string{} - renames := []Rename{} + + var renames []Rename for name, ctx := range cfg.Contexts { mergedName := name diff --git a/pkg/machinery/client/grpc_connection_wrapper.go b/pkg/machinery/client/grpc_connection_wrapper.go index ea72f4f125..376dd15c84 100644 --- a/pkg/machinery/client/grpc_connection_wrapper.go +++ b/pkg/machinery/client/grpc_connection_wrapper.go @@ -26,7 +26,7 @@ func newGRPCConnectionWrapper(clusterName string, conn *grpc.ClientConn) *grpcCo // Invoke performs a unary RPC and returns after the response is received // into reply. -func (c *grpcConnectionWrapper) Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...grpc.CallOption) error { +func (c *grpcConnectionWrapper) Invoke(ctx context.Context, method string, args any, reply any, opts ...grpc.CallOption) error { return c.ClientConn.Invoke(c.appendMetadata(ctx), method, args, reply, opts...) } diff --git a/pkg/machinery/client/inspect.go b/pkg/machinery/client/inspect.go index f32325c770..55023ab280 100644 --- a/pkg/machinery/client/inspect.go +++ b/pkg/machinery/client/inspect.go @@ -22,7 +22,7 @@ type InspectClient struct { func (c *InspectClient) ControllerRuntimeDependencies(ctx context.Context, callOptions ...grpc.CallOption) (*inspectapi.ControllerRuntimeDependenciesResponse, error) { resp, err := c.client.ControllerRuntimeDependencies(ctx, &emptypb.Empty{}, callOptions...) - var filtered interface{} + var filtered any filtered, err = FilterMessages(resp, err) resp, _ = filtered.(*inspectapi.ControllerRuntimeDependenciesResponse) //nolint:errcheck diff --git a/pkg/machinery/client/reply.go b/pkg/machinery/client/reply.go index 664fa1d3b9..c61a31779b 100644 --- a/pkg/machinery/client/reply.go +++ b/pkg/machinery/client/reply.go @@ -32,7 +32,7 @@ func (ne *NodeError) Unwrap() error { // FilterMessages removes error Messages from resp and builds multierror. // //nolint:gocyclo,cyclop -func FilterMessages(resp interface{}, err error) (interface{}, error) { +func FilterMessages(resp any, err error) (any, error) { if resp == nil { return nil, err } diff --git a/pkg/machinery/client/resources.go b/pkg/machinery/client/resources.go index d48dabc430..8daa4989ab 100644 --- a/pkg/machinery/client/resources.go +++ b/pkg/machinery/client/resources.go @@ -24,7 +24,7 @@ func (c *Client) ResolveResourceKind(ctx context.Context, resourceNamespace *res return nil, err } - matched := []*meta.ResourceDefinition{} + var matched []*meta.ResourceDefinition for it := registeredResources.Iterator(); it.Next(); { rd := it.Value() diff --git a/pkg/machinery/compatibility/talos12/talos12.go b/pkg/machinery/compatibility/talos12/talos12.go index 02c1fd85ae..f2a002abee 100644 --- a/pkg/machinery/compatibility/talos12/talos12.go +++ b/pkg/machinery/compatibility/talos12/talos12.go @@ -19,7 +19,7 @@ var MinimumHostUpgradeVersion = semver.MustParse("1.0.0") var MaximumHostDowngradeVersion = semver.MustParse("1.3.0") // DeniedHostUpgradeVersions are the versions of Talos that cannot be upgraded to 1.2. -var DeniedHostUpgradeVersions = []semver.Version{} +var DeniedHostUpgradeVersions []semver.Version // MinimumKubernetesVersion is the minimum version of Kubernetes is supported with 1.2. var MinimumKubernetesVersion = semver.MustParse("1.23.0") diff --git a/pkg/machinery/compatibility/talos13/talos13.go b/pkg/machinery/compatibility/talos13/talos13.go index dd9ced7202..025de1c9e9 100644 --- a/pkg/machinery/compatibility/talos13/talos13.go +++ b/pkg/machinery/compatibility/talos13/talos13.go @@ -19,7 +19,7 @@ var MinimumHostUpgradeVersion = semver.MustParse("1.0.0") var MaximumHostDowngradeVersion = semver.MustParse("1.5.0") // DeniedHostUpgradeVersions are the versions of Talos that cannot be upgraded to 1.3. -var DeniedHostUpgradeVersions = []semver.Version{} +var DeniedHostUpgradeVersions []semver.Version // MinimumKubernetesVersion is the minimum version of Kubernetes is supported with 1.3. var MinimumKubernetesVersion = semver.MustParse("1.24.0") diff --git a/pkg/machinery/compatibility/talos14/talos14.go b/pkg/machinery/compatibility/talos14/talos14.go index 35563bcbd6..6173bab4fe 100644 --- a/pkg/machinery/compatibility/talos14/talos14.go +++ b/pkg/machinery/compatibility/talos14/talos14.go @@ -19,7 +19,7 @@ var MinimumHostUpgradeVersion = semver.MustParse("1.0.0") var MaximumHostDowngradeVersion = semver.MustParse("1.6.0") // DeniedHostUpgradeVersions are the versions of Talos that cannot be upgraded to 1.4. -var DeniedHostUpgradeVersions = []semver.Version{} +var DeniedHostUpgradeVersions []semver.Version // MinimumKubernetesVersion is the minimum version of Kubernetes is supported with 1.4. var MinimumKubernetesVersion = semver.MustParse("1.25.0") diff --git a/pkg/machinery/compatibility/talos15/talos15.go b/pkg/machinery/compatibility/talos15/talos15.go index d2d9e1efe1..bf7382cc80 100644 --- a/pkg/machinery/compatibility/talos15/talos15.go +++ b/pkg/machinery/compatibility/talos15/talos15.go @@ -19,7 +19,7 @@ var MinimumHostUpgradeVersion = semver.MustParse("1.2.0") var MaximumHostDowngradeVersion = semver.MustParse("1.7.0") // DeniedHostUpgradeVersions are the versions of Talos that cannot be upgraded to 1.5. -var DeniedHostUpgradeVersions = []semver.Version{} +var DeniedHostUpgradeVersions []semver.Version // MinimumKubernetesVersion is the minimum version of Kubernetes is supported with 1.5. var MinimumKubernetesVersion = semver.MustParse("1.26.0") diff --git a/pkg/machinery/compatibility/talos16/talos16.go b/pkg/machinery/compatibility/talos16/talos16.go index 7a5fb8c7ab..d58e0e1b0f 100644 --- a/pkg/machinery/compatibility/talos16/talos16.go +++ b/pkg/machinery/compatibility/talos16/talos16.go @@ -19,7 +19,7 @@ var MinimumHostUpgradeVersion = semver.MustParse("1.3.0") var MaximumHostDowngradeVersion = semver.MustParse("1.8.0") // DeniedHostUpgradeVersions are the versions of Talos that cannot be upgraded to 1.6. -var DeniedHostUpgradeVersions = []semver.Version{} +var DeniedHostUpgradeVersions []semver.Version // MinimumKubernetesVersion is the minimum version of Kubernetes is supported with 1.6. var MinimumKubernetesVersion = semver.MustParse("1.24.0") diff --git a/pkg/machinery/compatibility/talos17/talos17.go b/pkg/machinery/compatibility/talos17/talos17.go index 6283cf0fc4..dff70248f9 100644 --- a/pkg/machinery/compatibility/talos17/talos17.go +++ b/pkg/machinery/compatibility/talos17/talos17.go @@ -19,7 +19,7 @@ var MinimumHostUpgradeVersion = semver.MustParse("1.4.0") var MaximumHostDowngradeVersion = semver.MustParse("1.9.0") // DeniedHostUpgradeVersions are the versions of Talos that cannot be upgraded to 1.7. -var DeniedHostUpgradeVersions = []semver.Version{} +var DeniedHostUpgradeVersions []semver.Version // MinimumKubernetesVersion is the minimum version of Kubernetes is supported with 1.7. var MinimumKubernetesVersion = semver.MustParse("1.25.0") diff --git a/pkg/machinery/compatibility/talos18/talos18.go b/pkg/machinery/compatibility/talos18/talos18.go index a7074ac0cc..8458431a0c 100644 --- a/pkg/machinery/compatibility/talos18/talos18.go +++ b/pkg/machinery/compatibility/talos18/talos18.go @@ -19,7 +19,7 @@ var MinimumHostUpgradeVersion = semver.MustParse("1.5.0") var MaximumHostDowngradeVersion = semver.MustParse("1.10.0") // DeniedHostUpgradeVersions are the versions of Talos that cannot be upgraded to 1.8. -var DeniedHostUpgradeVersions = []semver.Version{} +var DeniedHostUpgradeVersions []semver.Version // MinimumKubernetesVersion is the minimum version of Kubernetes is supported with 1.8. var MinimumKubernetesVersion = semver.MustParse("1.26.0") diff --git a/pkg/machinery/config/config/cluster.go b/pkg/machinery/config/config/cluster.go index b95ae691ca..5dda4e8608 100644 --- a/pkg/machinery/config/config/cluster.go +++ b/pkg/machinery/config/config/cluster.go @@ -82,14 +82,14 @@ type APIServer interface { Env() Env DisablePodSecurityPolicy() bool AdmissionControl() []AdmissionPlugin - AuditPolicy() map[string]interface{} + AuditPolicy() map[string]any Resources() Resources } // AdmissionPlugin defines the API server Admission Plugin configuration. type AdmissionPlugin interface { Name() string - Configuration() map[string]interface{} + Configuration() map[string]any } // ControllerManager defines the requirements for a config that pertains to controller manager related diff --git a/pkg/machinery/config/config/machine.go b/pkg/machinery/config/config/machine.go index 13396b5732..227164859e 100644 --- a/pkg/machinery/config/config/machine.go +++ b/pkg/machinery/config/config/machine.go @@ -30,7 +30,7 @@ type MachineConfig interface { Files() ([]File, error) Type() machine.Type Controlplane() MachineControlPlane - Pods() []map[string]interface{} + Pods() []map[string]any Kubelet() Kubelet Sysctls() map[string]string Sysfs() map[string]string @@ -49,7 +49,7 @@ type MachineConfig interface { // related options. type SeccompProfile interface { Name() string - Value() map[string]interface{} + Value() map[string]any } // NodeLabels defines the labels that should be set on a node. @@ -318,8 +318,8 @@ type Kubelet interface { ClusterDNS() []string ExtraArgs() map[string]string ExtraMounts() []specs.Mount - ExtraConfig() map[string]interface{} - CredentialProviderConfig() map[string]interface{} + ExtraConfig() map[string]any + CredentialProviderConfig() map[string]any DefaultRuntimeSeccompProfileEnabled() bool RegisterWithFQDN() bool NodeIP() KubeletNodeIP diff --git a/pkg/machinery/config/configloader/internal/decoder/unknown_keys.go b/pkg/machinery/config/configloader/internal/decoder/unknown_keys.go index 50cfcb7da9..bc7e61a9e3 100644 --- a/pkg/machinery/config/configloader/internal/decoder/unknown_keys.go +++ b/pkg/machinery/config/configloader/internal/decoder/unknown_keys.go @@ -13,7 +13,7 @@ import ( yaml "gopkg.in/yaml.v3" ) -func checkUnknownKeys(target interface{}, spec *yaml.Node) error { +func checkUnknownKeys(target any, spec *yaml.Node) error { unknown, err := internalCheckUnknownKeys(reflect.TypeOf(target), spec) if err != nil { return err @@ -82,10 +82,10 @@ func structKeys(typ reflect.Type) (map[string][]int, reflect.Type) { return availableKeys, typ } -var typeOfInterfaceAny = reflect.TypeOf((*interface{})(nil)).Elem() +var typeOfInterfaceAny = reflect.TypeOf((*any)(nil)).Elem() //nolint:gocyclo,cyclop -func internalCheckUnknownKeys(typ reflect.Type, spec *yaml.Node) (unknown interface{}, err error) { +func internalCheckUnknownKeys(typ reflect.Type, spec *yaml.Node) (unknown any, err error) { for typ.Kind() == reflect.Ptr { typ = typ.Elem() } @@ -124,10 +124,10 @@ func internalCheckUnknownKeys(typ reflect.Type, spec *yaml.Node) (unknown interf fieldIndex, ok := availableKeys[key] if !ok { if unknown == nil { - unknown = map[string]interface{}{} + unknown = map[string]any{} } - unknown.(map[string]interface{})[key] = spec.Content[i+1] + unknown.(map[string]any)[key] = spec.Content[i+1] continue } @@ -145,10 +145,10 @@ func internalCheckUnknownKeys(typ reflect.Type, spec *yaml.Node) (unknown interf if innerUnknown != nil { if unknown == nil { - unknown = map[string]interface{}{} + unknown = map[string]any{} } - unknown.(map[string]interface{})[key] = innerUnknown + unknown.(map[string]any)[key] = innerUnknown } } case yaml.SequenceNode: @@ -164,10 +164,10 @@ func internalCheckUnknownKeys(typ reflect.Type, spec *yaml.Node) (unknown interf if innerUnknown != nil { if unknown == nil { - unknown = []interface{}{} + unknown = []any{} } - unknown = append(unknown.([]interface{}), innerUnknown) + unknown = append(unknown.([]any), innerUnknown) } } } diff --git a/pkg/machinery/config/configpatcher/load.go b/pkg/machinery/config/configpatcher/load.go index 1b4a4d2778..6e4a7199c1 100644 --- a/pkg/machinery/config/configpatcher/load.go +++ b/pkg/machinery/config/configpatcher/load.go @@ -16,7 +16,7 @@ import ( "github.com/siderolabs/talos/pkg/machinery/config/configloader" ) -type patch []map[string]interface{} +type patch []map[string]any // LoadPatch loads the strategic merge patch or JSON patch (JSON/YAML for JSON patch). func LoadPatch(in []byte) (Patch, error) { diff --git a/pkg/machinery/config/configpatcher/load_test.go b/pkg/machinery/config/configpatcher/load_test.go index 11b43cd313..b5a23f92c3 100644 --- a/pkg/machinery/config/configpatcher/load_test.go +++ b/pkg/machinery/config/configpatcher/load_test.go @@ -57,10 +57,10 @@ func TestLoadYAML(t *testing.T) { require.NoError(t, err) assert.Equal(t, path, "/some/path") - var v interface{} + var v any v, err = p[0].ValueInterface() require.NoError(t, err) - assert.Equal(t, v, []interface{}{"a", "b", "c"}) + assert.Equal(t, v, []any{"a", "b", "c"}) } func TestLoadStrategic(t *testing.T) { diff --git a/pkg/machinery/config/encoder/documentation.go b/pkg/machinery/config/encoder/documentation.go index dc3fc33148..4565fe4e0d 100644 --- a/pkg/machinery/config/encoder/documentation.go +++ b/pkg/machinery/config/encoder/documentation.go @@ -45,7 +45,7 @@ type Doc struct { } // AddExample adds a new example snippet to the doc. -func (d *Doc) AddExample(name string, value interface{}) { +func (d *Doc) AddExample(name string, value any) { if d.Examples == nil { d.Examples = []*Example{} } @@ -79,7 +79,7 @@ type Example struct { Name string valueMutex sync.RWMutex - value interface{} + value any } // Populate populates example value. @@ -105,7 +105,7 @@ func (e *Example) Populate(index int) { } // GetValue returns example value. -func (e *Example) GetValue() interface{} { +func (e *Example) GetValue() any { e.valueMutex.RLock() defer e.valueMutex.RUnlock() @@ -156,7 +156,7 @@ func mergeDoc(a, b *Doc) *Doc { return &res } -func getDoc(in interface{}) *Doc { +func getDoc(in any) *Doc { v := reflect.ValueOf(in) if v.Kind() == reflect.Ptr && v.IsNil() { in = reflect.New(v.Type().Elem()).Interface() @@ -199,7 +199,7 @@ func renderExample(key string, doc *Doc, options *Options) string { return "" } - examples := []string{} + examples := make([]string, 0, len(doc.Examples)) for i, e := range doc.Examples { v := reflect.ValueOf(e.GetValue()) diff --git a/pkg/machinery/config/encoder/encoder.go b/pkg/machinery/config/encoder/encoder.go index b573e36d06..8e379b682f 100644 --- a/pkg/machinery/config/encoder/encoder.go +++ b/pkg/machinery/config/encoder/encoder.go @@ -15,12 +15,12 @@ import ( // Encoder implements config encoder. type Encoder struct { - value interface{} + value any options *Options } // NewEncoder initializes and returns an `Encoder`. -func NewEncoder(value interface{}, opts ...Option) *Encoder { +func NewEncoder(value any, opts ...Option) *Encoder { return &Encoder{ value: value, options: newOptions(opts...), @@ -110,7 +110,7 @@ func isNil(value reflect.Value) bool { } //nolint:gocyclo,cyclop -func toYamlNode(in interface{}, options *Options) (*yaml.Node, error) { +func toYamlNode(in any, options *Options) (*yaml.Node, error) { node := &yaml.Node{} flags := options.Comments @@ -206,7 +206,7 @@ func toYamlNode(in interface{}, options *Options) (*yaml.Node, error) { } } - var value interface{} + var value any if v.Field(i).CanInterface() { value = v.Field(i).Interface() } @@ -333,7 +333,7 @@ func appendNodes(dest *yaml.Node, nodes ...*yaml.Node) { dest.Content = append(dest.Content, nodes...) } -func addToMap(dest *yaml.Node, doc *Doc, fieldName, in interface{}, style yaml.Style, options *Options) error { +func addToMap(dest *yaml.Node, doc *Doc, fieldName, in any, style yaml.Style, options *Options) error { key, err := toYamlNode(fieldName, options) if err != nil { return err diff --git a/pkg/machinery/config/encoder/encoder_test.go b/pkg/machinery/config/encoder/encoder_test.go index 0672d338e4..93ab245f17 100644 --- a/pkg/machinery/config/encoder/encoder_test.go +++ b/pkg/machinery/config/encoder/encoder_test.go @@ -66,7 +66,7 @@ type WithCustomMarshaller struct { } // MarshalYAML implements custom marshaller. -func (cm *WithCustomMarshaller) MarshalYAML() (interface{}, error) { +func (cm *WithCustomMarshaller) MarshalYAML() (any, error) { node := &yaml.Node{} if err := node.Encode(map[string]string{"value": cm.value}); err != nil { @@ -166,7 +166,7 @@ func (suite *EncoderSuite) TestRun() { } tests := []struct { name string - value interface{} + value any expectedYAML string incompatible bool options []encoder.Option @@ -546,8 +546,8 @@ func (suite *EncoderSuite) TestConcurrent() { wg.Wait() } -func decodeToMap(data []byte) (map[interface{}]interface{}, error) { - raw := map[interface{}]interface{}{} +func decodeToMap(data []byte) (map[any]any, error) { + raw := map[any]any{} err := yaml.Unmarshal(data, &raw) return raw, err diff --git a/pkg/machinery/config/generate/init.go b/pkg/machinery/config/generate/init.go index 0f7a95e375..4bfda3a1bd 100644 --- a/pkg/machinery/config/generate/init.go +++ b/pkg/machinery/config/generate/init.go @@ -114,10 +114,10 @@ func (in *Input) init() ([]config.Document, error) { &v1alpha1.AdmissionPluginConfig{ PluginName: "PodSecurity", PluginConfiguration: v1alpha1.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "pod-security.admission.config.k8s.io/v1alpha1", "kind": "PodSecurityConfiguration", - "defaults": map[string]interface{}{ + "defaults": map[string]any{ "enforce": "baseline", "enforce-version": "latest", "audit": "restricted", @@ -125,10 +125,10 @@ func (in *Input) init() ([]config.Document, error) { "warn": "restricted", "warn-version": "latest", }, - "exemptions": map[string]interface{}{ - "usernames": []interface{}{}, - "runtimeClasses": []interface{}{}, - "namespaces": []interface{}{"kube-system"}, + "exemptions": map[string]any{ + "usernames": []any{}, + "runtimeClasses": []any{}, + "namespaces": []any{"kube-system"}, }, }, }, diff --git a/pkg/machinery/config/types/v1alpha1/v1alpha1_admissionplugin.go b/pkg/machinery/config/types/v1alpha1/v1alpha1_admissionplugin.go index 2f114062a1..aaf08af293 100644 --- a/pkg/machinery/config/types/v1alpha1/v1alpha1_admissionplugin.go +++ b/pkg/machinery/config/types/v1alpha1/v1alpha1_admissionplugin.go @@ -10,6 +10,6 @@ func (a *AdmissionPluginConfig) Name() string { } // Configuration implements the config.AdmissionPlugin interface. -func (a *AdmissionPluginConfig) Configuration() map[string]interface{} { +func (a *AdmissionPluginConfig) Configuration() map[string]any { return a.PluginConfiguration.Object } diff --git a/pkg/machinery/config/types/v1alpha1/v1alpha1_apiserverconfig.go b/pkg/machinery/config/types/v1alpha1/v1alpha1_apiserverconfig.go index 4b714a916e..29fc7a66f7 100644 --- a/pkg/machinery/config/types/v1alpha1/v1alpha1_apiserverconfig.go +++ b/pkg/machinery/config/types/v1alpha1/v1alpha1_apiserverconfig.go @@ -16,11 +16,11 @@ import ( // APIServerDefaultAuditPolicy is the default kube-apiserver audit policy. var APIServerDefaultAuditPolicy = Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "audit.k8s.io/v1", "kind": "Policy", - "rules": []interface{}{ - map[string]interface{}{ + "rules": []any{ + map[string]any{ "level": "Metadata", }, }, @@ -64,7 +64,7 @@ func (a *APIServerConfig) AdmissionControl() []config.AdmissionPlugin { } // AuditPolicy implements the config.APIServer interface. -func (a *APIServerConfig) AuditPolicy() map[string]interface{} { +func (a *APIServerConfig) AuditPolicy() map[string]any { if len(a.AuditPolicyConfig.Object) == 0 { return APIServerDefaultAuditPolicy.DeepCopy().Object } diff --git a/pkg/machinery/config/types/v1alpha1/v1alpha1_examples.go b/pkg/machinery/config/types/v1alpha1/v1alpha1_examples.go index 18a6f82dad..6b6e3331ca 100644 --- a/pkg/machinery/config/types/v1alpha1/v1alpha1_examples.go +++ b/pkg/machinery/config/types/v1alpha1/v1alpha1_examples.go @@ -331,7 +331,7 @@ func clusterNetworkExample() *ClusterNetworkConfig { func resourcesConfigRequestsExample() Unstructured { return Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "cpu": 1, "memory": "1Gi", }, @@ -340,7 +340,7 @@ func resourcesConfigRequestsExample() Unstructured { func resourcesConfigLimitsExample() Unstructured { return Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "cpu": 2, "memory": "2500Mi", }, @@ -450,7 +450,7 @@ func machineSeccompExample() []*MachineSeccompProfile { { MachineSeccompProfileName: "audit.json", MachineSeccompProfileValue: Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "defaultAction": "SCMP_ACT_LOG", }, }, @@ -631,7 +631,7 @@ func kubeletNodeIPExample() *KubeletNodeIPConfig { func kubeletExtraConfigExample() Unstructured { return Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "serverTLSBootstrap": true, }, } @@ -639,14 +639,14 @@ func kubeletExtraConfigExample() Unstructured { func kubeletCredentialProviderConfigExample() Unstructured { return Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "kubelet.config.k8s.io/v1", "kind": "CredentialProviderConfig", - "providers": []interface{}{ - map[string]interface{}{ + "providers": []any{ + map[string]any{ "name": "ecr-credential-provider", "apiVersion": "credentialprovider.kubelet.k8s.io/v1", - "matchImages": []interface{}{ + "matchImages": []any{ "*.dkr.ecr.*.amazonaws.com", "*.dkr.ecr.*.amazonaws.com.cn", "*.dkr.ecr-fips.*.amazonaws.com", @@ -696,15 +696,15 @@ func machineKernelExample() *KernelConfig { func machinePodsExample() []Unstructured { return []Unstructured{ { - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "v1", "kind": "pod", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "nginx", }, - "spec": map[string]interface{}{ - "containers": []interface{}{ - map[string]interface{}{ + "spec": map[string]any{ + "containers": []any{ + map[string]any{ "name": "nginx", "image": "nginx", }, @@ -720,10 +720,10 @@ func admissionControlConfigExample() []*AdmissionPluginConfig { { PluginName: "PodSecurity", PluginConfiguration: Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "pod-security.admission.config.k8s.io/v1alpha1", "kind": "PodSecurityConfiguration", - "defaults": map[string]interface{}{ + "defaults": map[string]any{ "enforce": "baseline", "enforce-version": "latest", "audit": "restricted", @@ -731,10 +731,10 @@ func admissionControlConfigExample() []*AdmissionPluginConfig { "warn": "restricted", "warn-version": "latest", }, - "exemptions": map[string]interface{}{ - "usernames": []interface{}{}, - "runtimeClasses": []interface{}{}, - "namespaces": []interface{}{"kube-system"}, + "exemptions": map[string]any{ + "usernames": []any{}, + "runtimeClasses": []any{}, + "namespaces": []any{"kube-system"}, }, }, }, diff --git a/pkg/machinery/config/types/v1alpha1/v1alpha1_marshal.go b/pkg/machinery/config/types/v1alpha1/v1alpha1_marshal.go index 3f7d215441..c1edf3cd2a 100644 --- a/pkg/machinery/config/types/v1alpha1/v1alpha1_marshal.go +++ b/pkg/machinery/config/types/v1alpha1/v1alpha1_marshal.go @@ -12,7 +12,7 @@ import ( type Base64Bytes []byte // UnmarshalYAML implements the yaml.Unmarshaler interface. -func (b *Base64Bytes) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (b *Base64Bytes) UnmarshalYAML(unmarshal func(any) error) error { var data string if err := unmarshal(&data); err != nil { @@ -30,6 +30,6 @@ func (b *Base64Bytes) UnmarshalYAML(unmarshal func(interface{}) error) error { } // MarshalYAML implements the yaml.Marshaler interface. -func (b Base64Bytes) MarshalYAML() (interface{}, error) { +func (b Base64Bytes) MarshalYAML() (any, error) { return base64.StdEncoding.EncodeToString(b), nil } diff --git a/pkg/machinery/config/types/v1alpha1/v1alpha1_provider.go b/pkg/machinery/config/types/v1alpha1/v1alpha1_provider.go index 6e37d55f70..9b6c9c3b2b 100644 --- a/pkg/machinery/config/types/v1alpha1/v1alpha1_provider.go +++ b/pkg/machinery/config/types/v1alpha1/v1alpha1_provider.go @@ -82,7 +82,7 @@ func (m *MachineSeccompProfile) Name() string { } // Value implements the config.Provider interface. -func (m *MachineSeccompProfile) Value() map[string]interface{} { +func (m *MachineSeccompProfile) Value() map[string]any { return m.MachineSeccompProfileValue.Object } @@ -203,8 +203,8 @@ func (m *MachineConfig) Controlplane() config.MachineControlPlane { } // Pods implements the config.Provider interface. -func (m *MachineConfig) Pods() []map[string]interface{} { - return xslices.Map(m.MachinePods, func(u Unstructured) map[string]interface{} { return u.Object }) +func (m *MachineConfig) Pods() []map[string]any { + return xslices.Map(m.MachinePods, func(u Unstructured) map[string]any { return u.Object }) } // ControllerManager implements the config.Provider interface. @@ -415,12 +415,12 @@ func (k *KubeletConfig) ExtraMounts() []specs.Mount { } // ExtraConfig implements the config.Provider interface. -func (k *KubeletConfig) ExtraConfig() map[string]interface{} { +func (k *KubeletConfig) ExtraConfig() map[string]any { return k.KubeletExtraConfig.Object } // CredentialProviderConfig implements the config.Provider interface. -func (k *KubeletConfig) CredentialProviderConfig() map[string]interface{} { +func (k *KubeletConfig) CredentialProviderConfig() map[string]any { return k.KubeletCredentialProviderConfig.Object } @@ -1219,7 +1219,7 @@ func (i *InstallConfig) DiskMatchers() []disk.Matcher { if i.InstallDiskSelector != nil { selector := i.InstallDiskSelector - matchers := []disk.Matcher{} + var matchers []disk.Matcher if selector.Size != nil { matchers = append(matchers, selector.Size.Matcher) } diff --git a/pkg/machinery/config/types/v1alpha1/v1alpha1_types.go b/pkg/machinery/config/types/v1alpha1/v1alpha1_types.go index 43e444604f..7ce7209ead 100644 --- a/pkg/machinery/config/types/v1alpha1/v1alpha1_types.go +++ b/pkg/machinery/config/types/v1alpha1/v1alpha1_types.go @@ -726,7 +726,7 @@ type NetworkConfig struct { type NetworkDeviceList []*Device // Merge the network interface configuration intelligently. -func (devices *NetworkDeviceList) Merge(other interface{}) error { +func (devices *NetworkDeviceList) Merge(other any) error { otherDevices, ok := other.(NetworkDeviceList) if !ok { return fmt.Errorf("unexpected type for device merge %T", other) @@ -832,12 +832,12 @@ type InstallDiskSizeMatcher struct { } // MarshalYAML is a custom marshaller for `InstallDiskSizeMatcher`. -func (m *InstallDiskSizeMatcher) MarshalYAML() (interface{}, error) { +func (m *InstallDiskSizeMatcher) MarshalYAML() (any, error) { return m.condition, nil } // UnmarshalYAML is a custom unmarshaller for `InstallDiskSizeMatcher`. -func (m *InstallDiskSizeMatcher) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (m *InstallDiskSizeMatcher) UnmarshalYAML(unmarshal func(any) error) error { if err := unmarshal(&m.condition); err != nil { return err } @@ -910,12 +910,12 @@ func (in *InstallDiskSizeMatchData) Compare(d *disk.Disk) bool { type InstallDiskType disk.Type // MarshalYAML is a custom marshaller for `InstallDiskSizeMatcher`. -func (it InstallDiskType) MarshalYAML() (interface{}, error) { +func (it InstallDiskType) MarshalYAML() (any, error) { return disk.Type(it).String(), nil } // UnmarshalYAML is a custom unmarshaler for `InstallDiskType`. -func (it *InstallDiskType) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (it *InstallDiskType) UnmarshalYAML(unmarshal func(any) error) error { var ( t string err error @@ -1059,7 +1059,7 @@ type Endpoint struct { } // UnmarshalYAML is a custom unmarshaller for `Endpoint`. -func (e *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (e *Endpoint) UnmarshalYAML(unmarshal func(any) error) error { var endpoint string if err := unmarshal(&endpoint); err != nil { @@ -1077,7 +1077,7 @@ func (e *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error { } // MarshalYAML is a custom marshaller for `Endpoint`. -func (e *Endpoint) MarshalYAML() (interface{}, error) { +func (e *Endpoint) MarshalYAML() (any, error) { return e.URL.String(), nil } @@ -1178,7 +1178,7 @@ type APIServerConfig struct { type AdmissionPluginConfigList []*AdmissionPluginConfig // Merge the admission plugin configuration intelligently. -func (configs *AdmissionPluginConfigList) Merge(other interface{}) error { +func (configs *AdmissionPluginConfigList) Merge(other any) error { otherConfigs, ok := other.(AdmissionPluginConfigList) if !ok { return fmt.Errorf("unexpected type for device merge %T", other) @@ -1495,7 +1495,7 @@ type MachineDisk struct { type DiskSize uint64 // MarshalYAML write as human readable string. -func (ds DiskSize) MarshalYAML() (interface{}, error) { +func (ds DiskSize) MarshalYAML() (any, error) { if ds%DiskSize(1000) == 0 { bytesString := humanize.Bytes(uint64(ds)) // ensure that stringifying bytes as human readable string @@ -1510,7 +1510,7 @@ func (ds DiskSize) MarshalYAML() (interface{}, error) { } // UnmarshalYAML read from human readable string. -func (ds *DiskSize) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (ds *DiskSize) UnmarshalYAML(unmarshal func(any) error) error { var size string if err := unmarshal(&size); err != nil { @@ -1658,7 +1658,7 @@ func (fm FileMode) String() string { } // MarshalYAML encodes as an octal value. -func (fm FileMode) MarshalYAML() (interface{}, error) { +func (fm FileMode) MarshalYAML() (any, error) { return &yaml.Node{ Kind: yaml.ScalarNode, Tag: "!!int", @@ -1997,7 +1997,7 @@ type Bridge struct { type VlanList []*Vlan // Merge the network interface configuration intelligently. -func (vlans *VlanList) Merge(other interface{}) error { +func (vlans *VlanList) Merge(other any) error { otherVlans, ok := other.(VlanList) if !ok { return fmt.Errorf("unexpected type for vlan merge %T", other) diff --git a/pkg/machinery/config/types/v1alpha1/v1alpha1_unstructured.go b/pkg/machinery/config/types/v1alpha1/v1alpha1_unstructured.go index b14ec690cf..ad95435c78 100644 --- a/pkg/machinery/config/types/v1alpha1/v1alpha1_unstructured.go +++ b/pkg/machinery/config/types/v1alpha1/v1alpha1_unstructured.go @@ -14,7 +14,7 @@ import ( // docgen: nodoc // +k8s:deepcopy-gen=true type Unstructured struct { - Object map[string]interface{} `yaml:",inline"` + Object map[string]any `yaml:",inline"` } // DeepCopy performs copying of the Object contents. @@ -25,31 +25,31 @@ func (in *Unstructured) DeepCopy() *Unstructured { out := new(Unstructured) - out.Object = deepCopyUnstructured(in.Object).(map[string]interface{}) //nolint:errcheck,forcetypeassert + out.Object = deepCopyUnstructured(in.Object).(map[string]any) //nolint:errcheck,forcetypeassert return out } -func deepCopyUnstructured(x interface{}) interface{} { +func deepCopyUnstructured(x any) any { switch x := x.(type) { - case map[string]interface{}: + case map[string]any: if x == nil { return x } - clone := make(map[string]interface{}, len(x)) + clone := make(map[string]any, len(x)) for k, v := range x { clone[k] = deepCopyUnstructured(v) } return clone - case []interface{}: + case []any: if x == nil { return x } - clone := make([]interface{}, len(x)) + clone := make([]any, len(x)) for i, v := range x { clone[i] = deepCopyUnstructured(v) diff --git a/pkg/machinery/config/types/v1alpha1/v1alpha1_unstructured_test.go b/pkg/machinery/config/types/v1alpha1/v1alpha1_unstructured_test.go index 61c8f59baa..6772e5ccfd 100644 --- a/pkg/machinery/config/types/v1alpha1/v1alpha1_unstructured_test.go +++ b/pkg/machinery/config/types/v1alpha1/v1alpha1_unstructured_test.go @@ -14,12 +14,12 @@ import ( func TestUnstructuredDeepCopy(t *testing.T) { u := v1alpha1.Unstructured{ - Object: map[string]interface{}{ - "strings": map[string]interface{}{ + Object: map[string]any{ + "strings": map[string]any{ "foo": "bar", }, - "numbers": []interface{}{ - map[string]interface{}{ + "numbers": []any{ + map[string]any{ "int": 32, "int8": int8(34), "byte": byte(35), diff --git a/pkg/machinery/config/types/v1alpha1/v1alpha1_validation_test.go b/pkg/machinery/config/types/v1alpha1/v1alpha1_validation_test.go index b665bac9ef..39ad416dd0 100644 --- a/pkg/machinery/config/types/v1alpha1/v1alpha1_validation_test.go +++ b/pkg/machinery/config/types/v1alpha1/v1alpha1_validation_test.go @@ -1370,7 +1370,7 @@ func TestValidate(t *testing.T) { }, MachineKubelet: &v1alpha1.KubeletConfig{ KubeletExtraConfig: v1alpha1.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "port": 345, }, }, diff --git a/pkg/machinery/formatters/formatters.go b/pkg/machinery/formatters/formatters.go index ed71bcd796..dc30c01979 100644 --- a/pkg/machinery/formatters/formatters.go +++ b/pkg/machinery/formatters/formatters.go @@ -53,12 +53,12 @@ func RenderMounts(resp *machine.MountsResponse, output io.Writer, remotePeer *pe } format := "%s\t%.02f\t%.02f\t%.02f\t%.02f%%\t%s\n" - args := []interface{}{r.Filesystem, float64(r.Size) * 1e-9, float64(r.Size-r.Available) * 1e-9, float64(r.Available) * 1e-9, percentAvailable, r.MountedOn} + args := []any{r.Filesystem, float64(r.Size) * 1e-9, float64(r.Size-r.Available) * 1e-9, float64(r.Available) * 1e-9, percentAvailable, r.MountedOn} if defaultNode != "" { format = "%s\t" + format - args = append([]interface{}{node}, args...) + args = append([]any{node}, args...) } fmt.Fprintf(w, format, args...) @@ -177,7 +177,7 @@ func RenderGraph(ctx context.Context, c *client.Client, resp *inspect.Controller for _, msg := range resp.GetMessages() { for _, edge := range msg.GetEdges() { - idLabels := []string{} + var idLabels []string if edge.GetResourceId() != "" { idLabels = append(idLabels, edge.GetResourceId()) diff --git a/pkg/machinery/resources/config/machine_config.go b/pkg/machinery/resources/config/machine_config.go index 17cbd316c9..715aedef74 100644 --- a/pkg/machinery/resources/config/machine_config.go +++ b/pkg/machinery/resources/config/machine_config.go @@ -62,7 +62,7 @@ func (r *MachineConfig) Metadata() *resource.Metadata { } // Spec implements resource.Resource. -func (r *MachineConfig) Spec() interface{} { +func (r *MachineConfig) Spec() any { return r.spec } diff --git a/pkg/machinery/resources/config/machine_type.go b/pkg/machinery/resources/config/machine_type.go index 8916aed016..938010acde 100644 --- a/pkg/machinery/resources/config/machine_type.go +++ b/pkg/machinery/resources/config/machine_type.go @@ -30,7 +30,7 @@ type machineTypeSpec struct { machine.Type } -func (spec machineTypeSpec) MarshalYAML() (interface{}, error) { +func (spec machineTypeSpec) MarshalYAML() (any, error) { return spec.Type.String(), nil } @@ -50,7 +50,7 @@ func (r *MachineType) Metadata() *resource.Metadata { } // Spec implements resource.Resource. -func (r *MachineType) Spec() interface{} { +func (r *MachineType) Spec() any { return r.spec } diff --git a/pkg/machinery/resources/cri/deep_copy.generated.go b/pkg/machinery/resources/cri/deep_copy.generated.go index 76d2b0ab35..c0a2d5e0dd 100644 --- a/pkg/machinery/resources/cri/deep_copy.generated.go +++ b/pkg/machinery/resources/cri/deep_copy.generated.go @@ -10,7 +10,7 @@ package cri func (o SeccompProfileSpec) DeepCopy() SeccompProfileSpec { var cp SeccompProfileSpec = o if o.Value != nil { - cp.Value = make(map[string]interface{}, len(o.Value)) + cp.Value = make(map[string]any, len(o.Value)) for k2, v2 := range o.Value { cp.Value[k2] = v2 } diff --git a/pkg/machinery/resources/cri/seccomp_profile.go b/pkg/machinery/resources/cri/seccomp_profile.go index 8c5ad28d1e..9315b6977e 100644 --- a/pkg/machinery/resources/cri/seccomp_profile.go +++ b/pkg/machinery/resources/cri/seccomp_profile.go @@ -25,8 +25,8 @@ type SeccompProfile = typed.Resource[SeccompProfileSpec, SeccompProfileExtension // //gotagsrewrite:gen type SeccompProfileSpec struct { - Name string `yaml:"name" protobuf:"1"` - Value map[string]interface{} `yaml:"value" protobuf:"2"` + Name string `yaml:"name" protobuf:"1"` + Value map[string]any `yaml:"value" protobuf:"2"` } // NewSeccompProfile creates new SeccompProfile object. diff --git a/pkg/machinery/resources/k8s/admissioncontrol_config.go b/pkg/machinery/resources/k8s/admissioncontrol_config.go index 690eb28b39..7f86d959ec 100644 --- a/pkg/machinery/resources/k8s/admissioncontrol_config.go +++ b/pkg/machinery/resources/k8s/admissioncontrol_config.go @@ -34,8 +34,8 @@ type AdmissionControlConfigSpec struct { // //gotagsrewrite:gen type AdmissionPluginSpec struct { - Name string `yaml:"name" protobuf:"1"` - Configuration map[string]interface{} `yaml:"configuration" protobuf:"2"` + Name string `yaml:"name" protobuf:"1"` + Configuration map[string]any `yaml:"configuration" protobuf:"2"` } // NewAdmissionControlConfig returns new AdmissionControlConfig resource. diff --git a/pkg/machinery/resources/k8s/auditpolicy_config.go b/pkg/machinery/resources/k8s/auditpolicy_config.go index 78bed028c4..65ea6248dc 100644 --- a/pkg/machinery/resources/k8s/auditpolicy_config.go +++ b/pkg/machinery/resources/k8s/auditpolicy_config.go @@ -27,7 +27,7 @@ type AuditPolicyConfig = typed.Resource[AuditPolicyConfigSpec, AuditPolicyConfig // //gotagsrewrite:gen type AuditPolicyConfigSpec struct { - Config map[string]interface{} `yaml:"config" protobuf:"1"` + Config map[string]any `yaml:"config" protobuf:"1"` } // NewAuditPolicyConfig returns new AuditPolicyConfig resource. diff --git a/pkg/machinery/resources/k8s/deep_copy.generated.go b/pkg/machinery/resources/k8s/deep_copy.generated.go index 02120bb10b..3b16add2b4 100644 --- a/pkg/machinery/resources/k8s/deep_copy.generated.go +++ b/pkg/machinery/resources/k8s/deep_copy.generated.go @@ -20,7 +20,7 @@ func (o AdmissionControlConfigSpec) DeepCopy() AdmissionControlConfigSpec { copy(cp.Config, o.Config) for i2 := range o.Config { if o.Config[i2].Configuration != nil { - cp.Config[i2].Configuration = make(map[string]interface{}, len(o.Config[i2].Configuration)) + cp.Config[i2].Configuration = make(map[string]any, len(o.Config[i2].Configuration)) for k4, v4 := range o.Config[i2].Configuration { cp.Config[i2].Configuration[k4] = v4 } @@ -76,7 +76,7 @@ func (o APIServerConfigSpec) DeepCopy() APIServerConfigSpec { func (o AuditPolicyConfigSpec) DeepCopy() AuditPolicyConfigSpec { var cp AuditPolicyConfigSpec = o if o.Config != nil { - cp.Config = make(map[string]interface{}, len(o.Config)) + cp.Config = make(map[string]any, len(o.Config)) for k2, v2 := range o.Config { cp.Config[k2] = v2 } @@ -258,7 +258,7 @@ func (o ManifestSpec) DeepCopy() ManifestSpec { copy(cp.Items, o.Items) for i2 := range o.Items { if o.Items[i2].Object != nil { - cp.Items[i2].Object = make(map[string]interface{}, len(o.Items[i2].Object)) + cp.Items[i2].Object = make(map[string]any, len(o.Items[i2].Object)) for k4, v4 := range o.Items[i2].Object { cp.Items[i2].Object[k4] = v4 } diff --git a/pkg/machinery/resources/k8s/manifest.go b/pkg/machinery/resources/k8s/manifest.go index 0f2eddd145..f00361428f 100644 --- a/pkg/machinery/resources/k8s/manifest.go +++ b/pkg/machinery/resources/k8s/manifest.go @@ -30,11 +30,11 @@ type ManifestSpec struct { // //gotagsrewrite:gen type SingleManifest struct { - Object map[string]interface{} `protobuf:"1" yaml:",inline"` + Object map[string]any `protobuf:"1" yaml:",inline"` } // MarshalYAML implements yaml.Marshaler. -func (spec ManifestSpec) MarshalYAML() (interface{}, error) { +func (spec ManifestSpec) MarshalYAML() (any, error) { return spec.Items, nil } diff --git a/pkg/machinery/resources/k8s/static_pod.go b/pkg/machinery/resources/k8s/static_pod.go index ad974f7055..8062715409 100644 --- a/pkg/machinery/resources/k8s/static_pod.go +++ b/pkg/machinery/resources/k8s/static_pod.go @@ -27,7 +27,7 @@ type StaticPodSpec struct { } // MarshalYAML implements yaml.Marshaler. -func (spec StaticPodSpec) MarshalYAML() (interface{}, error) { +func (spec StaticPodSpec) MarshalYAML() (any, error) { return spec.Pod, nil } diff --git a/pkg/machinery/resources/k8s/static_pod_status.go b/pkg/machinery/resources/k8s/static_pod_status.go index b7816c78b7..a57493cbc2 100644 --- a/pkg/machinery/resources/k8s/static_pod_status.go +++ b/pkg/machinery/resources/k8s/static_pod_status.go @@ -27,7 +27,7 @@ type StaticPodStatusSpec struct { } // MarshalYAML implements yaml.Marshaler. -func (spec StaticPodStatusSpec) MarshalYAML() (interface{}, error) { +func (spec StaticPodStatusSpec) MarshalYAML() (any, error) { return spec.PodStatus, nil } diff --git a/pkg/machinery/resources/network/dns_upstream.go b/pkg/machinery/resources/network/dns_upstream.go index 89c572ddf0..f4237a4172 100644 --- a/pkg/machinery/resources/network/dns_upstream.go +++ b/pkg/machinery/resources/network/dns_upstream.go @@ -32,7 +32,7 @@ type DNSUpstreamSpecSpec struct { } // MarshalYAML implements yaml.Marshaler interface. -func (d *DNSUpstreamSpecSpec) MarshalYAML() (interface{}, error) { +func (d *DNSUpstreamSpecSpec) MarshalYAML() (any, error) { d.Prx.Healthcheck() return map[string]string{ diff --git a/pkg/makefs/vfat.go b/pkg/makefs/vfat.go index 18be20c122..04c3cff2c9 100644 --- a/pkg/makefs/vfat.go +++ b/pkg/makefs/vfat.go @@ -12,7 +12,7 @@ import ( func VFAT(partname string, setters ...Option) error { opts := NewDefaultOptions(setters...) - args := []string{} + var args []string if opts.Label != "" { args = append(args, "-F", "32", "-n", opts.Label) diff --git a/pkg/provision/providers/docker/node.go b/pkg/provision/providers/docker/node.go index 7d7634d62c..04e9ab83a7 100644 --- a/pkg/provision/providers/docker/node.go +++ b/pkg/provision/providers/docker/node.go @@ -115,8 +115,7 @@ func (p *provisioner) createNode(ctx context.Context, clusterReq provision.Clust } // Create the host config. - - mounts := []mount.Mount{} + mounts := make([]mount.Mount, 0, len(constants.Overlays)+5) for _, path := range []string{"/run", "/system", "/tmp"} { mounts = append(mounts, mount.Mount{ diff --git a/pkg/provision/providers/vm/launch.go b/pkg/provision/providers/vm/launch.go index 127132b3ba..7b0f03c77d 100644 --- a/pkg/provision/providers/vm/launch.go +++ b/pkg/provision/providers/vm/launch.go @@ -20,7 +20,7 @@ import ( ) // ReadConfig loads configuration from stdin. -func ReadConfig(config interface{}) error { +func ReadConfig(config any) error { d := json.NewDecoder(os.Stdin) if err := d.Decode(config); err != nil { return fmt.Errorf("error decoding config from stdin: %w", err)