fix new lint errors

pull/19447/head
Steven Powell 2024-08-14 10:31:53 -07:00
parent e126545ff6
commit d8c94a6ad6
25 changed files with 137 additions and 75 deletions

View File

@ -20,7 +20,6 @@ import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"log"
v1 "k8s.io/api/admissionregistration/v1"
@ -59,7 +58,7 @@ func apiServerCert(clientset *kubernetes.Clientset) []byte {
pem, ok := c.Data["requestheader-client-ca-file"]
if !ok {
klog.Fatalf(fmt.Sprintf("cannot find the ca.crt in the configmap, configMap.Data is %#v", c.Data))
klog.Fatalf("cannot find the ca.crt in the configmap, configMap.Data is %#v", c.Data)
}
klog.Info("client-ca-file=", pem)
return []byte(pem)

View File

@ -241,7 +241,7 @@ func warnInvalidProfiles(invalidProfiles []*config.Profile) {
out.ErrT(style.Tip, "You can delete them using the following command(s): ")
for _, p := range invalidProfiles {
out.Err(fmt.Sprintf("\t $ minikube delete -p %s \n", p.Name))
out.Errf("\t $ minikube delete -p %s \n", p.Name)
}
}

View File

@ -36,7 +36,7 @@ func AskForYesNoConfirmation(s string, posResponses, negResponses []string) bool
reader := bufio.NewReader(os.Stdin)
for {
out.String("%s [y/n]: ", s)
out.Stringf("%s [y/n]: ", s)
response, err := reader.ReadString('\n')
if err != nil {
@ -78,7 +78,7 @@ func AskForStaticValueOptional(s string) string {
}
func getStaticValue(reader *bufio.Reader, s string) string {
out.String("%s", s)
out.String(s)
response, err := reader.ReadString('\n')
if err != nil {

View File

@ -642,7 +642,7 @@ func killProcess(path string) error {
// if multiple errors were encountered, combine them into a single error
out.Styled(style.Failure, "Multiple errors encountered:")
for _, e := range errs {
out.Err("%v\n", e)
out.Errf("%v\n", e)
}
return errors.New("multiple errors encountered while closing mount processes")
}

View File

@ -314,7 +314,7 @@ var buildImageCmd = &cobra.Command{
if runtime.GOOS == "windows" && strings.Contains(dockerFile, "\\") {
// if dockerFile is a DOS path, translate it into UNIX path
// because we are going to build this image in UNIX environment
out.String("minikube detects that you are using DOS-style path %s. minikube will convert it to UNIX-style by replacing all \\ to /", dockerFile)
out.Stringf("minikube detects that you are using DOS-style path %s. minikube will convert it to UNIX-style by replacing all \\ to /", dockerFile)
dockerFile = strings.ReplaceAll(dockerFile, "\\", "/")
}
if err := machine.BuildImage(img, dockerFile, tag, push, buildEnv, buildOpt, []*config.Profile{profile}, allNodes, nodeName); err != nil {

View File

@ -147,7 +147,7 @@ You may select another namespace by using 'minikube service {{.service}} -n <nam
data = append(data, []string{svc.Namespace, svc.Name, servicePortNames, serviceURLs})
if serviceURLMode && !driver.NeedsPortForward(co.Config.Driver) {
out.String(fmt.Sprintf("%s\n", serviceURLs))
out.Stringf("%s\n", serviceURLs)
}
}
// check whether there are running pods for this service
@ -229,7 +229,7 @@ func startKicServiceTunnel(services service.URLs, configName, driverName string)
service.PrintServiceList(os.Stdout, data)
} else {
for _, row := range data {
out.String(fmt.Sprintf("%s\n", row[3]))
out.Stringf("%s\n", row[3])
}
}
@ -286,12 +286,12 @@ func openURLs(urls [][]string) {
_, err := url.Parse(u[3])
if err != nil {
klog.Warningf("failed to parse url %q: %v (will not open)", u[3], err)
out.String(fmt.Sprintf("%s\n", u))
out.Stringf("%s\n", u)
continue
}
if serviceURLMode {
out.String(fmt.Sprintf("%s\n", u))
out.Stringf("%s\n", u)
continue
}

View File

@ -100,7 +100,7 @@ func TestSetAndSave(t *testing.T) {
// enable
if err := SetAndSave(profile, "dashboard", "true"); err != nil {
t.Errorf("Disable returned unexpected error: " + err.Error())
t.Errorf("Disable returned unexpected error: %v", err)
}
c, err := config.DefaultLoader.LoadConfigFromFile(profile)
@ -113,7 +113,7 @@ func TestSetAndSave(t *testing.T) {
// disable
if err := SetAndSave(profile, "dashboard", "false"); err != nil {
t.Errorf("Disable returned unexpected error: " + err.Error())
t.Errorf("Disable returned unexpected error: %v", err)
}
c, err = config.DefaultLoader.LoadConfigFromFile(profile)

View File

@ -17,6 +17,7 @@ limitations under the License.
package addons
import (
"errors"
"fmt"
"strconv"
@ -53,7 +54,7 @@ func isRuntimeContainerd(cc *config.ClusterConfig, _, _ string) error {
}
_, ok := r.(*cruntime.Containerd)
if !ok {
return fmt.Errorf(containerdOnlyAddonMsg)
return errors.New(containerdOnlyAddonMsg)
}
return nil
}

View File

@ -19,6 +19,7 @@ package kverify
import (
"context"
"errors"
"fmt"
"time"
@ -95,7 +96,7 @@ func waitPodCondition(cs *kubernetes.Clientset, name, namespace string, conditio
// return immediately: status == core.ConditionUnknown
if status == core.ConditionUnknown {
klog.Info(reason)
return false, fmt.Errorf(reason)
return false, errors.New(reason)
}
// reduce log spam
if time.Since(lap) > (2 * time.Second) {

View File

@ -58,7 +58,7 @@ func WaitForSystemPods(r cruntime.Manager, bs bootstrapper.Bootstrapper, cfg con
klog.Infof("%d kube-system pods found", len(pods.Items))
for _, pod := range pods.Items {
klog.Infof(podStatusMsg(pod))
klog.Info(podStatusMsg(pod))
}
if len(pods.Items) < 2 {
@ -86,7 +86,7 @@ func ExpectAppsRunning(cs *kubernetes.Clientset, expected []string) error {
klog.Infof("%d kube-system pods found", len(pods.Items))
for _, pod := range pods.Items {
klog.Infof(podStatusMsg(pod))
klog.Info(podStatusMsg(pod))
if pod.Status.Phase != core.PodRunning {
continue

View File

@ -100,7 +100,7 @@ func ISO(urls []string, skipChecksum bool) (string, error) {
msg.WriteString(fmt.Sprintf(" %s: %s\n", u, err))
}
return "", fmt.Errorf(msg.String())
return "", errors.New(msg.String())
}
// downloadISO downloads an ISO URL

View File

@ -70,7 +70,7 @@ func Message(r reason.Kind, format string, args ...out.V) {
// Code will exit with a code
func Code(code int) {
if shell {
out.Output(os.Stdout, fmt.Sprintf("false exit code %d\n", code))
out.Outputf(os.Stdout, "false exit code %d\n", code)
}
os.Exit(code)
}

View File

@ -762,21 +762,21 @@ func ListImages(profile *config.Profile, format string) error {
klog.Warningf("Error marshalling images list: %v", err.Error())
return nil
}
fmt.Printf(string(json) + "\n")
fmt.Printf("%s\n", string(json))
case "yaml":
yaml, err := yaml.Marshal(uniqueImages)
if err != nil {
klog.Warningf("Error marshalling images list: %v", err.Error())
return nil
}
fmt.Printf(string(yaml) + "\n")
fmt.Printf("%s\n", string(yaml))
default:
res := []string{}
for _, item := range uniqueImages {
res = append(res, item.RepoTags...)
}
sort.Sort(sort.Reverse(sort.StringSlice(res)))
fmt.Printf(strings.Join(res, "\n") + "\n")
fmt.Printf("%s\n", strings.Join(res, "\n"))
}
return nil

View File

@ -191,7 +191,7 @@ func (api *LocalClient) Create(h *host.Host) error {
// CA cert and client cert should be generated atomically, otherwise might cause bad certificate error.
lockErr := api.flock.LockWithTimeout(time.Second * 5)
if lockErr != nil {
return fmt.Errorf("failed to acquire bootstrap client lock: %v " + lockErr.Error())
return fmt.Errorf("failed to acquire bootstrap client lock: %v", lockErr)
}
defer func() {
lockErr = api.flock.Unlock()

View File

@ -17,7 +17,6 @@ limitations under the License.
package machine
import (
"fmt"
"os/exec"
"path"
"strings"
@ -173,7 +172,7 @@ func backup(h host.Host, files []string) error {
}
}
if len(errs) > 0 {
return errors.Errorf(fmt.Sprintf("%v", errs))
return errors.Errorf("%v", errs)
}
return nil
}
@ -208,7 +207,7 @@ func restore(h host.Host) error {
}
}
if len(errs) > 0 {
return errors.Errorf(fmt.Sprintf("%v", errs))
return errors.Errorf("%v", errs)
}
return nil
}

View File

@ -632,7 +632,7 @@ func setupKubeconfig(h host.Host, cc config.ClusterConfig, n config.Node, cluste
exit.Message(reason.DrvCPEndpoint, fmt.Sprintf("failed to construct cluster server address: %v", err), out.V{"profileArg": fmt.Sprintf("--profile=%s", clusterName)})
}
}
addr := fmt.Sprintf("https://" + net.JoinHostPort(host, strconv.Itoa(port)))
addr := fmt.Sprintf("https://%s", net.JoinHostPort(host, strconv.Itoa(port)))
if cc.KubernetesConfig.APIServerName != constants.APIServerName {
addr = strings.ReplaceAll(addr, host, cc.KubernetesConfig.APIServerName)

View File

@ -122,7 +122,7 @@ func TestLatestVersionFromURLCorrect(t *testing.T) {
latestVersion, err := latestVersionFromURL(server.URL)
if err != nil {
t.Fatalf(err.Error())
t.Fatal(err.Error())
}
expectedVersion, _ := semver.Make(versionFromURL)
if latestVersion.Compare(expectedVersion) != 0 {

View File

@ -126,12 +126,12 @@ func boxedCommon(printFunc func(format string, a ...interface{}), cfg box.Config
// Boxed writes a stylized and templated message in a box to stdout using the default style config
func Boxed(format string, a ...V) {
boxedCommon(String, defaultBoxCfg, "", format, a...)
boxedCommon(Stringf, defaultBoxCfg, "", format, a...)
}
// BoxedErr writes a stylized and templated message in a box to stderr using the default style config
func BoxedErr(format string, a ...V) {
boxedCommon(Err, defaultBoxCfg, "", format, a...)
boxedCommon(Errf, defaultBoxCfg, "", format, a...)
}
// BoxedWithConfig writes a templated message in a box with customized style config to stdout
@ -141,7 +141,7 @@ func BoxedWithConfig(cfg box.Config, st style.Enum, title string, text string, a
}
// need to make sure no newlines are in the title otherwise box-cli-maker panics
title = strings.ReplaceAll(title, "\n", "")
boxedCommon(String, cfg, title, text, a...)
boxedCommon(Stringf, cfg, title, text, a...)
}
// Sprintf is used for returning the string (doesn't write anything)
@ -159,8 +159,32 @@ func Infof(format string, a ...V) {
String(outStyled)
}
// String writes a basic string to stdout
func String(s string) {
// Flush log buffer so that output order makes sense
klog.Flush()
defer klog.Flush()
if silent || JSON {
klog.Info(s)
return
}
if outFile == nil {
klog.Warningf("[unset outFile]: %s", s)
return
}
klog.Info(s)
// if spin is active from a previous step, it will stop spinner displaying
if spin.Active() {
spin.Stop()
}
Output(outFile, s)
}
// String writes a basic formatted string to stdout
func String(format string, a ...interface{}) {
func Stringf(format string, a ...interface{}) {
// Flush log buffer so that output order makes sense
klog.Flush()
defer klog.Flush()
@ -180,11 +204,18 @@ func String(format string, a ...interface{}) {
spin.Stop()
}
Output(outFile, format, a...)
Outputf(outFile, format, a...)
}
// Output writes a basic formatted string
func Output(file fdWriter, format string, a ...interface{}) {
// Output writes a basic string
func Output(file fdWriter, s string) {
if _, err := fmt.Fprint(file, s); err != nil {
klog.Errorf("Fprint failed: %v", err)
}
}
// Outputf writes a basic formatted string
func Outputf(file fdWriter, format string, a ...interface{}) {
_, err := fmt.Fprintf(file, format, a...)
if err != nil {
klog.Errorf("Fprintf failed: %v", err)
@ -192,28 +223,28 @@ func Output(file fdWriter, format string, a ...interface{}) {
}
// spinnerString writes a basic formatted string to stdout with spinner character
func spinnerString(format string, a ...interface{}) {
func spinnerString(s string) {
// Flush log buffer so that output order makes sense
klog.Flush()
if outFile == nil {
klog.Warningf("[unset outFile]: %s", fmt.Sprintf(format, a...))
klog.Warningf("[unset outFile]: %s", s)
return
}
klog.Infof(format, a...)
klog.Info(s)
// if spin is active from a previous step, it will stop spinner displaying
if spin.Active() {
spin.Stop()
}
Output(outFile, format, a...)
Output(outFile, s)
// Start spinning at the end of the printed line
spin.Start()
}
// Ln writes a basic formatted string with a newline to stdout
func Ln(format string, a ...interface{}) {
String(format+"\n", a...)
Stringf(format+"\n", a...)
}
// ErrT writes a stylized and templated error message to stderr
@ -222,8 +253,31 @@ func ErrT(st style.Enum, format string, a ...V) {
Err(errStyled)
}
// Err writes a basic formatted string to stderr
func Err(format string, a ...interface{}) {
// Err writes a basic string to stderr
func Err(s string) {
if JSON {
register.PrintError(s)
klog.Warning(s)
return
}
register.RecordError(s)
if errFile == nil {
klog.Errorf("[unset errFile]: %s", s)
return
}
klog.Warning(s)
// if spin is active from a previous step, it will stop spinner displaying
if spin.Active() {
spin.Stop()
}
Output(errFile, s)
}
// Errf writes a basic formatted string to stderr
func Errf(format string, a ...interface{}) {
if JSON {
register.PrintError(format)
klog.Warningf(format, a...)
@ -242,12 +296,12 @@ func Err(format string, a ...interface{}) {
if spin.Active() {
spin.Stop()
}
Output(errFile, format, a...)
Outputf(errFile, format, a...)
}
// ErrLn writes a basic formatted string with a newline to stderr
func ErrLn(format string, a ...interface{}) {
Err(format+"\n", a...)
Errf(format+"\n", a...)
}
// SuccessT is a shortcut for writing a templated success message to stdout
@ -361,7 +415,7 @@ func LogEntries(msg string, err error, entries map[string][]string) {
// displayError prints the error and displays the standard minikube error messaging
func displayError(msg string, err error) {
klog.Warningf(fmt.Sprintf("%s: %v", msg, err))
klog.Warningf("%s: %v", msg, err)
if JSON {
ErrT(style.Fatal, "{{.msg}}: {{.err}}", V{"msg": translate.T(msg), "err": err})
return
@ -452,12 +506,6 @@ func applyTmpl(format string, a ...V) string {
// Return quotes back to normal
out = html.UnescapeString(out)
// escape any outstanding '%' signs so that they don't get interpreted
// as a formatting directive down the line
out = strings.ReplaceAll(out, "%", "%%")
// avoid doubling up in case this function is called multiple times
out = strings.ReplaceAll(out, "%%%%", "%%")
return out
}

View File

@ -33,7 +33,7 @@ import (
"k8s.io/minikube/pkg/minikube/translate"
)
func TestOutT(t *testing.T) {
func TestStep(t *testing.T) {
// Set the system locale to Arabic and define a dummy translation file.
translate.SetPreferredLanguage(language.Arabic)
@ -70,14 +70,14 @@ func TestOutT(t *testing.T) {
want = tc.want
}
if got != want {
t.Errorf("OutStyle() = %q (%d runes), want %q (%d runes)", got, len(got), want, len(want))
t.Errorf("Step() = %q (%d runes), want %q (%d runes)", got, len(got), want, len(want))
}
})
}
}
}
func TestOut(t *testing.T) {
func TestString(t *testing.T) {
t.Setenv(OverrideEnv, "")
testCases := []struct {
@ -97,11 +97,11 @@ func TestOut(t *testing.T) {
if tc.arg == nil {
String(tc.format)
} else {
String(tc.format, tc.arg)
Stringf(tc.format, tc.arg)
}
got := f.String()
if got != tc.want {
t.Errorf("Out(%s, %s) = %q, want %q", tc.format, tc.arg, got, tc.want)
t.Errorf("String(%s, %s) = %q, want %q", tc.format, tc.arg, got, tc.want)
}
})
}
@ -111,13 +111,27 @@ func TestErr(t *testing.T) {
t.Setenv(OverrideEnv, "0")
f := tests.NewFakeFile()
SetErrFile(f)
Err("xyz123 %s\n", "%s%%%d")
Err("xyz123\n")
Ln("unrelated message")
got := f.String()
want := "xyz123\n"
if got != want {
t.Errorf("Err() = %q, want %q", got, want)
}
}
func TestErrf(t *testing.T) {
t.Setenv(OverrideEnv, "0")
f := tests.NewFakeFile()
SetErrFile(f)
Errf("xyz123 %s\n", "%s%%%d")
Ln("unrelated message")
got := f.String()
want := "xyz123 %s%%%d\n"
if got != want {
t.Errorf("Err() = %q, want %q", got, want)
t.Errorf("Errf() = %q, want %q", got, want)
}
}

View File

@ -17,7 +17,7 @@ limitations under the License.
package reason
import (
"fmt"
"errors"
"testing"
)
@ -68,7 +68,7 @@ VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component MachineWrap,
}
for _, tc := range tests {
t.Run(tc.want, func(t *testing.T) {
got := MatchKnownIssue(Kind{}, fmt.Errorf(tc.err), tc.os)
got := MatchKnownIssue(Kind{}, errors.New(tc.err), tc.os)
if got == nil {
if tc.want != "" {
t.Errorf("FromError(%q)=nil, want %s", tc.err, tc.want)

View File

@ -230,13 +230,13 @@ func TestGetStoragev1(t *testing.T) {
}
configFile, err := os.CreateTemp("/tmp", "")
if err != nil {
t.Fatalf(err.Error())
t.Fatal(err.Error())
}
defer os.Remove(configFile.Name())
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
if err := setK8SConfig(t, test.config, configFile.Name()); err != nil {
t.Fatalf(err.Error())
t.Fatal(err.Error())
}
// context name is hardcoded by mockK8sConfig

View File

@ -17,7 +17,7 @@ limitations under the License.
package tests
import (
"fmt"
"errors"
"github.com/docker/machine/libmachine/drivers"
)
@ -49,7 +49,7 @@ func (m MockHost) RunSSHCommand(cmd string) (string, error) {
return output, nil
}
if m.Error != "" {
return "", fmt.Errorf(m.Error)
return "", errors.New(m.Error)
}
return "", nil
}

View File

@ -100,7 +100,7 @@ func (t *tunnel) cleanup() *Status {
err := t.router.Cleanup(t.status.TunnelID.Route)
if err != nil {
t.status.RouteError = errors.Errorf("error cleaning up route: %v", err)
klog.V(3).Infof(t.status.RouteError.Error())
klog.V(3).Info(t.status.RouteError.Error())
} else {
err = t.registry.Remove(t.status.TunnelID.Route)
if err != nil {
@ -211,7 +211,7 @@ func setupBridge(t *tunnel) {
command = exec.Command("sudo", "ifconfig", "bridge100", "deletem", member)
klog.Infof("About to run command: %s\n", command.Args)
response, err = command.CombinedOutput()
klog.Infof(string(response))
klog.Info(string(response))
if err != nil {
t.status.RouteError = fmt.Errorf("couldn't remove member %s: %s", member, err)
return
@ -220,7 +220,7 @@ func setupBridge(t *tunnel) {
command = exec.Command("sudo", "ifconfig", "bridge100", "addm", member)
klog.Infof("About to run command: %s\n", command.Args)
response, err = command.CombinedOutput()
klog.Infof(string(response))
klog.Info(string(response))
if err != nil {
t.status.RouteError = fmt.Errorf("couldn't re-add member %s: %s", member, err)
return

View File

@ -140,17 +140,17 @@ func validateHADeployApp(ctx context.Context, t *testing.T, profile string) {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "kubectl", "-p", profile, "--", "get", "pods", "-o", "jsonpath='{.items[*].status.podIP}'"))
if err != nil {
err := fmt.Errorf("failed to retrieve Pod IPs (may be temporary): %v", err)
t.Logf(err.Error())
t.Log(err.Error())
return err
}
podIPs := strings.Split(strings.Trim(rr.Stdout.String(), "'"), " ")
if len(podIPs) != 3 {
err := fmt.Errorf("expected 3 Pod IPs but got %d (may be temporary), output: %q", len(podIPs), rr.Output())
t.Logf(err.Error())
t.Log(err.Error())
return err
} else if podIPs[0] == podIPs[1] || podIPs[0] == podIPs[2] || podIPs[1] == podIPs[2] {
err := fmt.Errorf("expected 3 different pod IPs but got %s and %s (may be temporary), output: %q", podIPs[0], podIPs[1], rr.Output())
t.Logf(err.Error())
t.Log(err.Error())
return err
}
return nil
@ -419,7 +419,7 @@ func validateHARestartSecondaryNode(ctx context.Context, t *testing.T, profile s
// start stopped node(s) back up
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "node", "start", SecondNodeName, "-v=7", "--alsologtostderr"))
if err != nil {
t.Logf(rr.Stderr.String())
t.Log(rr.Stderr.String())
t.Errorf("secondary control-plane node start returned an error. args %q: %v", rr.Command(), err)
}

View File

@ -281,7 +281,7 @@ func validateStartNodeAfterStop(ctx context.Context, t *testing.T, profile strin
// Start the node back up
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "node", "start", ThirdNodeName, "-v=7", "--alsologtostderr"))
if err != nil {
t.Logf(rr.Stderr.String())
t.Log(rr.Stderr.String())
t.Errorf("node start returned an error. args %q: %v", rr.Command(), err)
}
@ -505,17 +505,17 @@ func validateDeployAppToMultiNode(ctx context.Context, t *testing.T, profile str
rr, err := Run(t, exec.CommandContext(ctx, Target(), "kubectl", "-p", profile, "--", "get", "pods", "-o", "jsonpath='{.items[*].status.podIP}'"))
if err != nil {
err := fmt.Errorf("failed to retrieve Pod IPs (may be temporary): %v", err)
t.Logf(err.Error())
t.Log(err.Error())
return err
}
podIPs := strings.Split(strings.Trim(rr.Stdout.String(), "'"), " ")
if len(podIPs) != 2 {
err := fmt.Errorf("expected 2 Pod IPs but got %d (may be temporary), output: %q", len(podIPs), rr.Output())
t.Logf(err.Error())
t.Log(err.Error())
return err
} else if podIPs[0] == podIPs[1] {
err := fmt.Errorf("expected 2 different pod IPs but got %s and %s (may be temporary), output: %q", podIPs[0], podIPs[1], rr.Output())
t.Logf(err.Error())
t.Log(err.Error())
return err
}
return nil