Skip to content

Commit

Permalink
Enable perfsprint linter
Browse files Browse the repository at this point in the history
... and fix lints on the way.

Most of the fixes are straightforward replacements of fmt.Errorf with
errors.New and string concatenations instead of fmt.Sprintf with a
single leading or trailing %s. Single integer conversions have been
replaced with the corresponding functions from the strconv package. Used
path.Join, filepath.Join and url.URL where it made sense.

Signed-off-by: Tom Wieczorek <[email protected]>
  • Loading branch information
twz123 committed Nov 15, 2024
1 parent 662d1e8 commit c0bc069
Show file tree
Hide file tree
Showing 104 changed files with 301 additions and 280 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ linters:
- gofmt # Checks whether code was gofmt-ed
- goheader # Checks is file headers matche a given pattern
- intrange # Checking for loops that could use an integer range
- perfsprint # Checks for faster fmt.Sprintf alternatives
- revive # Stricter drop-in replacement for golint
- testifylint # Checks usage of github.com/stretchr/testify
- unconvert # Checks for unnecessary type conversions
Expand Down
3 changes: 2 additions & 1 deletion cmd/airgap/listimages.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package airgap

import (
"errors"
"fmt"

"github.com/k0sproject/k0s/pkg/airgap"
Expand All @@ -39,7 +40,7 @@ func NewAirgapListImagesCmd() *cobra.Command {
}

if opts.EnableDynamicConfig {
return fmt.Errorf("dynamic config is not supported for airgap list-images")
return errors.New("dynamic config is not supported for airgap list-images")
}

clusterConfig, err := opts.K0sVars.NodeConfig()
Expand Down
11 changes: 7 additions & 4 deletions cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
Expand Down Expand Up @@ -221,7 +222,7 @@ func (c *command) isValidToken(ctx context.Context, token string, usage string)
return false
}

secretName := fmt.Sprintf("bootstrap-token-%s", parts[0])
secretName := "bootstrap-token-" + parts[0]
secret, err := c.client.CoreV1().Secrets("kube-system").Get(ctx, secretName, metav1.GetOptions{})
if err != nil {
logrus.Errorf("failed to get bootstrap token: %s", err.Error())
Expand All @@ -241,22 +242,24 @@ func (c *command) isValidToken(ctx context.Context, token string, usage string)
}

func (c *command) authMiddleware(next http.Handler, usage string) http.Handler {
unauthorizedErr := errors.New("go away")

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if auth == "" {
sendError(fmt.Errorf("go away"), w, http.StatusUnauthorized)
sendError(unauthorizedErr, w, http.StatusUnauthorized)
return
}

parts := strings.Split(auth, "Bearer ")
if len(parts) == 2 {
token := parts[1]
if !c.isValidToken(r.Context(), token, usage) {
sendError(fmt.Errorf("go away"), w, http.StatusUnauthorized)
sendError(unauthorizedErr, w, http.StatusUnauthorized)
return
}
} else {
sendError(fmt.Errorf("go away"), w, http.StatusUnauthorized)
sendError(unauthorizedErr, w, http.StatusUnauthorized)
return
}

Expand Down
3 changes: 2 additions & 1 deletion cmd/backup/backup_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ limitations under the License.
package backup

import (
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -56,7 +57,7 @@ func NewBackupCmd() *cobra.Command {
return err
}
if nodeConfig.Spec.Storage.Etcd.IsExternalClusterUsed() {
return fmt.Errorf("command 'k0s backup' does not support external etcd cluster")
return errors.New("command 'k0s backup' does not support external etcd cluster")
}
return c.backup(savePath, cmd.OutOrStdout())
},
Expand Down
14 changes: 8 additions & 6 deletions cmd/controller/certificates.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,18 @@ import (
"context"
"errors"
"fmt"
"net"
"net/url"
"os"
"path/filepath"
"strconv"

"github.com/k0sproject/k0s/internal/pkg/file"
"github.com/k0sproject/k0s/internal/pkg/users"
"github.com/k0sproject/k0s/pkg/apis/k0s/v1beta1"
"github.com/k0sproject/k0s/pkg/certificate"
"github.com/k0sproject/k0s/pkg/config"
"github.com/k0sproject/k0s/pkg/constant"
"net"
"os"
"path/filepath"
"strconv"

"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
Expand Down Expand Up @@ -66,7 +68,7 @@ func (c *Certificates) Init(ctx context.Context) error {
c.CACert = string(cert)
// Changing the URL here also requires changes in the "k0s kubeconfig admin" subcommand.
apiAddress := net.JoinHostPort(c.ClusterSpec.API.Address, strconv.Itoa(c.ClusterSpec.API.Port))
kubeConfigAPIUrl := fmt.Sprintf("https://%s", apiAddress)
kubeConfigAPIUrl := (&url.URL{Scheme: "https", Host: apiAddress}).String()

apiServerUID, err := users.LookupUID(constant.ApiserverUser)
if err != nil {
Expand Down Expand Up @@ -197,7 +199,7 @@ func (c *Certificates) Init(ctx context.Context) error {
"kubernetes.default",
"kubernetes.default.svc",
"kubernetes.default.svc.cluster",
fmt.Sprintf("kubernetes.svc.%s", c.ClusterSpec.Network.ClusterDomain),
"kubernetes.svc." + c.ClusterSpec.Network.ClusterDomain,
"localhost",
"127.0.0.1",
}
Expand Down
10 changes: 7 additions & 3 deletions cmd/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"net"
"os"
"os/signal"
"path"
"path/filepath"
"slices"
"syscall"
Expand Down Expand Up @@ -58,6 +59,7 @@ import (
"github.com/k0sproject/k0s/pkg/token"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/rest"
)

Expand Down Expand Up @@ -94,7 +96,7 @@ func NewControllerCmd() *cobra.Command {
c.TokenArg = args[0]
}
if c.TokenArg != "" && c.TokenFile != "" {
return fmt.Errorf("you can only pass one token argument either as a CLI argument 'k0s controller [join-token]' or as a flag 'k0s controller --token-file [path]'")
return errors.New("you can only pass one token argument either as a CLI argument 'k0s controller [join-token]' or as a flag 'k0s controller --token-file [path]'")
}
if err := c.ControllerOptions.Normalize(); err != nil {
return err
Expand Down Expand Up @@ -659,9 +661,11 @@ func (c *command) startWorker(ctx context.Context, profile string, nodeConfig *v
wc := workercmd.Command(*(*config.CLIOptions)(c))
wc.TokenArg = bootstrapConfig
wc.WorkerProfile = profile
wc.Labels = append(wc.Labels, fmt.Sprintf("%s=control-plane", constant.K0SNodeRoleLabel))
wc.Labels = append(wc.Labels, fields.OneTermEqualSelector(constant.K0SNodeRoleLabel, "control-plane").String())
if !c.SingleNode && !c.NoTaints {
wc.Taints = append(wc.Taints, fmt.Sprintf("%s/master=:NoSchedule", constant.NodeRoleLabelNamespace))
key := path.Join(constant.NodeRoleLabelNamespace, "master")
taint := fields.OneTermEqualSelector(key, ":NoSchedule")
wc.Taints = append(wc.Taints, taint.String())
}
return wc.Start(ctx)
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/etcd/etcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package etcd

import (
"errors"
"fmt"

"github.com/k0sproject/k0s/pkg/apis/k0s/v1beta1"
Expand Down Expand Up @@ -46,7 +47,7 @@ func NewEtcdCmd() *cobra.Command {
return fmt.Errorf("wrong storage type: %s", nodeConfig.Spec.Storage.Type)
}
if nodeConfig.Spec.Storage.Etcd.IsExternalClusterUsed() {
return fmt.Errorf("command 'k0s etcd' does not support external etcd cluster")
return errors.New("command 'k0s etcd' does not support external etcd cluster")
}
return nil
},
Expand Down
7 changes: 4 additions & 3 deletions cmd/etcd/leave.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"fmt"
"net"
"net/url"
"strconv"

"github.com/k0sproject/k0s/pkg/config"
"github.com/k0sproject/k0s/pkg/etcd"
Expand Down Expand Up @@ -52,7 +53,7 @@ func etcdLeaveCmd() *cobra.Command {
peerAddress := nodeConfig.Spec.Storage.Etcd.PeerAddress
if peerAddressArg == "" {
if peerAddress == "" {
return fmt.Errorf("can't leave etcd cluster: this node doesn't have an etcd peer address, check the k0s configuration or use --peer-address")
return errors.New("can't leave etcd cluster: this node doesn't have an etcd peer address, check the k0s configuration or use --peer-address")
}
} else {
peerAddress = peerAddressArg
Expand All @@ -73,13 +74,13 @@ func etcdLeaveCmd() *cobra.Command {
if err := etcdClient.DeleteMember(ctx, peerID); err != nil {
logrus.
WithField("peerURL", peerURL).
WithField("peerID", fmt.Sprintf("%x", peerID)).
WithField("peerID", strconv.FormatUint(peerID, 16)).
Errorf("Failed to delete node from cluster")
return err
}

logrus.
WithField("peerID", fmt.Sprintf("%x", peerID)).
WithField("peerID", strconv.FormatUint(peerID, 16)).
Info("Successfully deleted")
return nil
},
Expand Down
3 changes: 2 additions & 1 deletion cmd/install/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package install

import (
"errors"
"fmt"
"os"

Expand Down Expand Up @@ -54,7 +55,7 @@ func NewInstallCmd() *cobra.Command {
// - Sets up startup and logging for k0s.
func (c *command) setup(role string, args []string, installFlags *installFlags) error {
if os.Geteuid() != 0 {
return fmt.Errorf("this command must be run as root")
return errors.New("this command must be run as root")
}

nodeConfig, err := c.K0sVars.NodeConfig()
Expand Down
3 changes: 2 additions & 1 deletion cmd/kubectl/kubectl.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package kubectl

import (
"errors"
"fmt"
"os"
"os/exec"
Expand Down Expand Up @@ -171,7 +172,7 @@ func handleKubectlPlugins(kubectlCmd *cobra.Command) {
func fallbackToK0sKubeconfig(cmd *cobra.Command) error {
kubeconfigFlag := cmd.Flags().Lookup("kubeconfig")
if kubeconfigFlag == nil {
return fmt.Errorf("kubeconfig flag not found")
return errors.New("kubeconfig flag not found")
}

if kubeconfigFlag.Changed {
Expand Down
3 changes: 2 additions & 1 deletion cmd/restore/restore_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ limitations under the License.
package restore

import (
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -74,7 +75,7 @@ func NewRestoreCmd() *cobra.Command {

func (c *command) restore(path string, out io.Writer) error {
if os.Geteuid() != 0 {
return fmt.Errorf("this command must be run as root")
return errors.New("this command must be run as root")
}

k0sStatus, _ := status.GetStatusInfo(c.K0sVars.StatusSocketPath)
Expand Down
3 changes: 1 addition & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package cmd

import (
"errors"
"fmt"
"net/http"
"os"
"runtime"
Expand Down Expand Up @@ -135,7 +134,7 @@ func newDocsCmd() *cobra.Command {
case "man":
return doc.GenManTree(NewRootCmd(), &doc.GenManHeader{Title: "k0s", Section: "1"}, "./man")
}
return fmt.Errorf("invalid format")
return errors.New("invalid format")
},
}
}
Expand Down
6 changes: 3 additions & 3 deletions cmd/start/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ limitations under the License.
package start

import (
"fmt"
"errors"
"os"

"github.com/k0sproject/k0s/pkg/install"
Expand All @@ -32,15 +32,15 @@ func NewStartCmd() *cobra.Command {
Short: "Start the k0s service configured on this host. Must be run as root (or with sudo)",
RunE: func(cmd *cobra.Command, args []string) error {
if os.Geteuid() != 0 {
return fmt.Errorf("this command must be run as root")
return errors.New("this command must be run as root")
}
svc, err := install.InstalledService()
if err != nil {
return err
}
status, _ := svc.Status()
if status == service.StatusRunning {
return fmt.Errorf("already running")
return errors.New("already running")
}
return svc.Start()
},
Expand Down
6 changes: 3 additions & 3 deletions cmd/stop/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ limitations under the License.
package stop

import (
"fmt"
"errors"
"os"

"github.com/k0sproject/k0s/pkg/install"
Expand All @@ -32,7 +32,7 @@ func NewStopCmd() *cobra.Command {
Short: "Stop the k0s service configured on this host. Must be run as root (or with sudo)",
RunE: func(cmd *cobra.Command, args []string) error {
if os.Geteuid() != 0 {
return fmt.Errorf("this command must be run as root")
return errors.New("this command must be run as root")
}
svc, err := install.InstalledService()
if err != nil {
Expand All @@ -43,7 +43,7 @@ func NewStopCmd() *cobra.Command {
return err
}
if status == service.StatusStopped {
return fmt.Errorf("already stopped")
return errors.New("already stopped")
}
return svc.Stop()
},
Expand Down
5 changes: 3 additions & 2 deletions cmd/token/preshared.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package token
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -55,10 +56,10 @@ func preSharedCmd() *cobra.Command {
return err
}
if certPath == "" {
return fmt.Errorf("please, provide --cert argument")
return errors.New("please, provide --cert argument")
}
if joinURL == "" {
return fmt.Errorf("please, provide --url argument")
return errors.New("please, provide --url argument")
}

return nil
Expand Down
2 changes: 1 addition & 1 deletion cmd/worker/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func NewWorkerCmd() *cobra.Command {
}

if c.TokenArg != "" && c.TokenFile != "" {
return fmt.Errorf("you can only pass one token argument either as a CLI argument 'k0s worker [token]' or as a flag 'k0s worker --token-file [path]'")
return errors.New("you can only pass one token argument either as a CLI argument 'k0s worker [token]' or as a flag 'k0s worker --token-file [path]'")
}

if err := (&sysinfo.K0sSysinfoSpec{
Expand Down
3 changes: 2 additions & 1 deletion hack/tool/cmd/aws/provision/provision.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package provision

import (
"context"
"errors"
"fmt"
"os"
"os/exec"
Expand Down Expand Up @@ -100,7 +101,7 @@ func bugfixK0sctlNullImages(k0sctlConfigFile string) error {
cmd.Stdout = os.Stdout

if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to post-process k0sctl.yaml")
return errors.New("failed to post-process k0sctl.yaml")
}

return nil
Expand Down
Loading

0 comments on commit c0bc069

Please sign in to comment.