From 092db3cf7719144907d7321cc78b3163af837b8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20L=C3=A9one?= Date: Tue, 20 Aug 2024 18:04:30 +0200 Subject: [PATCH 1/2] chore: add support for perfsprint --- .golangci.yml | 1 + internal/core/checks_test.go | 4 ++-- internal/core/cobra_utils_test.go | 15 ++++++++------- internal/core/errors.go | 3 ++- internal/core/printer.go | 3 ++- internal/core/reflect.go | 2 +- internal/core/validate_test.go | 19 ++++++++++--------- internal/namespaces/alias/alias_test.go | 4 ++-- .../v1alpha1/custom_server_ssh.go | 3 ++- .../namespaces/autocomplete/autocomplete.go | 5 +++-- .../baremetal/v1/custom_server_fip_prompt.go | 3 ++- .../v2beta1/custom_invoice_download.go | 5 +++-- .../billing/v2beta1/custom_invoice_export.go | 3 ++- internal/namespaces/config/commands.go | 7 ++++--- internal/namespaces/feedback/issue.go | 4 ++-- .../function/v1beta1/custom_deploy_test.go | 3 ++- .../iam/v1alpha1/custom_rule_test.go | 4 ++-- internal/namespaces/init/prompt.go | 11 ++++++----- .../instance/v1/custom_security_group.go | 3 ++- .../namespaces/instance/v1/custom_server.go | 2 +- .../instance/v1/custom_server_create.go | 3 ++- .../instance/v1/custom_server_ssh.go | 3 ++- internal/namespaces/lb/v1/custom_backend.go | 2 +- .../mnq/v1beta1/custom_nats_helpers.go | 3 ++- .../mnq/v1beta1/custom_nats_prompt.go | 5 +++-- internal/namespaces/object/v1/s3configfile.go | 7 ++++--- internal/namespaces/rdb/v1/custom_backup.go | 3 ++- internal/namespaces/rdb/v1/custom_instance.go | 2 +- internal/namespaces/rdb/v1/custom_url.go | 3 ++- internal/namespaces/rdb/v1/helper_test.go | 3 ++- .../secret/v1beta1/custom_secret_version.go | 3 ++- internal/tasks/tasks_test.go | 7 ++++--- 32 files changed, 86 insertions(+), 62 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 519f631236..b6a3e6310d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -62,6 +62,7 @@ linters: - wastedassign # wastedassign finds wasted assignment statements. [fast: false, auto-fix: false] - whitespace # Tool for detection of leading and trailing whitespace [fast: true, auto-fix: true] - zerologlint # Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg` [fast: false, auto-fix: false] + - perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative. [fast: false, auto-fix: false] disable: - cyclop # checks function and package cyclomatic complexity [fast: false, auto-fix: false] diff --git a/internal/core/checks_test.go b/internal/core/checks_test.go index 3aaecf6066..fc3e10a409 100644 --- a/internal/core/checks_test.go +++ b/internal/core/checks_test.go @@ -2,7 +2,7 @@ package core_test import ( "context" - "fmt" + "errors" "path/filepath" "reflect" "strings" @@ -35,7 +35,7 @@ func TestCheckAPIKey(t *testing.T) { api := iam.NewAPI(ctx.Client) accessKey, exists := ctx.Client.GetAccessKey() if !exists { - return fmt.Errorf("missing access-key") + return errors.New("missing access-key") } apiKey, err := api.GetAPIKey(&iam.GetAPIKeyRequest{ diff --git a/internal/core/cobra_utils_test.go b/internal/core/cobra_utils_test.go index 3ec28e8e7a..609b55c70f 100644 --- a/internal/core/cobra_utils_test.go +++ b/internal/core/cobra_utils_test.go @@ -2,6 +2,7 @@ package core_test import ( "context" + "errors" "fmt" "reflect" "testing" @@ -115,7 +116,7 @@ func Test_handleUnmarshalErrors(t *testing.T) { Check: core.TestCheckCombine( core.TestCheckExitCode(1), core.TestCheckError(&core.CliError{ - Err: fmt.Errorf("invalid argument 'name_id': arg name must only contain lowercase letters, numbers or dashes"), + Err: errors.New("invalid argument 'name_id': arg name must only contain lowercase letters, numbers or dashes"), Hint: "Valid arguments are: name-id", }), ), @@ -127,7 +128,7 @@ func Test_handleUnmarshalErrors(t *testing.T) { Check: core.TestCheckCombine( core.TestCheckExitCode(1), core.TestCheckError(&core.CliError{ - Err: fmt.Errorf("invalid argument 'ubuntu_focal': arg name must only contain lowercase letters, numbers or dashes"), + Err: errors.New("invalid argument 'ubuntu_focal': arg name must only contain lowercase letters, numbers or dashes"), Hint: "Valid arguments are: name-id", }), ), @@ -143,7 +144,7 @@ func Test_handleUnmarshalErrors(t *testing.T) { Details: `Absolute time error: parsing time "+3R" as "2006-01-02T15:04:05Z07:00": cannot parse "+3R" as "2006" Relative time error: unknown unit in duration: "R" `, - Err: fmt.Errorf("date parsing error: +3R"), + Err: errors.New("date parsing error: +3R"), Hint: "Run `scw help date` to learn more about date parsing", }), ), @@ -177,7 +178,7 @@ func Test_PositionalArg(t *testing.T) { Check: core.TestCheckCombine( core.TestCheckExitCode(1), core.TestCheckError(&core.CliError{ - Err: fmt.Errorf("a positional argument is required for this command"), + Err: errors.New("a positional argument is required for this command"), Hint: "Try running: scw test positional ", }), ), @@ -201,7 +202,7 @@ func Test_PositionalArg(t *testing.T) { Check: core.TestCheckCombine( core.TestCheckExitCode(1), core.TestCheckError(&core.CliError{ - Err: fmt.Errorf("a positional argument is required for this command"), + Err: errors.New("a positional argument is required for this command"), Hint: "Try running: scw test positional plop tag=world", }), ), @@ -213,7 +214,7 @@ func Test_PositionalArg(t *testing.T) { Check: core.TestCheckCombine( core.TestCheckExitCode(1), core.TestCheckError(&core.CliError{ - Err: fmt.Errorf("a positional argument is required for this command"), + Err: errors.New("a positional argument is required for this command"), Hint: "Try running: scw test positional plop tag=world", }), ), @@ -225,7 +226,7 @@ func Test_PositionalArg(t *testing.T) { Check: core.TestCheckCombine( core.TestCheckExitCode(1), core.TestCheckError(&core.CliError{ - Err: fmt.Errorf("a positional argument is required for this command"), + Err: errors.New("a positional argument is required for this command"), Hint: "Try running: scw test positional plop", }), ), diff --git a/internal/core/errors.go b/internal/core/errors.go index 2cbe56e92f..54cb862ac0 100644 --- a/internal/core/errors.go +++ b/internal/core/errors.go @@ -1,6 +1,7 @@ package core import ( + "errors" "fmt" ) @@ -74,6 +75,6 @@ func ArgumentConflictError(arg1 string, arg2 string) *CliError { func WindowIsNotSupportedError() *CliError { return &CliError{ - Err: fmt.Errorf("windows is not currently supported"), + Err: errors.New("windows is not currently supported"), } } diff --git a/internal/core/printer.go b/internal/core/printer.go index 09c3255031..ee62b3aaaf 100644 --- a/internal/core/printer.go +++ b/internal/core/printer.go @@ -2,6 +2,7 @@ package core import ( "encoding/json" + "errors" "fmt" "io" "reflect" @@ -103,7 +104,7 @@ func setupTemplatePrinter(printer *Printer, opts string) error { printer.printerType = PrinterTypeTemplate if opts == "" { return &CliError{ - Err: fmt.Errorf("cannot use a template output with an empty template"), + Err: errors.New("cannot use a template output with an empty template"), Hint: `Try using golang template string: scw instance server list -o template="{{ .ID }} ☜(˚▽˚)☞ {{ .Name }}"`, Details: `https://golang.org/pkg/text/template`, } diff --git a/internal/core/reflect.go b/internal/core/reflect.go index 0e0c72b676..cf2d0e3f68 100644 --- a/internal/core/reflect.go +++ b/internal/core/reflect.go @@ -114,5 +114,5 @@ func GetValuesForFieldByName(value reflect.Value, parts []string) (values []refl return nil, fmt.Errorf("field %v does not exist for %v", fieldName, value.Type().Name()) } - return nil, fmt.Errorf("case is not handled") + return nil, errors.New("case is not handled") } diff --git a/internal/core/validate_test.go b/internal/core/validate_test.go index 7b20eb70a5..5b9c2c5ec2 100644 --- a/internal/core/validate_test.go +++ b/internal/core/validate_test.go @@ -2,6 +2,7 @@ package core_test import ( "context" + "errors" "fmt" "reflect" "testing" @@ -40,7 +41,7 @@ func Test_DefaultCommandValidateFunc(t *testing.T) { run := func(testCase TestCase) func(t *testing.T) { return func(t *testing.T) { err := core.DefaultCommandValidateFunc()(context.Background(), testCase.command, testCase.parsedArguments, testCase.rawArgs) - assert.Equal(t, fmt.Errorf("arg validation called"), err) + assert.Equal(t, errors.New("arg validation called"), err) } } @@ -50,7 +51,7 @@ func Test_DefaultCommandValidateFunc(t *testing.T) { { Name: "name", ValidateFunc: func(_ *core.ArgSpec, _ interface{}) error { - return fmt.Errorf("arg validation called") + return errors.New("arg validation called") }, }, }, @@ -69,7 +70,7 @@ func Test_DefaultCommandValidateFunc(t *testing.T) { { Name: "elements-map.{key}.name", ValidateFunc: func(_ *core.ArgSpec, _ interface{}) error { - return fmt.Errorf("arg validation called") + return errors.New("arg validation called") }, }, }, @@ -97,7 +98,7 @@ func Test_DefaultCommandValidateFunc(t *testing.T) { { Name: "elements-slice.{index}.name", ValidateFunc: func(_ *core.ArgSpec, _ interface{}) error { - return fmt.Errorf("arg validation called") + return errors.New("arg validation called") }, }, }, @@ -174,7 +175,7 @@ func Test_DefaultCommandValidateFunc(t *testing.T) { { Name: "name", ValidateFunc: func(_ *core.ArgSpec, _ interface{}) error { - return fmt.Errorf("arg validation called") + return errors.New("arg validation called") }, }, }, @@ -770,7 +771,7 @@ func Test_ValidateOneOf(t *testing.T) { Cmd: "scw oneof c=yo", Check: core.TestCheckCombine( core.TestCheckExitCode(1), - core.TestCheckError(fmt.Errorf("at least one argument from the 'group1' group is required")), + core.TestCheckError(errors.New("at least one argument from the 'group1' group is required")), ), })(t) }) @@ -800,7 +801,7 @@ func Test_ValidateOneOf(t *testing.T) { Cmd: "scw oneof a=yo b=no", Check: core.TestCheckCombine( core.TestCheckExitCode(1), - core.TestCheckError(fmt.Errorf("arguments 'a' and 'b' are mutually exclusive")), + core.TestCheckError(errors.New("arguments 'a' and 'b' are mutually exclusive")), ), })(t) }) @@ -868,7 +869,7 @@ func Test_ValidateOneOf(t *testing.T) { Cmd: "scw oneof all-ssh-keys=true ssh-key.0=11111111-1111-1111-1111-111111111111", Check: core.TestCheckCombine( core.TestCheckExitCode(1), - core.TestCheckError(fmt.Errorf("arguments 'ssh-key.0' and 'all-ssh-keys' are mutually exclusive")), + core.TestCheckError(errors.New("arguments 'ssh-key.0' and 'all-ssh-keys' are mutually exclusive")), ), })(t) }) @@ -999,7 +1000,7 @@ func Test_ValidateOneOf(t *testing.T) { Cmd: "scw oneof arg=true", Check: core.TestCheckCombine( core.TestCheckExitCode(1), - core.TestCheckError(fmt.Errorf("at least one argument from the 'ssh' group is required")), + core.TestCheckError(errors.New("at least one argument from the 'ssh' group is required")), ), })(t) }) diff --git a/internal/namespaces/alias/alias_test.go b/internal/namespaces/alias/alias_test.go index cf1eb5e552..9f038bd713 100644 --- a/internal/namespaces/alias/alias_test.go +++ b/internal/namespaces/alias/alias_test.go @@ -1,7 +1,7 @@ package alias_test import ( - "fmt" + "errors" "strings" "testing" @@ -80,7 +80,7 @@ func Test_Alias(t *testing.T) { } if strings.Contains(resString, "instance") { - return fmt.Errorf("alias list should not contain instance") + return errors.New("alias list should not contain instance") } return nil }, diff --git a/internal/namespaces/applesilicon/v1alpha1/custom_server_ssh.go b/internal/namespaces/applesilicon/v1alpha1/custom_server_ssh.go index 7931556a0e..543dadb57a 100644 --- a/internal/namespaces/applesilicon/v1alpha1/custom_server_ssh.go +++ b/internal/namespaces/applesilicon/v1alpha1/custom_server_ssh.go @@ -2,6 +2,7 @@ package applesilicon import ( "context" + "errors" "fmt" "os/exec" "reflect" @@ -70,7 +71,7 @@ func serverSSHRun(ctx context.Context, argsI interface{}) (i interface{}, e erro if serverResp.Status != applesilicon.ServerStatusReady { return nil, &core.CliError{ - Err: fmt.Errorf("server is not ready"), + Err: errors.New("server is not ready"), Details: fmt.Sprintf("Server %s currently in %s", serverResp.Name, serverResp.Status), } } diff --git a/internal/namespaces/autocomplete/autocomplete.go b/internal/namespaces/autocomplete/autocomplete.go index 1b8cfe1a12..6226013d0a 100644 --- a/internal/namespaces/autocomplete/autocomplete.go +++ b/internal/namespaces/autocomplete/autocomplete.go @@ -2,6 +2,7 @@ package autocomplete import ( "context" + "errors" "fmt" "io" "os" @@ -269,7 +270,7 @@ func autocompleteCompleteBashCommand() *core.Command { Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) { rawArgs := *argsI.(*args.RawArgs) if len(rawArgs) < 3 { - return nil, fmt.Errorf("not enough arguments") + return nil, errors.New("not enough arguments") } wordIndex, err := strconv.Atoi(rawArgs[1]) if err != nil { @@ -354,7 +355,7 @@ func autocompleteCompleteZshCommand() *core.Command { Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) { rawArgs := *argsI.(*args.RawArgs) if len(rawArgs) < 2 { - return nil, fmt.Errorf("not enough arguments") + return nil, errors.New("not enough arguments") } // First arg is the word index. diff --git a/internal/namespaces/baremetal/v1/custom_server_fip_prompt.go b/internal/namespaces/baremetal/v1/custom_server_fip_prompt.go index 3da8b3c967..b2354ee6f7 100644 --- a/internal/namespaces/baremetal/v1/custom_server_fip_prompt.go +++ b/internal/namespaces/baremetal/v1/custom_server_fip_prompt.go @@ -2,6 +2,7 @@ package baremetal import ( "context" + "errors" "fmt" "github.com/fatih/color" @@ -15,7 +16,7 @@ var ipTypeOption = []string{"IPv4", "IPv6"} func promptIPFlexibleServer(ctx context.Context, req *serverAddFlexibleIPRequest) (*serverAddFlexibleIPRequest, error) { if !interactive.IsInteractive { return nil, &core.CliError{ - Err: fmt.Errorf("failed to create and attach a new flexible IP"), + Err: errors.New("failed to create and attach a new flexible IP"), Hint: "Missing argument 'ip-type'", } } diff --git a/internal/namespaces/billing/v2beta1/custom_invoice_download.go b/internal/namespaces/billing/v2beta1/custom_invoice_download.go index 9b3d92f107..477b363f4d 100644 --- a/internal/namespaces/billing/v2beta1/custom_invoice_download.go +++ b/internal/namespaces/billing/v2beta1/custom_invoice_download.go @@ -2,6 +2,7 @@ package billing import ( "context" + "errors" "fmt" "io" "os" @@ -83,7 +84,7 @@ func invoiceDownloadBuilder(command *core.Command) *core.Command { if len(file) > 0 { fileExtension := filepath.Ext(file) if extensionOnFile := checkDownloadInvoiceExt(fileExtension); !extensionOnFile { - return fmt.Errorf("file has not supported extension") + return errors.New("file has not supported extension") } } @@ -126,7 +127,7 @@ func invoiceDownloadBuilder(command *core.Command) *core.Command { return err } if !overrideFile { - return fmt.Errorf("download file canceled") + return errors.New("download file canceled") } } diff --git a/internal/namespaces/billing/v2beta1/custom_invoice_export.go b/internal/namespaces/billing/v2beta1/custom_invoice_export.go index cc6a101a3b..d4cfcf0bf1 100644 --- a/internal/namespaces/billing/v2beta1/custom_invoice_export.go +++ b/internal/namespaces/billing/v2beta1/custom_invoice_export.go @@ -2,6 +2,7 @@ package billing import ( "context" + "errors" "fmt" "io" "os" @@ -122,7 +123,7 @@ func invoiceExportBuilder(command *core.Command) *core.Command { return err } if !overrideFile { - return fmt.Errorf("export file canceled") + return errors.New("export file canceled") } } diff --git a/internal/namespaces/config/commands.go b/internal/namespaces/config/commands.go index af4a40e496..d68ab87f07 100644 --- a/internal/namespaces/config/commands.go +++ b/internal/namespaces/config/commands.go @@ -3,6 +3,7 @@ package config import ( "bytes" "context" + "errors" "fmt" "os" "reflect" @@ -823,7 +824,7 @@ func validateAccessKey(profile *scw.Profile) error { if profile.AccessKey != nil { if *profile.AccessKey == "" { return &core.CliError{ - Err: fmt.Errorf("access key cannot be empty"), + Err: errors.New("access key cannot be empty"), } } @@ -838,7 +839,7 @@ func validateSecretKey(profile *scw.Profile) error { if profile.SecretKey != nil { if *profile.SecretKey == "" { return &core.CliError{ - Err: fmt.Errorf("secret key cannot be empty"), + Err: errors.New("secret key cannot be empty"), } } @@ -853,7 +854,7 @@ func validateDefaultOrganizationID(profile *scw.Profile) error { if profile.DefaultOrganizationID != nil { if *profile.DefaultOrganizationID == "" { return &core.CliError{ - Err: fmt.Errorf("default organization ID cannot be empty"), + Err: errors.New("default organization ID cannot be empty"), } } diff --git a/internal/namespaces/feedback/issue.go b/internal/namespaces/feedback/issue.go index 5992f1149a..f3c5ee845b 100644 --- a/internal/namespaces/feedback/issue.go +++ b/internal/namespaces/feedback/issue.go @@ -3,7 +3,7 @@ package feedback import ( "bytes" "context" - "fmt" + "errors" "html/template" "log" "net/url" @@ -98,7 +98,7 @@ func (i issue) openInBrowser(ctx context.Context) error { case darwin: openCmd = exec.Command("open", i.getURL()) //nolint:gosec default: - return fmt.Errorf("unsupported platform") + return errors.New("unsupported platform") } exitCode, err := core.ExecCmd(ctx, openCmd) diff --git a/internal/namespaces/function/v1beta1/custom_deploy_test.go b/internal/namespaces/function/v1beta1/custom_deploy_test.go index ba3ae2e8cd..a6eb458d21 100644 --- a/internal/namespaces/function/v1beta1/custom_deploy_test.go +++ b/internal/namespaces/function/v1beta1/custom_deploy_test.go @@ -1,6 +1,7 @@ package function_test import ( + "errors" "fmt" "os" "testing" @@ -55,7 +56,7 @@ func testDeleteFunctionNamespaceAfter(functionName string) func(*core.AfterFuncC } if namespaceID == "" { - return fmt.Errorf("namespace not found") + return errors.New("namespace not found") } return core.ExecAfterCmd(fmt.Sprintf("scw function namespace delete %s", namespaceID))(ctx) diff --git a/internal/namespaces/iam/v1alpha1/custom_rule_test.go b/internal/namespaces/iam/v1alpha1/custom_rule_test.go index a5f1ac94b7..7cf8f0b78a 100644 --- a/internal/namespaces/iam/v1alpha1/custom_rule_test.go +++ b/internal/namespaces/iam/v1alpha1/custom_rule_test.go @@ -1,7 +1,7 @@ package iam_test import ( - "fmt" + "errors" "testing" "github.com/alecthomas/assert" @@ -50,7 +50,7 @@ func Test_deleteRule(t *testing.T) { // Get first Rule ID policy := ctx.Meta["Policy"].(*iam.PolicyGetInterceptorResponse) if len(policy.Rules) != 2 { - return fmt.Errorf("expected two rules in policy") + return errors.New("expected two rules in policy") } ctx.Meta["Rule"] = policy.Rules[0] diff --git a/internal/namespaces/init/prompt.go b/internal/namespaces/init/prompt.go index 94ad6fed8f..dd67456601 100644 --- a/internal/namespaces/init/prompt.go +++ b/internal/namespaces/init/prompt.go @@ -2,6 +2,7 @@ package init import ( "context" + "errors" "fmt" "github.com/fatih/color" @@ -21,7 +22,7 @@ func promptOrganizationID(ctx context.Context) (string, error) { Prompt: "Choose your default organization ID", ValidateFunc: func(s string) error { if !validation.IsUUID(s) { - return fmt.Errorf("organization id is not a valid uuid") + return errors.New("organization id is not a valid uuid") } return nil }, @@ -146,7 +147,7 @@ func promptSecretKey(ctx context.Context) (string, error) { if validation.IsSecretKey(s) { return nil } - return fmt.Errorf("invalid secret-key") + return errors.New("invalid secret-key") }, }) if err != nil { @@ -176,7 +177,7 @@ func promptAccessKey(ctx context.Context) (string, error) { }, ValidateFunc: func(s string) error { if !validation.IsAccessKey(s) { - return fmt.Errorf("invalid access-key") + return errors.New("invalid access-key") } return nil @@ -205,7 +206,7 @@ func promptDefaultZone(ctx context.Context) (scw.Zone, error) { ValidateFunc: func(s string) error { logger.Debugf("s: %v", s) if !validation.IsZone(s) { - return fmt.Errorf("invalid zone") + return errors.New("invalid zone") } return nil }, @@ -242,7 +243,7 @@ func promptProfileOverride(ctx context.Context, config *scw.Config, configPath s return err } if !overrideConfig { - return fmt.Errorf("initialization canceled") + return errors.New("initialization canceled") } } diff --git a/internal/namespaces/instance/v1/custom_security_group.go b/internal/namespaces/instance/v1/custom_security_group.go index ec044a04fc..1f439f6cfe 100644 --- a/internal/namespaces/instance/v1/custom_security_group.go +++ b/internal/namespaces/instance/v1/custom_security_group.go @@ -2,6 +2,7 @@ package instance import ( "context" + "errors" "fmt" "reflect" "strconv" @@ -278,7 +279,7 @@ func securityGroupDeleteBuilder(c *core.Command) *core.Command { api := instance.NewAPI(core.ExtractClient(ctx)) newError := &core.CliError{ - Err: fmt.Errorf("cannot delete security-group currently in use"), + Err: errors.New("cannot delete security-group currently in use"), } // Get security-group. diff --git a/internal/namespaces/instance/v1/custom_server.go b/internal/namespaces/instance/v1/custom_server.go index 7986fe033e..dea7865a10 100644 --- a/internal/namespaces/instance/v1/custom_server.go +++ b/internal/namespaces/instance/v1/custom_server.go @@ -623,7 +623,7 @@ func serverDetachIPCommand() *core.Command { } return nil, fmt.Errorf("no public ip found") } - return nil, fmt.Errorf("no server found") + return nil, errors.New("no server found") }, Examples: []*core.Example{ { diff --git a/internal/namespaces/instance/v1/custom_server_create.go b/internal/namespaces/instance/v1/custom_server_create.go index e7a925aef1..ff85a2715d 100644 --- a/internal/namespaces/instance/v1/custom_server_create.go +++ b/internal/namespaces/instance/v1/custom_server_create.go @@ -3,6 +3,7 @@ package instance import ( "bytes" "context" + "errors" "fmt" "reflect" "strconv" @@ -572,7 +573,7 @@ func validateRootVolume(imageRequiredSize scw.Size, rootVolume *instance.VolumeS if rootVolume.ID != nil { return &core.CliError{ - Err: fmt.Errorf("you cannot use an existing volume as a root volume"), + Err: errors.New("you cannot use an existing volume as a root volume"), Details: "You must create an image of this volume and use its ID in the 'image' argument.", } } diff --git a/internal/namespaces/instance/v1/custom_server_ssh.go b/internal/namespaces/instance/v1/custom_server_ssh.go index 9eaf589b3d..6a9d66ecda 100644 --- a/internal/namespaces/instance/v1/custom_server_ssh.go +++ b/internal/namespaces/instance/v1/custom_server_ssh.go @@ -2,6 +2,7 @@ package instance import ( "context" + "errors" "fmt" "os/exec" "reflect" @@ -69,7 +70,7 @@ func instanceServerSSHRun(ctx context.Context, argsI interface{}) (i interface{} if serverResp.Server.State != instance.ServerStateRunning { return nil, &core.CliError{ - Err: fmt.Errorf("server is not running"), + Err: errors.New("server is not running"), Hint: fmt.Sprintf("Start the instance with: %s instance server start %s --wait", core.ExtractBinaryName(ctx), serverResp.Server.ID), } } diff --git a/internal/namespaces/lb/v1/custom_backend.go b/internal/namespaces/lb/v1/custom_backend.go index c986f11100..5bd33652ed 100644 --- a/internal/namespaces/lb/v1/custom_backend.go +++ b/internal/namespaces/lb/v1/custom_backend.go @@ -782,7 +782,7 @@ func interceptBackend() core.CommandInterceptor { switch detail.ArgumentName { case "Port": return nil, &core.CliError{ - Err: fmt.Errorf("missing or invalid 'health-check.port' argument"), + Err: errors.New("missing or invalid 'health-check.port' argument"), } case "CheckMaxRetries": return nil, &core.CliError{ diff --git a/internal/namespaces/mnq/v1beta1/custom_nats_helpers.go b/internal/namespaces/mnq/v1beta1/custom_nats_helpers.go index 11fd56004d..c563e8ac68 100644 --- a/internal/namespaces/mnq/v1beta1/custom_nats_helpers.go +++ b/internal/namespaces/mnq/v1beta1/custom_nats_helpers.go @@ -3,6 +3,7 @@ package mnq import ( "context" "encoding/json" + "errors" "fmt" "os" "path/filepath" @@ -76,7 +77,7 @@ func getNATSContextDir(ctx context.Context) (string, error) { if xdgConfigHome == "" { homeDir := core.ExtractEnv(ctx, "HOME") if homeDir == "" { - return "", fmt.Errorf("both XDG_CONFIG_HOME and HOME are not set") + return "", errors.New("both XDG_CONFIG_HOME and HOME are not set") } return filepath.Join(homeDir, ".config", "nats", "context"), nil } diff --git a/internal/namespaces/mnq/v1beta1/custom_nats_prompt.go b/internal/namespaces/mnq/v1beta1/custom_nats_prompt.go index 2c6cddbfe8..4ecaba4a65 100644 --- a/internal/namespaces/mnq/v1beta1/custom_nats_prompt.go +++ b/internal/namespaces/mnq/v1beta1/custom_nats_prompt.go @@ -2,6 +2,7 @@ package mnq import ( "context" + "errors" "fmt" "github.com/scaleway/scaleway-cli/v2/internal/interactive" @@ -14,7 +15,7 @@ func promptNatsAccounts(ctx context.Context, natsAccounts []*mnq.NatsAccount, to } if !interactive.IsInteractive { - return nil, fmt.Errorf("failed to create NATS context: Multiple NATS accounts found. Please provide an account ID explicitly as the command is not running in interactive mode") + return nil, errors.New("failed to create NATS context: Multiple NATS accounts found. Please provide an account ID explicitly as the command is not running in interactive mode") } if totalCount == 1 { return natsAccounts[0], nil @@ -40,7 +41,7 @@ func promptNatsAccounts(ctx context.Context, natsAccounts []*mnq.NatsAccount, to func promptOverWriteFile(ctx context.Context, filePath string) (bool, error) { if !interactive.IsInteractive { - return false, fmt.Errorf("file Exist") + return false, errors.New("file Exist") } config := interactive.PromptBoolConfig{ diff --git a/internal/namespaces/object/v1/s3configfile.go b/internal/namespaces/object/v1/s3configfile.go index 9ac5efce52..106c2258dc 100644 --- a/internal/namespaces/object/v1/s3configfile.go +++ b/internal/namespaces/object/v1/s3configfile.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "path" "text/template" @@ -85,7 +86,7 @@ func newS3Config(ctx context.Context, region scw.Region, name string) (s3config, } secretKey, secretExists := client.GetSecretKey() if !secretExists { - return s3config{}, fmt.Errorf("no secret key found") + return s3config{}, errors.New("no secret key found") } config := s3config{ AccessKey: accessKey, @@ -108,7 +109,7 @@ func (c s3config) getPath(tool s3tool) (string, error) { case mc: return path.Join(homeDir, ".mc", "config.json"), nil default: - return "", fmt.Errorf("unknown tool") + return "", errors.New("unknown tool") } } @@ -160,6 +161,6 @@ func (c s3config) getConfigFile(tool s3tool) (core.RawResult, error) { } return append(res, '\n'), nil default: - return nil, fmt.Errorf("unknown tool") + return nil, errors.New("unknown tool") } } diff --git a/internal/namespaces/rdb/v1/custom_backup.go b/internal/namespaces/rdb/v1/custom_backup.go index f2312ee666..fdb7a00b4f 100644 --- a/internal/namespaces/rdb/v1/custom_backup.go +++ b/internal/namespaces/rdb/v1/custom_backup.go @@ -2,6 +2,7 @@ package rdb import ( "context" + "errors" "fmt" "io" "net/url" @@ -321,7 +322,7 @@ func backupDownloadCommand() *core.Command { httpClient := core.ExtractHTTPClient(ctx) if backup.DownloadURL == nil { - return nil, fmt.Errorf("download URL is still nil after export") + return nil, errors.New("download URL is still nil after export") } res, err := httpClient.Get(*backup.DownloadURL) diff --git a/internal/namespaces/rdb/v1/custom_instance.go b/internal/namespaces/rdb/v1/custom_instance.go index 999a1a0ecb..731db6ba9d 100644 --- a/internal/namespaces/rdb/v1/custom_instance.go +++ b/internal/namespaces/rdb/v1/custom_instance.go @@ -686,7 +686,7 @@ func passwordFileHint(family engineFamily) string { func detectEngineFamily(instance *rdbSDK.Instance) (engineFamily, error) { if instance == nil { - return Unknown, fmt.Errorf("instance engine is nil") + return Unknown, errors.New("instance engine is nil") } if strings.HasPrefix(instance.Engine, string(PostgreSQL)) { return PostgreSQL, nil diff --git a/internal/namespaces/rdb/v1/custom_url.go b/internal/namespaces/rdb/v1/custom_url.go index 1aad838fb0..c75e88697f 100644 --- a/internal/namespaces/rdb/v1/custom_url.go +++ b/internal/namespaces/rdb/v1/custom_url.go @@ -2,6 +2,7 @@ package rdb import ( "context" + "errors" "fmt" "net/url" "reflect" @@ -104,7 +105,7 @@ func generateURL(ctx context.Context, argsI interface{}) (interface{}, error) { endpoint = privateEndpoint } if endpoint == nil { - return nil, fmt.Errorf("instance has no endpoint therefore no url can be returned") + return nil, errors.New("instance has no endpoint therefore no url can be returned") } u.Host = fmt.Sprintf("%s:%d", endpoint.IP.String(), endpoint.Port) diff --git a/internal/namespaces/rdb/v1/helper_test.go b/internal/namespaces/rdb/v1/helper_test.go index 2d6352aeff..f435545461 100644 --- a/internal/namespaces/rdb/v1/helper_test.go +++ b/internal/namespaces/rdb/v1/helper_test.go @@ -1,6 +1,7 @@ package rdb_test import ( + "errors" "fmt" "github.com/scaleway/scaleway-cli/v2/internal/core" @@ -58,7 +59,7 @@ func createPN() core.BeforeFunc { func getIPSubnet(ipNet scw.IPNet) (*string, error) { addr := ipNet.IP.To4() if addr == nil { - return nil, fmt.Errorf("could get ip 4 bytes") + return nil, errors.New("could get ip 4 bytes") } addr = addr.Mask(addr.DefaultMask()) addr[3] = +3 diff --git a/internal/namespaces/secret/v1beta1/custom_secret_version.go b/internal/namespaces/secret/v1beta1/custom_secret_version.go index 6d61556ab2..af13c103c6 100644 --- a/internal/namespaces/secret/v1beta1/custom_secret_version.go +++ b/internal/namespaces/secret/v1beta1/custom_secret_version.go @@ -3,6 +3,7 @@ package secret import ( "context" "encoding/json" + "errors" "fmt" "reflect" @@ -84,7 +85,7 @@ func getSecretVersionField(data []byte, field string) ([]byte, error) { rawField, ok := rawFields.(map[string]interface{})[field] if !ok { - return nil, fmt.Errorf("JSON field is not present") + return nil, errors.New("JSON field is not present") } switch field := rawField.(type) { diff --git a/internal/tasks/tasks_test.go b/internal/tasks/tasks_test.go index 401459138e..16cadc5646 100644 --- a/internal/tasks/tasks_test.go +++ b/internal/tasks/tasks_test.go @@ -2,6 +2,7 @@ package tasks_test import ( "context" + "errors" "fmt" "os" "runtime" @@ -45,7 +46,7 @@ func TestInvalidGeneric(t *testing.T) { ts.SetLoggerMode(tasks.PrinterModeQuiet) tasks.Add(ts, "convert int to string", func(_ *tasks.Task, args int) (nextArgs string, err error) { - return fmt.Sprintf("%d", args), nil + return strconv.Itoa(args), nil }) tasks.Add(ts, "divide by 4", func(_ *tasks.Task, args int) (nextArgs int, err error) { return args / 4, nil @@ -76,7 +77,7 @@ func TestCleanup(t *testing.T) { clean++ return nil }) - return nil, fmt.Errorf("fail") + return nil, errors.New("fail") }) _, err := ts.Execute(context.Background(), nil) @@ -125,7 +126,7 @@ func TestCleanupOnContext(t *testing.T) { select { case <-task.Ctx.Done(): - return nil, fmt.Errorf("interrupted") + return nil, errors.New("interrupted") case <-time.After(time.Second * 3): return nil, nil } From 74182b21f4bb8e114f78e51fcce3dccae990f612 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20L=C3=A9one?= Date: Thu, 22 Aug 2024 14:44:59 +0200 Subject: [PATCH 2/2] chore: add support for perfsprint --- .golangci.yml | 5 ++++- internal/args/errors.go | 2 +- internal/args/unmarshal.go | 5 +++-- internal/core/cobra_usage_builder.go | 2 +- internal/core/cobra_utils.go | 10 +++++----- internal/core/cobra_utils_test.go | 5 ++--- internal/core/command.go | 4 ++-- internal/core/printer.go | 6 +++--- internal/core/validate_test.go | 6 +++--- internal/core/web.go | 2 +- internal/interactive/list.go | 5 +++-- internal/interactive/test.go | 3 +-- internal/interactive/utils.go | 4 ++-- .../applesilicon/v1alpha1/custom_server_ssh.go | 3 ++- .../namespaces/autocomplete/autocomplete.go | 6 +++--- internal/namespaces/autocomplete/errors.go | 3 ++- .../namespaces/baremetal/v1/custom_server.go | 3 ++- .../baremetal/v1/custom_server_fip.go | 4 ++-- .../billing/v2beta1/custom_invoice_download.go | 6 +++--- .../billing/v2beta1/custom_invoice_export.go | 4 ++-- .../cockpit/v1beta1/custom_cockpit.go | 2 +- internal/namespaces/config/commands.go | 12 ++++++------ internal/namespaces/config/commands_test.go | 3 +-- .../container/v1beta1/custom_deploy.go | 2 +- .../container/v1beta1/custom_deploy_test.go | 2 +- .../domain/v2beta1/custom_record_set.go | 3 ++- .../function/v1beta1/custom_deploy.go | 3 ++- .../function/v1beta1/custom_deploy_test.go | 2 +- internal/namespaces/iam/v1alpha1/error.go | 3 ++- internal/namespaces/init/prompt.go | 2 +- .../namespaces/instance/v1/custom_server.go | 2 +- .../instance/v1/custom_server_action.go | 2 +- .../instance/v1/custom_server_console.go | 3 ++- .../instance/v1/custom_server_rdp.go | 2 +- .../instance/v1/custom_server_rdp_test.go | 5 +++-- .../instance/v1/custom_server_ssh.go | 7 ++++--- .../namespaces/instance/v1/custom_ssh_key.go | 3 ++- .../namespaces/instance/v1/custom_volume.go | 4 ++-- internal/namespaces/k8s/v1/custom_cluster.go | 2 +- internal/namespaces/k8s/v1/helpers_test.go | 4 ++-- internal/namespaces/lb/v1/custom_backend.go | 18 +++++++++--------- .../namespaces/lb/v1/custom_certificate.go | 3 ++- .../namespaces/lb/v1/custom_private_network.go | 4 ++-- internal/namespaces/lb/v1/helper_test.go | 4 ++-- .../mnq/v1beta1/custom_nats_prompt.go | 2 +- .../namespaces/object/v1/custom_bucket_test.go | 10 +++++----- .../object/v1/custom_config_install.go | 6 +++--- internal/namespaces/object/v1/s3configfile.go | 3 +-- internal/namespaces/rdb/v1/custom_acl.go | 4 ++-- internal/namespaces/rdb/v1/custom_endpoint.go | 3 ++- internal/namespaces/rdb/v1/custom_instance.go | 5 +++-- internal/namespaces/rdb/v1/custom_url_test.go | 6 +++--- .../registry/v1/custom_docker_helper.go | 9 +++++---- .../registry/v1/custom_image_test.go | 4 ++-- .../namespaces/registry/v1/custom_login.go | 4 ++-- .../secret/v1beta1/custom_secret_version.go | 5 ++--- internal/platform/terminal/terminal_client.go | 10 +++++----- internal/sshconfig/bastion_host.go | 2 +- internal/sshconfig/sshconfig.go | 2 +- internal/tabwriter/tabwriter_test.go | 5 +++-- internal/tasks/tasks_test.go | 3 +-- 61 files changed, 141 insertions(+), 127 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index b6a3e6310d..55c68fbabc 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -41,6 +41,7 @@ linters: - musttag # enforce field tags in (un)marshaled structs [fast: false, auto-fix: false] - nakedret # Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false] - nolintlint # Reports ill-formed or insufficient nolint directives [fast: true, auto-fix: false] + - perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative. [fast: false, auto-fix: false] - prealloc # Finds slice declarations that could potentially be pre-allocated [fast: true, auto-fix: false] - predeclared # find code that shadows one of Go's predeclared identifiers [fast: true, auto-fix: false] - promlinter # Check Prometheus metrics naming via promlint [fast: true, auto-fix: false] @@ -62,7 +63,6 @@ linters: - wastedassign # wastedassign finds wasted assignment statements. [fast: false, auto-fix: false] - whitespace # Tool for detection of leading and trailing whitespace [fast: true, auto-fix: true] - zerologlint # Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg` [fast: false, auto-fix: false] - - perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative. [fast: false, auto-fix: false] disable: - cyclop # checks function and package cyclomatic complexity [fast: false, auto-fix: false] @@ -99,6 +99,9 @@ issues: exclude-dirs: - internal/pkg + max-issues-per-linter: 0 + max-same-issues: 0 + exclude-rules: - path: _test\.go linters: diff --git a/internal/args/errors.go b/internal/args/errors.go index a9f12c8479..446e0b33b0 100644 --- a/internal/args/errors.go +++ b/internal/args/errors.go @@ -188,7 +188,7 @@ type CannotParseDateError struct { } func (e *CannotParseDateError) Error() string { - return fmt.Sprintf(`date parsing error: could not parse %s`, e.ArgValue) + return "date parsing error: could not parse " + e.ArgValue } type CannotParseBoolError struct { diff --git a/internal/args/unmarshal.go b/internal/args/unmarshal.go index bc2594b939..3b742dc980 100644 --- a/internal/args/unmarshal.go +++ b/internal/args/unmarshal.go @@ -5,6 +5,7 @@ package args // into CLI arguments represented as Go data. import ( + "errors" "fmt" "io" "net" @@ -32,7 +33,7 @@ var unmarshalFuncs = map[reflect.Type]UnmarshalFunc{ // Only support G, GB for now (case insensitive). value = strings.ToLower(value) if !strings.HasSuffix(value, "g") && !strings.HasSuffix(value, "gb") { - return fmt.Errorf("size must be defined using the G or GB unit") + return errors.New("size must be defined using the G or GB unit") } bytes, err := humanize.ParseBytes(value) @@ -70,7 +71,7 @@ var unmarshalFuncs = map[reflect.Type]UnmarshalFunc{ } if len(value) == 0 { - return fmt.Errorf("empty time given") + return errors.New("empty time given") } // Handle relative time diff --git a/internal/core/cobra_usage_builder.go b/internal/core/cobra_usage_builder.go index a49892681c..7fbcc3d552 100644 --- a/internal/core/cobra_usage_builder.go +++ b/internal/core/cobra_usage_builder.go @@ -126,7 +126,7 @@ func buildExamples(binaryName string, cmd *Command) string { for _, cmdExample := range cmd.Examples { // Build title. - title := fmt.Sprintf(" %s", cmdExample.Short) + title := " " + cmdExample.Short commandLine := cmdExample.GetCommandLine(binaryName, cmd) commandLine = interactive.Indent(commandLine, 4) diff --git a/internal/core/cobra_utils.go b/internal/core/cobra_utils.go index cb63e9aff9..be7a03efde 100644 --- a/internal/core/cobra_utils.go +++ b/internal/core/cobra_utils.go @@ -59,7 +59,7 @@ func cobraRun(ctx context.Context, cmd *Command) func(*cobra.Command, []string) if exist { otherArgs := rawArgs.Remove(positionalArgSpec.Name) return &CliError{ - Err: fmt.Errorf("a positional argument is required for this command"), + Err: errors.New("a positional argument is required for this command"), Hint: positionalArgHint(meta.BinaryName, cmd, value, otherArgs, len(positionalArgs) > 0), } } @@ -67,7 +67,7 @@ func cobraRun(ctx context.Context, cmd *Command) func(*cobra.Command, []string) // If no positional arguments were provided, return an error if len(positionalArgs) == 0 { return &CliError{ - Err: fmt.Errorf("a positional argument is required for this command"), + Err: errors.New("a positional argument is required for this command"), Hint: positionalArgHint(meta.BinaryName, cmd, "<"+positionalArgSpec.Name+">", rawArgs, false), } } @@ -209,7 +209,7 @@ func handleUnmarshalErrors(cmd *Command, unmarshalErr *args.UnmarshalArgError) e switch e.Err.(type) { case *args.CannotParseBoolError: return &CliError{ - Err: fmt.Errorf(""), + Err: errors.New(""), Message: fmt.Sprintf("invalid value for '%s' argument: invalid boolean value", unmarshalErr.ArgName), Hint: "Possible values: true, false", } @@ -237,7 +237,7 @@ Relative time error: %s return &CliError{ Err: fmt.Errorf("invalid argument '%s': %s", unmarshalErr.ArgName, e.Error()), - Hint: fmt.Sprintf("Valid arguments are: %s", strings.Join(argNames, ", ")), + Hint: "Valid arguments are: " + strings.Join(argNames, ", "), } case *args.UnknownArgError: argNames := []string(nil) @@ -248,7 +248,7 @@ Relative time error: %s return &CliError{ Err: fmt.Errorf("unknown argument '%s'", unmarshalErr.ArgName), - Hint: fmt.Sprintf("Valid arguments are: %s", strings.Join(argNames, ", ")), + Hint: "Valid arguments are: " + strings.Join(argNames, ", "), } default: diff --git a/internal/core/cobra_utils_test.go b/internal/core/cobra_utils_test.go index 609b55c70f..806b2cd708 100644 --- a/internal/core/cobra_utils_test.go +++ b/internal/core/cobra_utils_test.go @@ -3,7 +3,6 @@ package core_test import ( "context" "errors" - "fmt" "reflect" "testing" "time" @@ -190,7 +189,7 @@ func Test_PositionalArg(t *testing.T) { Check: core.TestCheckCombine( core.TestCheckExitCode(1), core.TestCheckError(&core.CliError{ - Err: fmt.Errorf("a positional argument is required for this command"), + Err: errors.New("a positional argument is required for this command"), Hint: "Try running: scw test positional tag=world", }), ), @@ -312,7 +311,7 @@ func Test_MultiPositionalArg(t *testing.T) { Check: core.TestCheckCombine( core.TestCheckExitCode(1), core.TestCheckError(&core.CliError{ - Err: fmt.Errorf("a positional argument is required for this command"), + Err: errors.New("a positional argument is required for this command"), Hint: "Try running: scw test multi-positional tag=tag1", }), ), diff --git a/internal/core/command.go b/internal/core/command.go index 1d73c728e7..90b2b76404 100644 --- a/internal/core/command.go +++ b/internal/core/command.go @@ -162,8 +162,8 @@ func (c *Command) seeAlsosAsStr() string { seeAlsos := make([]string, 0, len(c.SeeAlsos)) for _, cmdSeeAlso := range c.SeeAlsos { - short := fmt.Sprintf(" # %s", cmdSeeAlso.Short) - commandStr := fmt.Sprintf(" %s", cmdSeeAlso.Command) + short := " # " + cmdSeeAlso.Short + commandStr := " " + cmdSeeAlso.Command seeAlsoLines := []string{ short, diff --git a/internal/core/printer.go b/internal/core/printer.go index ee62b3aaaf..38840f49bc 100644 --- a/internal/core/printer.go +++ b/internal/core/printer.go @@ -186,7 +186,7 @@ func (p *Printer) printHuman(data interface{}, opt *human.MarshalOpt) error { } if len(p.humanFields) > 0 && reflect.TypeOf(data).Kind() != reflect.Slice { - return p.printHuman(fmt.Errorf("list of fields for human output is only supported for commands that return a list"), nil) + return p.printHuman(errors.New("list of fields for human output is only supported for commands that return a list"), nil) } if len(p.humanFields) > 0 { @@ -204,7 +204,7 @@ func (p *Printer) printHuman(data interface{}, opt *human.MarshalOpt) error { case *human.UnknownFieldError: return p.printHuman(&CliError{ Err: fmt.Errorf("unknown field '%s' in output options", e.FieldName), - Hint: fmt.Sprintf("Valid fields are: %s", strings.Join(e.ValidFields, ", ")), + Hint: "Valid fields are: " + strings.Join(e.ValidFields, ", "), }, nil) case nil: // Do nothing @@ -300,7 +300,7 @@ func (p *Printer) printTemplate(data interface{}) error { return p.printHuman(&CliError{ Err: err, Message: "templating error", - Hint: fmt.Sprintf("Acceptable values are:\n - %s", strings.Join(gofields.ListFields(elemValue.Type()), "\n - ")), + Hint: "Acceptable values are:\n - " + strings.Join(gofields.ListFields(elemValue.Type()), "\n - "), }, nil) } _, err = writer.Write([]byte{'\n'}) diff --git a/internal/core/validate_test.go b/internal/core/validate_test.go index 5b9c2c5ec2..5e414933c2 100644 --- a/internal/core/validate_test.go +++ b/internal/core/validate_test.go @@ -126,7 +126,7 @@ func Test_DefaultCommandValidateFunc(t *testing.T) { { Name: "elements-slice.{index}.elements-slice.{index}.name", ValidateFunc: func(_ *core.ArgSpec, _ interface{}) error { - return fmt.Errorf("arg validation called") + return errors.New("arg validation called") }, }, }, @@ -156,7 +156,7 @@ func Test_DefaultCommandValidateFunc(t *testing.T) { { Name: "short", ValidateFunc: func(_ *core.ArgSpec, _ interface{}) error { - return fmt.Errorf("arg validation called") + return errors.New("arg validation called") }, }, }, @@ -836,7 +836,7 @@ func Test_ValidateOneOf(t *testing.T) { Cmd: "scw oneof a=yo c=no", Check: core.TestCheckCombine( core.TestCheckExitCode(1), - core.TestCheckError(fmt.Errorf("arguments 'a' and 'c' are mutually exclusive")), + core.TestCheckError(errors.New("arguments 'a' and 'c' are mutually exclusive")), ), })(t) }) diff --git a/internal/core/web.go b/internal/core/web.go index 817d37695f..48a420ecb6 100644 --- a/internal/core/web.go +++ b/internal/core/web.go @@ -33,7 +33,7 @@ func runWeb(cmd *Command, respI interface{}) (interface{}, error) { return nil, &CliError{ Err: err, Message: "Failed to open web url", - Details: fmt.Sprintf("You can open it: %s", url), + Details: "You can open it: " + url, Hint: "You may not have a default browser configured", Code: 1, } diff --git a/internal/interactive/list.go b/internal/interactive/list.go index 96cd1facab..65d60a8e2e 100644 --- a/internal/interactive/list.go +++ b/internal/interactive/list.go @@ -5,6 +5,7 @@ package interactive import ( "bytes" "context" + "errors" "fmt" "os" @@ -57,7 +58,7 @@ func (m *ListPrompt) View() string { if m.cursor == i { s += fmt.Sprintf("> %s\n", choice) } else { - s += fmt.Sprintf("%s\n", choice) + s += choice + "\n" } } @@ -89,7 +90,7 @@ func (m *ListPrompt) Execute(ctx context.Context) (int, error) { } if m.cancelled { - return -1, fmt.Errorf("prompt cancelled") + return -1, errors.New("prompt cancelled") } return m.cursor, nil diff --git a/internal/interactive/test.go b/internal/interactive/test.go index 8c78110dfd..bd68c9fd71 100644 --- a/internal/interactive/test.go +++ b/internal/interactive/test.go @@ -2,7 +2,6 @@ package interactive import ( "context" - "fmt" "io" ) @@ -45,7 +44,7 @@ type mockResponseReader struct { func (m *mockResponseReader) Read(p []byte) (n int, err error) { if m.ctx != nil { if mockResponse, exist := popMockResponseFromContext(m.ctx); exist { - buff := []byte(fmt.Sprintf("%s\n", mockResponse)) + buff := []byte(mockResponse + "\n") copy(p, buff) return len(buff), nil } diff --git a/internal/interactive/utils.go b/internal/interactive/utils.go index a4b46dbbc0..bb960f7ec9 100644 --- a/internal/interactive/utils.go +++ b/internal/interactive/utils.go @@ -3,7 +3,7 @@ package interactive import ( - "fmt" + "errors" "io" "os" @@ -44,7 +44,7 @@ func isInteractive() bool { func ValidateOrganizationID() ValidateFunc { return func(s string) error { if !validation.IsOrganizationID(s) { - return fmt.Errorf("invalid organization-id") + return errors.New("invalid organization-id") } return nil } diff --git a/internal/namespaces/applesilicon/v1alpha1/custom_server_ssh.go b/internal/namespaces/applesilicon/v1alpha1/custom_server_ssh.go index 543dadb57a..649821d429 100644 --- a/internal/namespaces/applesilicon/v1alpha1/custom_server_ssh.go +++ b/internal/namespaces/applesilicon/v1alpha1/custom_server_ssh.go @@ -6,6 +6,7 @@ import ( "fmt" "os/exec" "reflect" + "strconv" "github.com/scaleway/scaleway-cli/v2/internal/core" applesilicon "github.com/scaleway/scaleway-sdk-go/api/applesilicon/v1alpha1" @@ -78,7 +79,7 @@ func serverSSHRun(ctx context.Context, argsI interface{}) (i interface{}, e erro sshArgs := []string{ serverResp.IP.String(), - "-p", fmt.Sprintf("%d", args.Port), + "-p", strconv.FormatUint(uint64(args.Port), 10), "-l", args.Username, "-t", } diff --git a/internal/namespaces/autocomplete/autocomplete.go b/internal/namespaces/autocomplete/autocomplete.go index 6226013d0a..78a484581d 100644 --- a/internal/namespaces/autocomplete/autocomplete.go +++ b/internal/namespaces/autocomplete/autocomplete.go @@ -278,7 +278,7 @@ func autocompleteCompleteBashCommand() *core.Command { } words := rawArgs[2:] if len(words) <= wordIndex { - return nil, fmt.Errorf("index to complete is invalid") + return nil, errors.New("index to complete is invalid") } aliases := core.ExtractAliases(ctx) @@ -317,7 +317,7 @@ func autocompleteCompleteFishCommand() *core.Command { Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) { rawArgs := *argsI.(*args.RawArgs) if len(rawArgs) < 4 { - return nil, fmt.Errorf("not enough arguments") + return nil, errors.New("not enough arguments") } aliases := core.ExtractAliases(ctx) @@ -366,7 +366,7 @@ func autocompleteCompleteZshCommand() *core.Command { wordIndex-- // In zsh word index starts at 1. if wordIndex <= 0 { - return nil, fmt.Errorf("index cannot be 1 (0) or lower") + return nil, errors.New("index cannot be 1 (0) or lower") } // Other args are all the words. diff --git a/internal/namespaces/autocomplete/errors.go b/internal/namespaces/autocomplete/errors.go index e23c83b143..14b26e6c36 100644 --- a/internal/namespaces/autocomplete/errors.go +++ b/internal/namespaces/autocomplete/errors.go @@ -1,6 +1,7 @@ package autocomplete import ( + "errors" "fmt" "github.com/scaleway/scaleway-cli/v2/internal/core" @@ -20,7 +21,7 @@ func unsupportedOsError(OS string) *core.CliError { func installationCancelledError(shellName string, script string) *core.CliError { return &core.CliError{ - Err: fmt.Errorf("installation cancelled"), + Err: errors.New("installation cancelled"), Hint: fmt.Sprintf("To manually enable autocomplete for %v, run: %v", shellName, script), } } diff --git a/internal/namespaces/baremetal/v1/custom_server.go b/internal/namespaces/baremetal/v1/custom_server.go index 3d3b9ba7a6..63b210d6ad 100644 --- a/internal/namespaces/baremetal/v1/custom_server.go +++ b/internal/namespaces/baremetal/v1/custom_server.go @@ -2,6 +2,7 @@ package baremetal import ( "context" + "errors" "fmt" "reflect" "time" @@ -55,7 +56,7 @@ func serverWaitCommand() *core.Command { } if server.Status != baremetal.ServerStatusReady { return nil, &core.CliError{ - Err: fmt.Errorf("server did not reach a stable delivery status"), + Err: errors.New("server did not reach a stable delivery status"), Details: fmt.Sprintf("server %s is in %s status", server.ID, server.Status), } } diff --git a/internal/namespaces/baremetal/v1/custom_server_fip.go b/internal/namespaces/baremetal/v1/custom_server_fip.go index 9b777e42c1..44fc68bff8 100644 --- a/internal/namespaces/baremetal/v1/custom_server_fip.go +++ b/internal/namespaces/baremetal/v1/custom_server_fip.go @@ -2,7 +2,7 @@ package baremetal import ( "context" - "fmt" + "errors" "reflect" "github.com/scaleway/scaleway-cli/v2/internal/core" @@ -56,7 +56,7 @@ func serverAddFlexibleIP() *core.Command { return nil } return &core.CliError{ - Err: fmt.Errorf("error looks like the IP type isn't correct"), + Err: errors.New("error looks like the IP type isn't correct"), Hint: "Two type available : IPv6 or IPv4", } }, diff --git a/internal/namespaces/billing/v2beta1/custom_invoice_download.go b/internal/namespaces/billing/v2beta1/custom_invoice_download.go index 477b363f4d..7c9557a70e 100644 --- a/internal/namespaces/billing/v2beta1/custom_invoice_download.go +++ b/internal/namespaces/billing/v2beta1/custom_invoice_download.go @@ -77,7 +77,7 @@ func invoiceDownloadBuilder(command *core.Command) *core.Command { date, err := trimDateFromFileName(resp.Name) if err != nil { - return fmt.Errorf("parse date on file name") + return errors.New("parse date on file name") } dir, file := getDirFile(args.FilePath) @@ -140,7 +140,7 @@ func invoiceDownloadBuilder(command *core.Command) *core.Command { func addDownloadExt(fileName, contentType string) string { switch contentType { case "application/pdf": - fileName = fmt.Sprintf("%s.pdf", fileName) + fileName += ".pdf" } return fileName @@ -178,7 +178,7 @@ func billingDownloadRun(ctx context.Context, argsI interface{}) (interface{}, er // case when filepath is a directory: join default name with custom path date, err := trimDateFromFileName(resp.Name) if err != nil { - return nil, fmt.Errorf("parse date on file name") + return nil, errors.New("parse date on file name") } defaultFileName := fmt.Sprintf("%s-%s-%s", invoiceDefaultPrefix, date, argsDownload.InvoiceID) diff --git a/internal/namespaces/billing/v2beta1/custom_invoice_export.go b/internal/namespaces/billing/v2beta1/custom_invoice_export.go index d4cfcf0bf1..ccb3378e40 100644 --- a/internal/namespaces/billing/v2beta1/custom_invoice_export.go +++ b/internal/namespaces/billing/v2beta1/custom_invoice_export.go @@ -81,7 +81,7 @@ func invoiceExportBuilder(command *core.Command) *core.Command { if len(file) > 0 { fileExtension := filepath.Ext(file) if extensionOnFile := checkExportInvoiceExt(fileExtension); !extensionOnFile { - return fmt.Errorf("file has not supported extension") + return errors.New("file has not supported extension") } } @@ -186,7 +186,7 @@ func billingExportRun(ctx context.Context, argsI interface{}) (interface{}, erro func addExportExt(fileName, contentType string) string { switch contentType { case "text/csv": - fileName = fmt.Sprintf("%s.csv", fileName) + fileName += ".csv" } return fileName diff --git a/internal/namespaces/cockpit/v1beta1/custom_cockpit.go b/internal/namespaces/cockpit/v1beta1/custom_cockpit.go index 3128103970..2a0579fa34 100644 --- a/internal/namespaces/cockpit/v1beta1/custom_cockpit.go +++ b/internal/namespaces/cockpit/v1beta1/custom_cockpit.go @@ -58,7 +58,7 @@ func cockpitWaitCommand() *core.Command { if targetCockpit.Status != cockpit.CockpitStatusReady { return nil, &core.CliError{ - Err: fmt.Errorf("cockpit did not reach a stable delivery status"), + Err: errors.New("cockpit did not reach a stable delivery status"), Details: fmt.Sprintf("cockpit %s is in %s status", targetCockpit.ProjectID, targetCockpit.Status), } } diff --git a/internal/namespaces/config/commands.go b/internal/namespaces/config/commands.go index d68ab87f07..b95f7f3101 100644 --- a/internal/namespaces/config/commands.go +++ b/internal/namespaces/config/commands.go @@ -358,7 +358,7 @@ func configUnsetCommand() *core.Command { } return &core.SuccessResult{ - Message: fmt.Sprintf("successfully unset %s", key), + Message: "successfully unset " + key, }, nil }, } @@ -441,7 +441,7 @@ func configDeleteProfileCommand() *core.Command { } return &core.SuccessResult{ - Message: fmt.Sprintf("successfully delete profile %s", profileName), + Message: "successfully delete profile " + profileName, }, nil }, } @@ -492,7 +492,7 @@ func configActivateProfileCommand() *core.Command { } return &core.SuccessResult{ - Message: fmt.Sprintf("successfully activate profile %s", profileName), + Message: "successfully activate profile " + profileName, }, nil }, } @@ -869,7 +869,7 @@ func validateDefaultProjectID(profile *scw.Profile) error { if profile.DefaultProjectID != nil { if *profile.DefaultProjectID == "" { return &core.CliError{ - Err: fmt.Errorf("default project ID cannot be empty"), + Err: errors.New("default project ID cannot be empty"), } } @@ -884,7 +884,7 @@ func validateDefaultRegion(profile *scw.Profile) error { if profile.DefaultRegion != nil { if *profile.DefaultRegion == "" { return &core.CliError{ - Err: fmt.Errorf("default region cannot be empty"), + Err: errors.New("default region cannot be empty"), } } @@ -899,7 +899,7 @@ func validateDefaultZone(profile *scw.Profile) error { if profile.DefaultZone != nil { if *profile.DefaultZone == "" { return &core.CliError{ - Err: fmt.Errorf("default zone cannot be empty"), + Err: errors.New("default zone cannot be empty"), } } diff --git a/internal/namespaces/config/commands_test.go b/internal/namespaces/config/commands_test.go index ab6c4e2571..9a8a6da1a1 100644 --- a/internal/namespaces/config/commands_test.go +++ b/internal/namespaces/config/commands_test.go @@ -1,7 +1,6 @@ package config_test import ( - "fmt" "os" "path" "regexp" @@ -316,7 +315,7 @@ func Test_ConfigImportCommand(t *testing.T) { core.Test(&core.TestConfig{ Commands: config.GetCommands(), BeforeFunc: beforeFuncCreateFullConfig(), - Cmd: fmt.Sprintf("scw config import %s", tmpFile.Name()), + Cmd: "scw config import " + tmpFile.Name(), Check: core.TestCheckCombine( core.TestCheckExitCode(0), core.TestCheckGolden(), diff --git a/internal/namespaces/container/v1beta1/custom_deploy.go b/internal/namespaces/container/v1beta1/custom_deploy.go index fe679c3a5c..828443f44e 100644 --- a/internal/namespaces/container/v1beta1/custom_deploy.go +++ b/internal/namespaces/container/v1beta1/custom_deploy.go @@ -118,7 +118,7 @@ func containerDeployRun(ctx context.Context, argsI interface{}) (i interface{}, if args.Name == "" { args.Name = filepath.Base(args.BuildSource) if args.Name == "." { - return nil, fmt.Errorf("unable to determine application name, please specify it with name=") + return nil, errors.New("unable to determine application name, please specify it with name=") } args.Name = "app-" + args.Name diff --git a/internal/namespaces/container/v1beta1/custom_deploy_test.go b/internal/namespaces/container/v1beta1/custom_deploy_test.go index 7208c9e170..53ba04bfef 100644 --- a/internal/namespaces/container/v1beta1/custom_deploy_test.go +++ b/internal/namespaces/container/v1beta1/custom_deploy_test.go @@ -194,6 +194,6 @@ func testDeleteRegistryAfter(appName string) func(*core.AfterFuncCtx) error { return nil } - return core.ExecAfterCmd(fmt.Sprintf("scw registry namespace delete %s", registryID))(ctx) + return core.ExecAfterCmd("scw registry namespace delete " + registryID)(ctx) } } diff --git a/internal/namespaces/domain/v2beta1/custom_record_set.go b/internal/namespaces/domain/v2beta1/custom_record_set.go index e095840619..4e3b7ab623 100644 --- a/internal/namespaces/domain/v2beta1/custom_record_set.go +++ b/internal/namespaces/domain/v2beta1/custom_record_set.go @@ -2,6 +2,7 @@ package domain import ( "context" + "errors" "fmt" "reflect" @@ -181,7 +182,7 @@ func dnsRecordSetRun(ctx context.Context, argsI interface{}) (i interface{}, e e } if len(request.Values) == 0 { - return nil, fmt.Errorf("at least one values (eg: values.0) is required") + return nil, errors.New("at least one values (eg: values.0) is required") } for _, data := range request.Values { diff --git a/internal/namespaces/function/v1beta1/custom_deploy.go b/internal/namespaces/function/v1beta1/custom_deploy.go index 4229ef5f78..e816b7584f 100644 --- a/internal/namespaces/function/v1beta1/custom_deploy.go +++ b/internal/namespaces/function/v1beta1/custom_deploy.go @@ -4,6 +4,7 @@ package function import ( "context" + "errors" "fmt" "net/http" "os" @@ -70,7 +71,7 @@ func functionDeploy() *core.Command { } if zipFileStat.Size() < 0 { - return nil, fmt.Errorf("invalid zip-file, invalid size") + return nil, errors.New("invalid zip-file, invalid size") } ts := tasks.Begin() diff --git a/internal/namespaces/function/v1beta1/custom_deploy_test.go b/internal/namespaces/function/v1beta1/custom_deploy_test.go index a6eb458d21..3d4f555c90 100644 --- a/internal/namespaces/function/v1beta1/custom_deploy_test.go +++ b/internal/namespaces/function/v1beta1/custom_deploy_test.go @@ -59,6 +59,6 @@ func testDeleteFunctionNamespaceAfter(functionName string) func(*core.AfterFuncC return errors.New("namespace not found") } - return core.ExecAfterCmd(fmt.Sprintf("scw function namespace delete %s", namespaceID))(ctx) + return core.ExecAfterCmd("scw function namespace delete " + namespaceID)(ctx) } } diff --git a/internal/namespaces/iam/v1alpha1/error.go b/internal/namespaces/iam/v1alpha1/error.go index 2455f8c491..06276756f6 100644 --- a/internal/namespaces/iam/v1alpha1/error.go +++ b/internal/namespaces/iam/v1alpha1/error.go @@ -1,6 +1,7 @@ package iam import ( + "errors" "fmt" "github.com/scaleway/scaleway-cli/v2/internal/core" @@ -8,7 +9,7 @@ import ( func installationCanceled(addKeyInstructions string) *core.CliError { return &core.CliError{ - Err: fmt.Errorf("installation of SSH key canceled"), + Err: errors.New("installation of SSH key canceled"), Hint: "You can add it later using " + addKeyInstructions, } } diff --git a/internal/namespaces/init/prompt.go b/internal/namespaces/init/prompt.go index dd67456601..9bcf7c96f1 100644 --- a/internal/namespaces/init/prompt.go +++ b/internal/namespaces/init/prompt.go @@ -38,7 +38,7 @@ func promptManualProjectID(ctx context.Context, defaultProjectID string) (string DefaultValueDoc: defaultProjectID, ValidateFunc: func(s string) error { if !validation.IsProjectID(s) { - return fmt.Errorf("organization id is not a valid uuid") + return errors.New("organization id is not a valid uuid") } return nil }, diff --git a/internal/namespaces/instance/v1/custom_server.go b/internal/namespaces/instance/v1/custom_server.go index dea7865a10..a109c427c5 100644 --- a/internal/namespaces/instance/v1/custom_server.go +++ b/internal/namespaces/instance/v1/custom_server.go @@ -621,7 +621,7 @@ func serverDetachIPCommand() *core.Command { } return api.GetServer(&instance.GetServerRequest{ServerID: args.ServerID}) } - return nil, fmt.Errorf("no public ip found") + return nil, errors.New("no public ip found") } return nil, errors.New("no server found") }, diff --git a/internal/namespaces/instance/v1/custom_server_action.go b/internal/namespaces/instance/v1/custom_server_action.go index e9e495317c..8619fe4139 100644 --- a/internal/namespaces/instance/v1/custom_server_action.go +++ b/internal/namespaces/instance/v1/custom_server_action.go @@ -190,7 +190,7 @@ Once your image is ready you will be able to create a new server based on this i tmp := strings.Split(res.Task.HrefResult, "/") if len(tmp) != 3 { - return nil, fmt.Errorf("cannot extract image id from task") + return nil, errors.New("cannot extract image id from task") } return api.GetImage(&instance.GetImageRequest{Zone: args.Zone, ImageID: tmp[2]}) }, diff --git a/internal/namespaces/instance/v1/custom_server_console.go b/internal/namespaces/instance/v1/custom_server_console.go index 356a811fa8..98d505d9eb 100644 --- a/internal/namespaces/instance/v1/custom_server_console.go +++ b/internal/namespaces/instance/v1/custom_server_console.go @@ -4,6 +4,7 @@ package instance import ( "context" + "errors" "fmt" "reflect" @@ -57,7 +58,7 @@ func instanceServerConsoleRun(ctx context.Context, argsI interface{}) (i interfa secretKey, ok := client.GetSecretKey() if !ok { - return nil, fmt.Errorf("could not get secret key") + return nil, errors.New("could not get secret key") } ttyClient, err := gotty.NewClient(server.Zone, server.ID, secretKey) diff --git a/internal/namespaces/instance/v1/custom_server_rdp.go b/internal/namespaces/instance/v1/custom_server_rdp.go index 407e48ce16..4b80b454e2 100644 --- a/internal/namespaces/instance/v1/custom_server_rdp.go +++ b/internal/namespaces/instance/v1/custom_server_rdp.go @@ -113,7 +113,7 @@ func instanceServerGetRdpPasswordRun(ctx context.Context, argsI interface{}) (i } if resp.Server.AdminPasswordEncryptedValue == nil || *resp.Server.AdminPasswordEncryptedValue == "" { return &core.CliError{ - Err: fmt.Errorf("rdp password is empty"), + Err: errors.New("rdp password is empty"), Message: "RDP password is nil or empty in api response", Details: "Your server have no RDP password available", Hint: "You may need to wait for your OS to start before having a generated RDP password, it can take more than 10 minutes.\nUse -w, --wait to wait for password to be available", diff --git a/internal/namespaces/instance/v1/custom_server_rdp_test.go b/internal/namespaces/instance/v1/custom_server_rdp_test.go index 69450b1a98..2cf0c39e7b 100644 --- a/internal/namespaces/instance/v1/custom_server_rdp_test.go +++ b/internal/namespaces/instance/v1/custom_server_rdp_test.go @@ -4,6 +4,7 @@ import ( "crypto/rand" "crypto/rsa" "encoding/pem" + "errors" "fmt" "os" "path/filepath" @@ -41,7 +42,7 @@ func loadRSASSHKey(path string) (*rsa.PrivateKey, error) { return nil, fmt.Errorf("failed to save test key: %w", err) } } else if len(pemContent) == 0 { - return nil, fmt.Errorf("empty test key, should be updated with cassettes") + return nil, errors.New("empty test key, should be updated with cassettes") } key, err := ssh.ParseRawPrivateKey(pemContent) @@ -93,7 +94,7 @@ func generateRSASSHKey(metaKey string) func(beforeFunc *core.BeforeFuncCtx) erro api := iam.NewAPI(ctx.Client) projectID, exists := ctx.Client.GetDefaultProjectID() if !exists { - return fmt.Errorf("missing project id") + return errors.New("missing project id") } key, err := api.CreateSSHKey(&iam.CreateSSHKeyRequest{ Name: "test-cli-instance-server-get-rdp-password", diff --git a/internal/namespaces/instance/v1/custom_server_ssh.go b/internal/namespaces/instance/v1/custom_server_ssh.go index 6a9d66ecda..f3d6ba6594 100644 --- a/internal/namespaces/instance/v1/custom_server_ssh.go +++ b/internal/namespaces/instance/v1/custom_server_ssh.go @@ -6,6 +6,7 @@ import ( "fmt" "os/exec" "reflect" + "strconv" "github.com/scaleway/scaleway-cli/v2/internal/core" "github.com/scaleway/scaleway-sdk-go/api/instance/v1" @@ -16,7 +17,7 @@ type instanceSSHServerRequest struct { Zone scw.Zone ServerID string Username string - Port uint + Port uint64 Command string } @@ -77,14 +78,14 @@ func instanceServerSSHRun(ctx context.Context, argsI interface{}) (i interface{} if serverResp.Server.PublicIP == nil { return nil, &core.CliError{ - Err: fmt.Errorf("server does not have a public IP to connect to"), + Err: errors.New("server does not have a public IP to connect to"), Hint: fmt.Sprintf("Add a public IP to the instance with: %s instance server update %s ip=", core.ExtractBinaryName(ctx), serverResp.Server.ID), } } sshArgs := []string{ serverResp.Server.PublicIP.Address.String(), - "-p", fmt.Sprintf("%d", args.Port), + "-p", strconv.FormatUint(args.Port, 10), "-l", args.Username, "-t", } diff --git a/internal/namespaces/instance/v1/custom_ssh_key.go b/internal/namespaces/instance/v1/custom_ssh_key.go index 361abb28ff..1900ec8961 100644 --- a/internal/namespaces/instance/v1/custom_ssh_key.go +++ b/internal/namespaces/instance/v1/custom_ssh_key.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "encoding/binary" + "errors" "fmt" "hash/crc32" "reflect" @@ -244,7 +245,7 @@ Lookup /root/.ssh/authorized_keys on your server for more information`, } if len(removedKeys) == 0 { - return nil, fmt.Errorf("no key found with given filters") + return nil, errors.New("no key found with given filters") } _, err = api.UpdateServer(&instance.UpdateServerRequest{ diff --git a/internal/namespaces/instance/v1/custom_volume.go b/internal/namespaces/instance/v1/custom_volume.go index 1b8e79fb55..2fc6bbad8d 100644 --- a/internal/namespaces/instance/v1/custom_volume.go +++ b/internal/namespaces/instance/v1/custom_volume.go @@ -2,8 +2,8 @@ package instance import ( "context" - "fmt" "reflect" + "strconv" "time" "github.com/fatih/color" @@ -36,7 +36,7 @@ func volumeSummaryMarshalerFunc(i interface{}, opt *human.MarshalOpt) (string, e // volumeMapMarshalerFunc returns the length of the map. func volumeMapMarshalerFunc(i interface{}, _ *human.MarshalOpt) (string, error) { volumes := i.(map[string]*instance.Volume) - return fmt.Sprintf("%v", len(volumes)), nil + return strconv.Itoa(len(volumes)), nil } // Builders diff --git a/internal/namespaces/k8s/v1/custom_cluster.go b/internal/namespaces/k8s/v1/custom_cluster.go index 342fb87d1d..253b296090 100644 --- a/internal/namespaces/k8s/v1/custom_cluster.go +++ b/internal/namespaces/k8s/v1/custom_cluster.go @@ -123,7 +123,7 @@ func clusterCreateBuilder(c *core.Command) *core.Command { if args.Version == "latest" { latestVersion, err := getLatestK8SVersion(core.ExtractClient(ctx)) if err != nil { - return nil, fmt.Errorf("could not retrieve latest K8S version") + return nil, errors.New("could not retrieve latest K8S version") } args.Version = latestVersion } diff --git a/internal/namespaces/k8s/v1/helpers_test.go b/internal/namespaces/k8s/v1/helpers_test.go index 215a0fe809..9361a09a95 100644 --- a/internal/namespaces/k8s/v1/helpers_test.go +++ b/internal/namespaces/k8s/v1/helpers_test.go @@ -81,7 +81,7 @@ func createClusterAndWaitAndInstallKubeconfig(clusterNameSuffix string, metaKey } ctx.Meta[kubeconfigMetaKey] = kubeconfig - cmd = fmt.Sprintf("scw k8s kubeconfig install %s", cluster.ID) + cmd = "scw k8s kubeconfig install " + cluster.ID _ = ctx.ExecuteCmd(strings.Split(cmd, " ")) return nil } @@ -146,7 +146,7 @@ func createClusterAndWaitAndKubeconfigAndPopulateFileAndInstall(clusterNameSuffi if err != nil { return err } - cmd = fmt.Sprintf("scw k8s kubeconfig install %s", cluster.ID) + cmd = "scw k8s kubeconfig install " + cluster.ID _ = ctx.ExecuteCmd(strings.Split(cmd, " ")) return nil diff --git a/internal/namespaces/lb/v1/custom_backend.go b/internal/namespaces/lb/v1/custom_backend.go index 5bd33652ed..94d80088ac 100644 --- a/internal/namespaces/lb/v1/custom_backend.go +++ b/internal/namespaces/lb/v1/custom_backend.go @@ -152,7 +152,7 @@ func backendCreateBuilder(c *core.Command) *core.Command { if server.Server.PrivateIP == nil { return nil, &core.CliError{ Message: fmt.Sprintf("server %s (%s) does not have a private ip", server.Server.ID, server.Server.Name), - Hint: fmt.Sprintf("Private ip are assigned when the server boots, start yours with: scw instance server start %s", server.Server.ID), + Hint: "Private ip are assigned when the server boots, start yours with: scw instance server start " + server.Server.ID, } } serverIPs = append(serverIPs, *server.Server.PrivateIP) @@ -208,7 +208,7 @@ func backendCreateBuilder(c *core.Command) *core.Command { if server.PrivateIP == nil { return nil, &core.CliError{ Message: fmt.Sprintf("server %s (%s) does not have a private ip", server.ID, server.Name), - Hint: fmt.Sprintf("Private ip are assigned when the server boots, start yours with: scw instance server start %s", server.ID), + Hint: "Private ip are assigned when the server boots, start yours with: scw instance server start " + server.ID, } } serverIPs = append(serverIPs, *server.PrivateIP) @@ -331,7 +331,7 @@ func backendAddServersBuilder(c *core.Command) *core.Command { if server.Server.PrivateIP == nil { return nil, &core.CliError{ Message: fmt.Sprintf("server %s (%s) does not have a private ip", server.Server.ID, server.Server.Name), - Hint: fmt.Sprintf("Private ip are assigned when the server boots, start yours with: scw instance server start %s", server.Server.ID), + Hint: "Private ip are assigned when the server boots, start yours with: scw instance server start " + server.Server.ID, } } serverIPs = append(serverIPs, *server.Server.PrivateIP) @@ -387,7 +387,7 @@ func backendAddServersBuilder(c *core.Command) *core.Command { if server.PrivateIP == nil { return nil, &core.CliError{ Message: fmt.Sprintf("server %s (%s) does not have a private ip", server.ID, server.Name), - Hint: fmt.Sprintf("Private ip are assigned when the server boots, start yours with: scw instance server start %s", server.ID), + Hint: "Private ip are assigned when the server boots, start yours with: scw instance server start " + server.ID, } } serverIPs = append(serverIPs, *server.PrivateIP) @@ -499,7 +499,7 @@ func backendRemoveServersBuilder(c *core.Command) *core.Command { if server.Server.PrivateIP == nil { return nil, &core.CliError{ Message: fmt.Sprintf("server %s (%s) does not have a private ip", server.Server.ID, server.Server.Name), - Hint: fmt.Sprintf("Private ip are assigned when the server boots, start yours with: scw instance server start %s", server.Server.ID), + Hint: "Private ip are assigned when the server boots, start yours with: scw instance server start " + server.Server.ID, } } serverIPs = append(serverIPs, *server.Server.PrivateIP) @@ -555,7 +555,7 @@ func backendRemoveServersBuilder(c *core.Command) *core.Command { if server.PrivateIP == nil { return nil, &core.CliError{ Message: fmt.Sprintf("server %s (%s) does not have a private ip", server.ID, server.Name), - Hint: fmt.Sprintf("Private ip are assigned when the server boots, start yours with: scw instance server start %s", server.ID), + Hint: "Private ip are assigned when the server boots, start yours with: scw instance server start " + server.ID, } } serverIPs = append(serverIPs, *server.PrivateIP) @@ -667,7 +667,7 @@ func backendSetServersBuilder(c *core.Command) *core.Command { if server.Server.PrivateIP == nil { return nil, &core.CliError{ Message: fmt.Sprintf("server %s (%s) does not have a private ip", server.Server.ID, server.Server.Name), - Hint: fmt.Sprintf("Private ip are assigned when the server boots, start yours with: scw instance server start %s", server.Server.ID), + Hint: "Private ip are assigned when the server boots, start yours with: scw instance server start " + server.Server.ID, } } serverIPs = append(serverIPs, *server.Server.PrivateIP) @@ -723,7 +723,7 @@ func backendSetServersBuilder(c *core.Command) *core.Command { if server.PrivateIP == nil { return nil, &core.CliError{ Message: fmt.Sprintf("server %s (%s) does not have a private ip", server.ID, server.Name), - Hint: fmt.Sprintf("Private ip are assigned when the server boots, start yours with: scw instance server start %s", server.ID), + Hint: "Private ip are assigned when the server boots, start yours with: scw instance server start " + server.ID, } } serverIPs = append(serverIPs, *server.PrivateIP) @@ -786,7 +786,7 @@ func interceptBackend() core.CommandInterceptor { } case "CheckMaxRetries": return nil, &core.CliError{ - Err: fmt.Errorf("missing or invalid 'health-check.check-max-retries' argument"), + Err: errors.New("missing or invalid 'health-check.check-max-retries' argument"), } } } diff --git a/internal/namespaces/lb/v1/custom_certificate.go b/internal/namespaces/lb/v1/custom_certificate.go index 9f01167382..606b9b03d2 100644 --- a/internal/namespaces/lb/v1/custom_certificate.go +++ b/internal/namespaces/lb/v1/custom_certificate.go @@ -2,6 +2,7 @@ package lb import ( "context" + "errors" "fmt" "reflect" @@ -112,7 +113,7 @@ func certificateCreateBuilder(c *core.Command) *core.Command { } return nil, &core.CliError{ - Err: fmt.Errorf("missing required argument"), + Err: errors.New("missing required argument"), Hint: fmt.Sprintf("You need to specify %s or %s", leCommonNameArgSpecs.Name, customeCertificateArgSpecs.Name), Code: 1, } diff --git a/internal/namespaces/lb/v1/custom_private_network.go b/internal/namespaces/lb/v1/custom_private_network.go index 52c225775c..66ca6b805e 100644 --- a/internal/namespaces/lb/v1/custom_private_network.go +++ b/internal/namespaces/lb/v1/custom_private_network.go @@ -1,7 +1,7 @@ package lb import ( - "fmt" + "errors" "time" "github.com/scaleway/scaleway-cli/v2/internal/human" @@ -11,7 +11,7 @@ import ( func lbPrivateNetworksMarshalerFunc(i interface{}, opt *human.MarshalOpt) (string, error) { privateNetworks, ok := i.([]*lb.PrivateNetwork) if !ok { - return "", fmt.Errorf("invalid type: expected []*lb.PrivateNetwork") + return "", errors.New("invalid type: expected []*lb.PrivateNetwork") } type customPrivateNetwork struct { diff --git a/internal/namespaces/lb/v1/helper_test.go b/internal/namespaces/lb/v1/helper_test.go index 1b60562af4..f8e7667564 100644 --- a/internal/namespaces/lb/v1/helper_test.go +++ b/internal/namespaces/lb/v1/helper_test.go @@ -63,7 +63,7 @@ func createBackend(forwardPort int32) core.BeforeFunc { func addIP2Backend(ip string) core.BeforeFunc { return core.ExecStoreBeforeCmd( "AddIP2Backend", - fmt.Sprintf("scw lb backend add-servers {{ .Backend.ID }} server-ip.0=%s", ip), + "scw lb backend add-servers {{ .Backend.ID }} server-ip.0="+ip, ) } @@ -97,7 +97,7 @@ func createClusterAndWaitAndInstallKubeconfig(metaKey string, kubeconfigMetaKey } ctx.Meta[kubeconfigMetaKey] = kubeconfig - cmd = fmt.Sprintf("scw k8s kubeconfig install %s", cluster.ID) + cmd = "scw k8s kubeconfig install " + cluster.ID _ = ctx.ExecuteCmd(strings.Split(cmd, " ")) return nil } diff --git a/internal/namespaces/mnq/v1beta1/custom_nats_prompt.go b/internal/namespaces/mnq/v1beta1/custom_nats_prompt.go index 4ecaba4a65..2ed91447a9 100644 --- a/internal/namespaces/mnq/v1beta1/custom_nats_prompt.go +++ b/internal/namespaces/mnq/v1beta1/custom_nats_prompt.go @@ -11,7 +11,7 @@ import ( func promptNatsAccounts(ctx context.Context, natsAccounts []*mnq.NatsAccount, totalCount uint64) (*mnq.NatsAccount, error) { if totalCount == 0 { - return nil, fmt.Errorf("no nats account found, please create a NATS account with 'scw mnq nats create-account'") + return nil, errors.New("no nats account found, please create a NATS account with 'scw mnq nats create-account'") } if !interactive.IsInteractive { diff --git a/internal/namespaces/object/v1/custom_bucket_test.go b/internal/namespaces/object/v1/custom_bucket_test.go index 1954eca976..d312fdf4bb 100644 --- a/internal/namespaces/object/v1/custom_bucket_test.go +++ b/internal/namespaces/object/v1/custom_bucket_test.go @@ -25,7 +25,7 @@ func Test_BucketCreate(t *testing.T) { bucketName1 := randomNameWithPrefix(core.TestBucketNamePrefix + testBucketNameActionCreate) t.Run("Simple", core.Test(&core.TestConfig{ Commands: object.GetCommands(), - Cmd: fmt.Sprintf("scw object bucket create %s", bucketName1), + Cmd: "scw object bucket create " + bucketName1, Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { bucket := ctx.Result.(*object.BucketResponse).BucketInfo @@ -113,7 +113,7 @@ func Test_BucketDelete(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ Commands: object.GetCommands(), BeforeFunc: createBucket(bucketName), - Cmd: fmt.Sprintf("scw object bucket delete %s", bucketName), + Cmd: "scw object bucket delete " + bucketName, Check: core.TestCheckCombine( core.TestCheckS3Golden(), core.TestCheckExitCode(0), @@ -127,7 +127,7 @@ func Test_BucketGet(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ Commands: object.GetCommands(), BeforeFunc: createBucket(bucketName1), - Cmd: fmt.Sprintf("scw object bucket get %s", bucketName1), + Cmd: "scw object bucket get " + bucketName1, Check: core.TestCheckCombine( core.TestCheckS3Golden(), core.TestCheckExitCode(0), @@ -253,11 +253,11 @@ func randomNameWithPrefix(prefix string) string { } func createBucket(name string) core.BeforeFunc { - return core.ExecStoreBeforeCmd("Bucket", fmt.Sprintf("scw object bucket create %s", name)) + return core.ExecStoreBeforeCmd("Bucket", "scw object bucket create "+name) } func deleteBucket(name string) core.AfterFunc { - return core.ExecAfterCmd(fmt.Sprintf("scw object bucket delete %s", name)) + return core.ExecAfterCmd("scw object bucket delete " + name) } func checkACL(t *testing.T, expected string, actual []object.CustomS3ACLGrant, owner string) { diff --git a/internal/namespaces/object/v1/custom_config_install.go b/internal/namespaces/object/v1/custom_config_install.go index 0b89c6b43e..7254ab921b 100644 --- a/internal/namespaces/object/v1/custom_config_install.go +++ b/internal/namespaces/object/v1/custom_config_install.go @@ -2,7 +2,7 @@ package object import ( "context" - "fmt" + "errors" "os" "path/filepath" "reflect" @@ -88,7 +88,7 @@ func configInstallCommand() *core.Command { return nil, err } if !doIt { - return nil, fmt.Errorf("installation aborted by user") + return nil, errors.New("installation aborted by user") } } @@ -104,7 +104,7 @@ func configInstallCommand() *core.Command { return "", err } return &core.SuccessResult{ - Message: fmt.Sprintf("Configuration file successfully installed at %s", configPath), + Message: "Configuration file successfully installed at " + configPath, }, nil }, } diff --git a/internal/namespaces/object/v1/s3configfile.go b/internal/namespaces/object/v1/s3configfile.go index 106c2258dc..fbed747a44 100644 --- a/internal/namespaces/object/v1/s3configfile.go +++ b/internal/namespaces/object/v1/s3configfile.go @@ -5,7 +5,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "path" "text/template" @@ -82,7 +81,7 @@ func newS3Config(ctx context.Context, region scw.Region, name string) (s3config, client := core.ExtractClient(ctx) accessKey, accessExists := client.GetAccessKey() if !accessExists { - return s3config{}, fmt.Errorf("no access key found") + return s3config{}, errors.New("no access key found") } secretKey, secretExists := client.GetSecretKey() if !secretExists { diff --git a/internal/namespaces/rdb/v1/custom_acl.go b/internal/namespaces/rdb/v1/custom_acl.go index 584a60a180..74e558cdca 100644 --- a/internal/namespaces/rdb/v1/custom_acl.go +++ b/internal/namespaces/rdb/v1/custom_acl.go @@ -82,7 +82,7 @@ func aclAddBuilder(c *core.Command) *core.Command { description := args.Description if description == "" { - description = fmt.Sprintf("Allow %s", args.ACLRuleIPs.String()) + description = "Allow " + args.ACLRuleIPs.String() } rule, err := api.AddInstanceACLRules(&rdb.AddInstanceACLRulesRequest{ @@ -271,7 +271,7 @@ func aclSetBuilder(c *core.Command) *core.Command { for _, ip := range args.ACLRuleIPs { aclRules = append(aclRules, &rdb.ACLRuleRequest{ IP: ip, - Description: fmt.Sprintf("Allow %s", ip.String()), + Description: "Allow " + ip.String(), }) } diff --git a/internal/namespaces/rdb/v1/custom_endpoint.go b/internal/namespaces/rdb/v1/custom_endpoint.go index 33ff096d02..689b075ff0 100644 --- a/internal/namespaces/rdb/v1/custom_endpoint.go +++ b/internal/namespaces/rdb/v1/custom_endpoint.go @@ -2,6 +2,7 @@ package rdb import ( "context" + "errors" "fmt" "reflect" @@ -266,7 +267,7 @@ func endpointRequestFromCustom(customEndpoints []*rdbEndpointSpecCustom) ([]*rdb LoadBalancer: &rdb.EndpointSpecLoadBalancer{}, }) } else { - return nil, fmt.Errorf("endpoint must be either a load-balancer or a private network") + return nil, errors.New("endpoint must be either a load-balancer or a private network") } } return endpoints, nil diff --git a/internal/namespaces/rdb/v1/custom_instance.go b/internal/namespaces/rdb/v1/custom_instance.go index 731db6ba9d..407ded2cb4 100644 --- a/internal/namespaces/rdb/v1/custom_instance.go +++ b/internal/namespaces/rdb/v1/custom_instance.go @@ -10,6 +10,7 @@ import ( "path" "reflect" "runtime" + "strconv" "strings" "time" @@ -734,7 +735,7 @@ func createConnectCommandLineArgs(endpoint *rdbSDK.Endpoint, family engineFamily return []string{ clidb, "--host", endpoint.IP.String(), - "--port", fmt.Sprintf("%d", endpoint.Port), + "--port", strconv.FormatUint(uint64(endpoint.Port), 10), "--username", args.Username, "--dbname", database, }, nil @@ -748,7 +749,7 @@ func createConnectCommandLineArgs(endpoint *rdbSDK.Endpoint, family engineFamily return []string{ clidb, "--host", endpoint.IP.String(), - "--port", fmt.Sprintf("%d", endpoint.Port), + "--port", strconv.FormatUint(uint64(endpoint.Port), 10), "--database", database, "--user", args.Username, }, nil diff --git a/internal/namespaces/rdb/v1/custom_url_test.go b/internal/namespaces/rdb/v1/custom_url_test.go index 768f957592..63efe5d1a3 100644 --- a/internal/namespaces/rdb/v1/custom_url_test.go +++ b/internal/namespaces/rdb/v1/custom_url_test.go @@ -56,7 +56,7 @@ func Test_UserGetURL(t *testing.T) { createInstance("PostgreSQL-12"), core.ExecBeforeCmd(fmt.Sprintf("scw rdb user create instance-id={{ $.Instance.ID }} name=%s password=%s is-admin=false", customUserName, customUserPassword)), ), - Cmd: fmt.Sprintf("scw rdb user get-url {{ $.Instance.ID }} user=%s", customUserName), + Cmd: "scw rdb user get-url {{ $.Instance.ID }} user=" + customUserName, Check: core.TestCheckCombine( core.TestCheckGolden(), func(t *testing.T, ctx *core.CheckFuncCtx) { @@ -73,9 +73,9 @@ func Test_UserGetURL(t *testing.T) { Commands: rdb.GetCommands(), BeforeFunc: core.BeforeFuncCombine( createInstance("PostgreSQL-12"), - core.ExecBeforeCmd(fmt.Sprintf("scw rdb database create instance-id={{ $.Instance.ID }} name=%s", customDBName)), + core.ExecBeforeCmd("scw rdb database create instance-id={{ $.Instance.ID }} name="+customDBName), ), - Cmd: fmt.Sprintf("scw rdb user get-url {{ $.Instance.ID }} db=%s", customDBName), + Cmd: "scw rdb user get-url {{ $.Instance.ID }} db=" + customDBName, Check: core.TestCheckCombine( core.TestCheckGolden(), func(t *testing.T, ctx *core.CheckFuncCtx) { diff --git a/internal/namespaces/registry/v1/custom_docker_helper.go b/internal/namespaces/registry/v1/custom_docker_helper.go index 073140564f..47da007473 100644 --- a/internal/namespaces/registry/v1/custom_docker_helper.go +++ b/internal/namespaces/registry/v1/custom_docker_helper.go @@ -5,6 +5,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "os" @@ -70,7 +71,7 @@ func registrySetupDockerHelperRun(ctx context.Context, argsI interface{}) (i int if err != nil { return nil, err } - helperScriptPath := filepath.Join(scriptDirArg, fmt.Sprintf("docker-credential-%s", binaryName)) + helperScriptPath := filepath.Join(scriptDirArg, "docker-credential-"+binaryName) buf := bytes.Buffer{} tplData := map[string]string{ "BinaryName": binaryName, @@ -100,7 +101,7 @@ func registrySetupDockerHelperRun(ctx context.Context, argsI interface{}) (i int return nil, err } if !continueInstallation { - return nil, fmt.Errorf("installation cancelled") + return nil, errors.New("installation cancelled") } err = writeHelperScript(helperScriptPath, helperScriptContent) @@ -119,7 +120,7 @@ func registrySetupDockerHelperRun(ctx context.Context, argsI interface{}) (i int } _, _ = interactive.Println() - _, err = exec.LookPath(fmt.Sprintf("docker-credential-%s", binaryName)) + _, err = exec.LookPath("docker-credential-" + binaryName) if err != nil { _, _ = interactive.Println(fmt.Sprintf("docker-credential-%s is not present in your $PATH, you should add %s to your $PATH to make it work.", binaryName, path.Dir(helperScriptPath))) _, _ = interactive.Println(fmt.Sprintf("You can add it by adding `export PATH=$PATH:%s` to your `.bashrc`, `.fishrc` or `.zshrc`", path.Dir(helperScriptPath))) @@ -184,7 +185,7 @@ func registryDockerHelperGetRun(ctx context.Context, _ interface{}) (i interface secretKey, ok := client.GetSecretKey() if !ok { - return nil, fmt.Errorf("could not get secret key") + return nil, errors.New("could not get secret key") } raw, err := json.Marshal(registryDockerHelperGetResponse{ diff --git a/internal/namespaces/registry/v1/custom_image_test.go b/internal/namespaces/registry/v1/custom_image_test.go index 709035b5ef..82b12a4574 100644 --- a/internal/namespaces/registry/v1/custom_image_test.go +++ b/internal/namespaces/registry/v1/custom_image_test.go @@ -84,7 +84,7 @@ func setupImage(dockerImage string, namespaceEndpoint string, imageName string, core.BeforeFuncOsExec("docker", "pull", dockerImage), core.BeforeFuncOsExec("docker", "tag", dockerImage, remote), core.BeforeFuncOsExec("docker", "push", remote), - core.ExecStoreBeforeCmd("ImageListResult", fmt.Sprintf("scw registry image list name=%s", imageName)), - core.ExecBeforeCmd(fmt.Sprintf(`scw registry image update {{ (index .ImageListResult 0).ID }} visibility=%s`, visibility.String())), + core.ExecStoreBeforeCmd("ImageListResult", "scw registry image list name="+imageName), + core.ExecBeforeCmd("scw registry image update {{ (index .ImageListResult 0).ID }} visibility="+visibility.String()), ) } diff --git a/internal/namespaces/registry/v1/custom_login.go b/internal/namespaces/registry/v1/custom_login.go index 81f282796b..9488af7e5f 100644 --- a/internal/namespaces/registry/v1/custom_login.go +++ b/internal/namespaces/registry/v1/custom_login.go @@ -3,7 +3,7 @@ package registry import ( "bytes" "context" - "fmt" + "errors" "os/exec" "reflect" @@ -46,7 +46,7 @@ func registryLoginRun(ctx context.Context, argsI interface{}) (i interface{}, e secretKey, ok := client.GetSecretKey() if !ok { - return nil, fmt.Errorf("could not get secret key") + return nil, errors.New("could not get secret key") } cmdArgs := []string{"login", "-u", "scaleway", "--password-stdin", endpoint} diff --git a/internal/namespaces/secret/v1beta1/custom_secret_version.go b/internal/namespaces/secret/v1beta1/custom_secret_version.go index af13c103c6..9f25a017d7 100644 --- a/internal/namespaces/secret/v1beta1/custom_secret_version.go +++ b/internal/namespaces/secret/v1beta1/custom_secret_version.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "reflect" "github.com/scaleway/scaleway-cli/v2/internal/core" @@ -80,7 +79,7 @@ func secretVersionAccessBuilder(c *core.Command) *core.Command { func getSecretVersionField(data []byte, field string) ([]byte, error) { var rawFields interface{} if err := json.Unmarshal(data, &rawFields); err != nil { - return nil, fmt.Errorf("cannot unmarshal JSON data") + return nil, errors.New("cannot unmarshal JSON data") } rawField, ok := rawFields.(map[string]interface{})[field] @@ -92,6 +91,6 @@ func getSecretVersionField(data []byte, field string) ([]byte, error) { case string: return []byte(field), nil default: - return nil, fmt.Errorf("JSON field type is not valid") + return nil, errors.New("JSON field type is not valid") } } diff --git a/internal/platform/terminal/terminal_client.go b/internal/platform/terminal/terminal_client.go index 513659d645..971edfdb36 100644 --- a/internal/platform/terminal/terminal_client.go +++ b/internal/platform/terminal/terminal_client.go @@ -115,7 +115,7 @@ func validateClient(client *scw.Client) error { accessKey, _ := client.GetAccessKey() if accessKey == "" { return &platform.ClientError{ - Err: fmt.Errorf("access key is required"), + Err: errors.New("access key is required"), Details: configErrorDetails("access_key", "SCW_ACCESS_KEY"), } } @@ -129,7 +129,7 @@ func validateClient(client *scw.Client) error { secretKey, _ := client.GetSecretKey() if secretKey == "" { return &platform.ClientError{ - Err: fmt.Errorf("secret key is required"), + Err: errors.New("secret key is required"), Details: configErrorDetails("secret_key", "SCW_SECRET_KEY"), } } @@ -143,7 +143,7 @@ func validateClient(client *scw.Client) error { defaultOrganizationID, _ := client.GetDefaultOrganizationID() if defaultOrganizationID == "" { return &platform.ClientError{ - Err: fmt.Errorf("organization ID is required"), + Err: errors.New("organization ID is required"), Details: configErrorDetails("default_organization_id", "SCW_DEFAULT_ORGANIZATION_ID"), } } @@ -157,7 +157,7 @@ func validateClient(client *scw.Client) error { defaultZone, _ := client.GetDefaultZone() if defaultZone == "" { return &platform.ClientError{ - Err: fmt.Errorf("default zone is required"), + Err: errors.New("default zone is required"), Details: configErrorDetails("default_zone", "SCW_DEFAULT_ZONE"), } } @@ -175,7 +175,7 @@ func validateClient(client *scw.Client) error { defaultRegion, _ := client.GetDefaultRegion() if defaultRegion == "" { return &platform.ClientError{ - Err: fmt.Errorf("default region is required"), + Err: errors.New("default region is required"), Details: configErrorDetails("default_region", "SCW_DEFAULT_REGION"), } } diff --git a/internal/sshconfig/bastion_host.go b/internal/sshconfig/bastion_host.go index e4e93c21d2..c8e2360249 100644 --- a/internal/sshconfig/bastion_host.go +++ b/internal/sshconfig/bastion_host.go @@ -30,7 +30,7 @@ func (b BastionHost) Config() string { } func (b BastionHost) name() string { - return fmt.Sprintf("*.%s", b.Name) + return "*." + b.Name } func (b BastionHost) address() string { diff --git a/internal/sshconfig/sshconfig.go b/internal/sshconfig/sshconfig.go index 0c85aa6687..0b42ad4dbf 100644 --- a/internal/sshconfig/sshconfig.go +++ b/internal/sshconfig/sshconfig.go @@ -78,7 +78,7 @@ func sshConfigFolder(homeDir string) string { } func includeLine() string { - return fmt.Sprintf("Include %s", sshConfigFileName) + return "Include " + sshConfigFileName } // DefaultConfigFilePath returns the default ssh config file path diff --git a/internal/tabwriter/tabwriter_test.go b/internal/tabwriter/tabwriter_test.go index 0bd9f3f726..8124603f90 100644 --- a/internal/tabwriter/tabwriter_test.go +++ b/internal/tabwriter/tabwriter_test.go @@ -8,6 +8,7 @@ import ( "bytes" "fmt" "io" + "strconv" "testing" "github.com/scaleway/scaleway-cli/v2/internal/tabwriter" @@ -725,7 +726,7 @@ func BenchmarkPyramid(b *testing.B) { for _, x := range [...]int{10, 100, 1000} { // Build a line with x cells. line := bytes.Repeat([]byte("a\t"), x) - b.Run(fmt.Sprintf("%d", x), func(b *testing.B) { + b.Run(strconv.Itoa(x), func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { w := tabwriter.NewWriter(io.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings @@ -747,7 +748,7 @@ func BenchmarkRagged(b *testing.B) { lines[i] = bytes.Repeat([]byte("a\t"), w) } for _, h := range [...]int{10, 100, 1000} { - b.Run(fmt.Sprintf("%d", h), func(b *testing.B) { + b.Run(strconv.Itoa(h), func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { w := tabwriter.NewWriter(io.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings diff --git a/internal/tasks/tasks_test.go b/internal/tasks/tasks_test.go index 16cadc5646..954daa2d32 100644 --- a/internal/tasks/tasks_test.go +++ b/internal/tasks/tasks_test.go @@ -3,7 +3,6 @@ package tasks_test import ( "context" "errors" - "fmt" "os" "runtime" "strconv" @@ -20,7 +19,7 @@ func TestGeneric(t *testing.T) { ts.SetLoggerMode(tasks.PrinterModeQuiet) tasks.Add(ts, "convert int to string", func(_ *tasks.Task, args int) (nextArgs string, err error) { - return fmt.Sprintf("%d", args), nil + return strconv.Itoa(args), nil }) tasks.Add(ts, "convert string to int and divide by 4", func(_ *tasks.Task, args string) (nextArgs int, err error) { i, err := strconv.ParseInt(args, 10, 32)