Skip to content

Commit

Permalink
chore: simplify code
Browse files Browse the repository at this point in the history
- 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 <dmitry.matrenichev@siderolabs.com>
  • Loading branch information
DmitriyMV committed Jul 8, 2024
1 parent 963612b commit dad9c40
Show file tree
Hide file tree
Showing 144 changed files with 410 additions and 403 deletions.
2 changes: 1 addition & 1 deletion cmd/installer/pkg/install/manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion cmd/talosctl/cmd/mgmt/dhcpd_launch_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion cmd/talosctl/cmd/mgmt/gen/csr.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions cmd/talosctl/cmd/mgmt/gen/keypair.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions cmd/talosctl/cmd/talos/disks.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func printDisks(ctx context.Context, c *client.Client) error {
}
}

args := []interface{}{}
var args []any

if node != "" {
args = append(args, node)
Expand All @@ -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),
Expand Down
4 changes: 2 additions & 2 deletions cmd/talosctl/cmd/talos/diskusage.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ var duCmd = &cobra.Command{

size := stringifySize(info.Size)

args := []interface{}{
args := []any{
size, info.RelativeName,
}

Expand All @@ -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...)
Expand Down
12 changes: 6 additions & 6 deletions cmd/talosctl/cmd/talos/etcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
Expand Down Expand Up @@ -233,15 +233,15 @@ var etcdMemberListCmd = &cobra.Command{
}
}

args := []interface{}{
args := []any{
etcdresource.FormatMemberID(member.Id),
member.Hostname,
strings.Join(member.PeerUrls, ","),
strings.Join(member.ClientUrls, ","),
member.IsLearner,
}
if node != "" {
args = append([]interface{}{node}, args...)
args = append([]any{node}, args...)
}

fmt.Fprintf(w, pattern, args...)
Expand Down Expand Up @@ -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())),
Expand All @@ -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...)
Expand Down
22 changes: 11 additions & 11 deletions cmd/talosctl/cmd/talos/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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,
Expand All @@ -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()
Expand Down
16 changes: 8 additions & 8 deletions cmd/talosctl/cmd/talos/netstat.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ func (n *netstat) printNetstat(response *machine.NetstatResponse) error {
}
}

args := []interface{}{}
var args []any

if node != "" {
args = append(args, node)
Expand All @@ -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),
Expand All @@ -302,31 +302,31 @@ 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),
}...)
}

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

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],
}...)
}
Expand All @@ -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),
}...)
}
Expand Down
6 changes: 3 additions & 3 deletions cmd/talosctl/cmd/talos/output/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}
}
Expand All @@ -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 {
Expand All @@ -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("", " ")

Expand Down
6 changes: 3 additions & 3 deletions cmd/talosctl/cmd/talos/output/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion cmd/talosctl/cmd/talos/processes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
3 changes: 2 additions & 1 deletion cmd/talosctl/pkg/mgmt/helpers/wireguard.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion cmd/talosctl/pkg/talos/helpers/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
Expand Down
3 changes: 2 additions & 1 deletion cmd/talosctl/pkg/talos/yamlstrip/yamlstrip.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion hack/cloud-image-uploader/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
7 changes: 4 additions & 3 deletions hack/docgen/main.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/app/init/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ func mountRootFS() error {
image string
}

layers := []layer{}
var layers []layer

squashfs := mount.NewMountPoints()

Expand Down
Loading

0 comments on commit dad9c40

Please sign in to comment.