diff --git a/.golangci.yml b/.golangci.yml index b7be9e413a2d..a00093c80d93 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -44,9 +44,6 @@ linters: run: timeout: 5m - skip-files: - - cli/compose/schema/bindata.go - - .*generated.* linters-settings: depguard: @@ -58,7 +55,8 @@ linters-settings: gocyclo: min-complexity: 16 govet: - check-shadowing: true + enable: + - shadow settings: shadow: strict: true @@ -94,6 +92,10 @@ issues: exclude: - parameter .* always receives + exclude-files: + - cli/compose/schema/bindata.go + - .*generated.* + exclude-rules: # We prefer to use an "exclude-list" so that new "default" exclusions are not # automatically inherited. We can decide whether or not to follow upstream diff --git a/cli-plugins/manager/error_test.go b/cli-plugins/manager/error_test.go index 55222d7042ea..c4cb19bd55d5 100644 --- a/cli-plugins/manager/error_test.go +++ b/cli-plugins/manager/error_test.go @@ -2,7 +2,7 @@ package manager import ( "encoding/json" - "fmt" + "errors" "testing" "gotest.tools/v3/assert" @@ -13,7 +13,7 @@ func TestPluginError(t *testing.T) { err := NewPluginError("new error") assert.Check(t, is.Error(err, "new error")) - inner := fmt.Errorf("testing") + inner := errors.New("testing") err = wrapAsPluginError(inner, "wrapping") assert.Check(t, is.Error(err, "wrapping: testing")) assert.Check(t, is.ErrorIs(err, inner)) diff --git a/cli/command/cli.go b/cli/command/cli.go index 28253f8c16c1..1d671135e655 100644 --- a/cli/command/cli.go +++ b/cli/command/cli.go @@ -315,7 +315,7 @@ func newAPIClientFromEndpoint(ep docker.Endpoint, configFile *configfile.ConfigF func resolveDockerEndpoint(s store.Reader, contextName string) (docker.Endpoint, error) { if s == nil { - return docker.Endpoint{}, fmt.Errorf("no context store initialized") + return docker.Endpoint{}, errors.New("no context store initialized") } ctxMeta, err := s.GetMetadata(contextName) if err != nil { diff --git a/cli/command/cli_test.go b/cli/command/cli_test.go index d0456cddc575..2f9cb89c4a43 100644 --- a/cli/command/cli_test.go +++ b/cli/command/cli_test.go @@ -192,7 +192,7 @@ func TestInitializeFromClientHangs(t *testing.T) { ts.Start() defer ts.Close() - opts := &flags.ClientOptions{Hosts: []string{fmt.Sprintf("unix://%s", socket)}} + opts := &flags.ClientOptions{Hosts: []string{"unix://" + socket}} configFile := &configfile.ConfigFile{} apiClient, err := NewAPIClientFromFlags(opts, configFile) assert.NilError(t, err) diff --git a/cli/command/container/attach.go b/cli/command/container/attach.go index 7f1cb258240a..a2d983868355 100644 --- a/cli/command/container/attach.go +++ b/cli/command/container/attach.go @@ -2,7 +2,6 @@ package container import ( "context" - "fmt" "io" "github.com/docker/cli/cli" @@ -158,7 +157,7 @@ func getExitStatus(errC <-chan error, resultC <-chan container.WaitResponse) err select { case result := <-resultC: if result.Error != nil { - return fmt.Errorf(result.Error.Message) + return errors.New(result.Error.Message) } if result.StatusCode != 0 { return cli.StatusError{StatusCode: int(result.StatusCode)} diff --git a/cli/command/container/attach_test.go b/cli/command/container/attach_test.go index b0aaea688cb3..7c16aec778f6 100644 --- a/cli/command/container/attach_test.go +++ b/cli/command/container/attach_test.go @@ -1,7 +1,6 @@ package container import ( - "fmt" "io" "testing" @@ -79,7 +78,7 @@ func TestNewAttachCommandErrors(t *testing.T) { func TestGetExitStatus(t *testing.T) { var ( - expectedErr = fmt.Errorf("unexpected error") + expectedErr = errors.New("unexpected error") errC = make(chan error, 1) resultC = make(chan container.WaitResponse, 1) ) diff --git a/cli/command/container/create_test.go b/cli/command/container/create_test.go index 36158dd3be4d..f77c699db344 100644 --- a/cli/command/container/create_test.go +++ b/cli/command/container/create_test.go @@ -3,7 +3,6 @@ package container import ( "context" "errors" - "fmt" "io" "os" "runtime" @@ -231,7 +230,7 @@ func TestNewCreateCommandWithContentTrustErrors(t *testing.T) { platform *specs.Platform, containerName string, ) (container.CreateResponse, error) { - return container.CreateResponse{}, fmt.Errorf("shouldn't try to pull image") + return container.CreateResponse{}, errors.New("shouldn't try to pull image") }, }, test.EnableContentTrust) fakeCLI.SetNotaryClient(tc.notaryFunc) diff --git a/cli/command/container/list_test.go b/cli/command/container/list_test.go index c42638300598..6c80541870ef 100644 --- a/cli/command/container/list_test.go +++ b/cli/command/container/list_test.go @@ -1,7 +1,7 @@ package container import ( - "fmt" + "errors" "io" "testing" @@ -147,7 +147,7 @@ func TestContainerListErrors(t *testing.T) { }, { containerListFunc: func(_ container.ListOptions) ([]types.Container, error) { - return nil, fmt.Errorf("error listing containers") + return nil, errors.New("error listing containers") }, expectedError: "error listing containers", }, diff --git a/cli/command/container/opts.go b/cli/command/container/opts.go index 5ce22a6e4ca8..2a49259d2914 100644 --- a/cli/command/container/opts.go +++ b/cli/command/container/opts.go @@ -574,10 +574,10 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con return nil, errors.Errorf("--health-retries cannot be negative") } if copts.healthStartPeriod < 0 { - return nil, fmt.Errorf("--health-start-period cannot be negative") + return nil, errors.New("--health-start-period cannot be negative") } if copts.healthStartInterval < 0 { - return nil, fmt.Errorf("--health-start-interval cannot be negative") + return nil, errors.New("--health-start-interval cannot be negative") } healthConfig = &container.HealthConfig{ diff --git a/cli/command/container/opts_test.go b/cli/command/container/opts_test.go index 28c109e6fbdb..e03c26530e2f 100644 --- a/cli/command/container/opts_test.go +++ b/cli/command/container/opts_test.go @@ -335,7 +335,7 @@ func TestParseHostname(t *testing.T) { hostnameWithDomain := "--hostname=hostname.domainname" hostnameWithDomainTld := "--hostname=hostname.domainname.tld" for hostname, expectedHostname := range validHostnames { - if config, _, _ := mustParse(t, fmt.Sprintf("--hostname=%s", hostname)); config.Hostname != expectedHostname { + if config, _, _ := mustParse(t, "--hostname="+hostname); config.Hostname != expectedHostname { t.Fatalf("Expected the config to have 'hostname' as %q, got %q", expectedHostname, config.Hostname) } } diff --git a/cli/command/container/rm_test.go b/cli/command/container/rm_test.go index 3f36e890d50b..704effbb59ce 100644 --- a/cli/command/container/rm_test.go +++ b/cli/command/container/rm_test.go @@ -2,7 +2,7 @@ package container import ( "context" - "fmt" + "errors" "io" "sort" "sync" @@ -37,7 +37,7 @@ func TestRemoveForce(t *testing.T) { mutex.Unlock() if container == "nosuchcontainer" { - return errdefs.NotFound(fmt.Errorf("Error: no such container: " + container)) + return errdefs.NotFound(errors.New("Error: no such container: " + container)) } return nil }, diff --git a/cli/command/container/run_test.go b/cli/command/container/run_test.go index 007fcb222c5c..d02956da1de3 100644 --- a/cli/command/container/run_test.go +++ b/cli/command/container/run_test.go @@ -3,7 +3,6 @@ package container import ( "context" "errors" - "fmt" "io" "net" "os/signal" @@ -135,7 +134,7 @@ func TestRunCommandWithContentTrustErrors(t *testing.T) { platform *specs.Platform, containerName string, ) (container.CreateResponse, error) { - return container.CreateResponse{}, fmt.Errorf("shouldn't try to pull image") + return container.CreateResponse{}, errors.New("shouldn't try to pull image") }, }, test.EnableContentTrust) fakeCLI.SetNotaryClient(tc.notaryFunc) diff --git a/cli/command/container/stats.go b/cli/command/container/stats.go index 4ac158266a30..dd5e35d5fae8 100644 --- a/cli/command/container/stats.go +++ b/cli/command/container/stats.go @@ -218,7 +218,7 @@ func RunStats(ctx context.Context, dockerCLI command.Cli, options *StatsOptions) // with a list of container names/IDs. if options.Filters != nil && options.Filters.Len() > 0 { - return fmt.Errorf("filtering is not supported when specifying a list of containers") + return errors.New("filtering is not supported when specifying a list of containers") } // Create the list of containers, and start collecting stats for all diff --git a/cli/command/context/options.go b/cli/command/context/options.go index ce79d57a4fe5..7b39f7d7686b 100644 --- a/cli/command/context/options.go +++ b/cli/command/context/options.go @@ -1,7 +1,6 @@ package context import ( - "fmt" "strconv" "strings" @@ -76,7 +75,7 @@ func validateConfig(config map[string]string, allowedKeys map[string]struct{}) e var errs []string for k := range config { if _, ok := allowedKeys[k]; !ok { - errs = append(errs, fmt.Sprintf("%s: unrecognized config key", k)) + errs = append(errs, "unrecognized config key: "+k) } } if len(errs) == 0 { diff --git a/cli/command/image/build.go b/cli/command/image/build.go index 61a5ed4dbb86..f19ac389bddd 100644 --- a/cli/command/image/build.go +++ b/cli/command/image/build.go @@ -458,7 +458,7 @@ func rewriteDockerfileFromForContentTrust(ctx context.Context, dockerfile io.Rea return nil, nil, err } - line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, fmt.Sprintf("FROM %s", reference.FamiliarString(trustedRef))) + line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, "FROM "+reference.FamiliarString(trustedRef)) resolvedTags = append(resolvedTags, &resolvedTag{ digestRef: trustedRef, tagRef: ref, diff --git a/cli/command/image/build/context.go b/cli/command/image/build/context.go index 6a5a50a1b463..2b8fed3be5c1 100644 --- a/cli/command/image/build/context.go +++ b/cli/command/image/build/context.go @@ -226,7 +226,7 @@ func GetContextFromURL(out io.Writer, remoteURL, dockerfileName string) (io.Read progressOutput := streamformatter.NewProgressOutput(out) // Pass the response body through a progress reader. - progReader := progress.NewProgressReader(response.Body, progressOutput, response.ContentLength, "", fmt.Sprintf("Downloading build context from remote url: %s", remoteURL)) + progReader := progress.NewProgressReader(response.Body, progressOutput, response.ContentLength, "", "Downloading build context from remote url: "+remoteURL) return GetContextFromReader(ioutils.NewReadCloserWrapper(progReader, func() error { return response.Body.Close() }), dockerfileName) } @@ -234,7 +234,7 @@ func GetContextFromURL(out io.Writer, remoteURL, dockerfileName string) (io.Read // getWithStatusError does an http.Get() and returns an error if the // status code is 4xx or 5xx. func getWithStatusError(url string) (resp *http.Response, err error) { - //#nosec G107 -- Ignore G107: Potential HTTP request made with variable url + //nolint:gosec // Ignore G107: Potential HTTP request made with variable url if resp, err = http.Get(url); err != nil { return nil, err } diff --git a/cli/command/image/pull_test.go b/cli/command/image/pull_test.go index 51e8ece6e615..3aa6e5524409 100644 --- a/cli/command/image/pull_test.go +++ b/cli/command/image/pull_test.go @@ -1,6 +1,7 @@ package image import ( + "errors" "fmt" "io" "strings" @@ -112,7 +113,7 @@ func TestNewPullCommandWithContentTrustErrors(t *testing.T) { for _, tc := range testCases { cli := test.NewFakeCli(&fakeClient{ imagePullFunc: func(ref string, options image.PullOptions) (io.ReadCloser, error) { - return io.NopCloser(strings.NewReader("")), fmt.Errorf("shouldn't try to pull image") + return io.NopCloser(strings.NewReader("")), errors.New("shouldn't try to pull image") }, }, test.EnableContentTrust) cli.SetNotaryClient(tc.notaryFunc) diff --git a/cli/command/image/remove_test.go b/cli/command/image/remove_test.go index 9220a5a16b13..b1035da92445 100644 --- a/cli/command/image/remove_test.go +++ b/cli/command/image/remove_test.go @@ -18,7 +18,7 @@ type notFound struct { } func (n notFound) Error() string { - return fmt.Sprintf("Error: No such image: %s", n.imageID) + return "Error: No such image: " + n.imageID } func (n notFound) NotFound() {} diff --git a/cli/command/network/connect.go b/cli/command/network/connect.go index 6ffb9b8dcf2d..22a685ef1d25 100644 --- a/cli/command/network/connect.go +++ b/cli/command/network/connect.go @@ -2,7 +2,7 @@ package network import ( "context" - "fmt" + "errors" "strings" "github.com/docker/cli/cli" @@ -10,6 +10,7 @@ import ( "github.com/docker/cli/cli/command/completion" "github.com/docker/cli/opts" "github.com/docker/docker/api/types/network" + "github.com/docker/docker/client" "github.com/spf13/cobra" ) @@ -36,14 +37,14 @@ func newConnectCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { options.network = args[0] options.container = args[1] - return runConnect(cmd.Context(), dockerCli, options) + return runConnect(cmd.Context(), dockerCli.Client(), options) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) == 0 { return completion.NetworkNames(dockerCli)(cmd, args, toComplete) } - network := args[0] - return completion.ContainerNames(dockerCli, true, not(isConnected(network)))(cmd, args, toComplete) + nw := args[0] + return completion.ContainerNames(dockerCli, true, not(isConnected(nw)))(cmd, args, toComplete) }, } @@ -57,14 +58,13 @@ func newConnectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runConnect(ctx context.Context, dockerCli command.Cli, options connectOptions) error { - client := dockerCli.Client() - +func runConnect(ctx context.Context, apiClient client.NetworkAPIClient, options connectOptions) error { driverOpts, err := convertDriverOpt(options.driverOpts) if err != nil { return err } - epConfig := &network.EndpointSettings{ + + return apiClient.NetworkConnect(ctx, options.network, options.container, &network.EndpointSettings{ IPAMConfig: &network.EndpointIPAMConfig{ IPv4Address: options.ipaddress, IPv6Address: options.ipv6address, @@ -73,9 +73,7 @@ func runConnect(ctx context.Context, dockerCli command.Cli, options connectOptio Links: options.links.GetAll(), Aliases: options.aliases, DriverOpts: driverOpts, - } - - return client.NetworkConnect(ctx, options.network, options.container, epConfig) + }) } func convertDriverOpt(options []string) (map[string]string, error) { @@ -85,7 +83,7 @@ func convertDriverOpt(options []string) (map[string]string, error) { // TODO(thaJeztah): we should probably not accept whitespace here (both for key and value). k = strings.TrimSpace(k) if !ok || k == "" { - return nil, fmt.Errorf("invalid key/value pair format in driver options") + return nil, errors.New("invalid key/value pair format in driver options") } driverOpt[k] = strings.TrimSpace(v) } diff --git a/cli/command/plugin/create_test.go b/cli/command/plugin/create_test.go index 37ce5e22c4bc..e05eb6085538 100644 --- a/cli/command/plugin/create_test.go +++ b/cli/command/plugin/create_test.go @@ -1,7 +1,7 @@ package plugin import ( - "fmt" + "errors" "io" "runtime" "testing" @@ -91,16 +91,14 @@ func TestCreateErrorFromDaemon(t *testing.T) { fs.WithFile("config.json", `{ "Name": "plugin-foo" }`)) defer tmpDir.Remove() - cli := test.NewFakeCli(&fakeClient{ + cmd := newCreateCommand(test.NewFakeCli(&fakeClient{ pluginCreateFunc: func(createContext io.Reader, createOptions types.PluginCreateOptions) error { - return fmt.Errorf("Error creating plugin") + return errors.New("error creating plugin") }, - }) - - cmd := newCreateCommand(cli) + })) cmd.SetArgs([]string{"plugin-foo", tmpDir.Path()}) cmd.SetOut(io.Discard) - assert.ErrorContains(t, cmd.Execute(), "Error creating plugin") + assert.ErrorContains(t, cmd.Execute(), "error creating plugin") } func TestCreatePlugin(t *testing.T) { diff --git a/cli/command/plugin/disable_test.go b/cli/command/plugin/disable_test.go index ca2e0d2cbbbe..cd78943c942d 100644 --- a/cli/command/plugin/disable_test.go +++ b/cli/command/plugin/disable_test.go @@ -1,7 +1,7 @@ package plugin import ( - "fmt" + "errors" "io" "testing" @@ -27,9 +27,9 @@ func TestPluginDisableErrors(t *testing.T) { }, { args: []string{"plugin-foo"}, - expectedError: "Error disabling plugin", + expectedError: "error disabling plugin", pluginDisableFunc: func(name string, disableOptions types.PluginDisableOptions) error { - return fmt.Errorf("Error disabling plugin") + return errors.New("error disabling plugin") }, }, } diff --git a/cli/command/plugin/enable_test.go b/cli/command/plugin/enable_test.go index 1d8840e77c16..0f220547562a 100644 --- a/cli/command/plugin/enable_test.go +++ b/cli/command/plugin/enable_test.go @@ -1,7 +1,7 @@ package plugin import ( - "fmt" + "errors" "io" "testing" @@ -29,7 +29,7 @@ func TestPluginEnableErrors(t *testing.T) { { args: []string{"plugin-foo"}, pluginEnableFunc: func(name string, options types.PluginEnableOptions) error { - return fmt.Errorf("failed to enable plugin") + return errors.New("failed to enable plugin") }, expectedError: "failed to enable plugin", }, @@ -43,10 +43,9 @@ func TestPluginEnableErrors(t *testing.T) { } for _, tc := range testCases { - cmd := newEnableCommand( - test.NewFakeCli(&fakeClient{ - pluginEnableFunc: tc.pluginEnableFunc, - })) + cmd := newEnableCommand(test.NewFakeCli(&fakeClient{ + pluginEnableFunc: tc.pluginEnableFunc, + })) cmd.SetArgs(tc.args) for key, value := range tc.flags { cmd.Flags().Set(key, value) diff --git a/cli/command/plugin/inspect_test.go b/cli/command/plugin/inspect_test.go index 4d3127660a68..f5c2ad585760 100644 --- a/cli/command/plugin/inspect_test.go +++ b/cli/command/plugin/inspect_test.go @@ -1,13 +1,13 @@ package plugin import ( + "errors" "fmt" "io" "testing" "github.com/docker/cli/internal/test" "github.com/docker/docker/api/types" - "gotest.tools/v3/assert" "gotest.tools/v3/golden" ) @@ -52,7 +52,7 @@ func TestInspectErrors(t *testing.T) { args: []string{"foo"}, expectedError: "error inspecting plugin", inspectFunc: func(name string) (*types.Plugin, []byte, error) { - return nil, nil, fmt.Errorf("error inspecting plugin") + return nil, nil, errors.New("error inspecting plugin") }, }, { diff --git a/cli/command/plugin/install_test.go b/cli/command/plugin/install_test.go index e49b582f83c8..03cad5f110e9 100644 --- a/cli/command/plugin/install_test.go +++ b/cli/command/plugin/install_test.go @@ -1,7 +1,7 @@ package plugin import ( - "fmt" + "errors" "io" "strings" "testing" @@ -38,9 +38,9 @@ func TestInstallErrors(t *testing.T) { { description: "installation error", args: []string{"foo"}, - expectedError: "Error installing plugin", + expectedError: "error installing plugin", installFunc: func(name string, options types.PluginInstallOptions) (io.ReadCloser, error) { - return nil, fmt.Errorf("Error installing plugin") + return nil, errors.New("error installing plugin") }, }, { @@ -48,7 +48,7 @@ func TestInstallErrors(t *testing.T) { args: []string{"foo"}, expectedError: "docker image pull", installFunc: func(name string, options types.PluginInstallOptions) (io.ReadCloser, error) { - return nil, fmt.Errorf("(image) when fetching") + return nil, errors.New("(image) when fetching") }, }, } @@ -92,7 +92,7 @@ func TestInstallContentTrustErrors(t *testing.T) { for _, tc := range testCases { cli := test.NewFakeCli(&fakeClient{ pluginInstallFunc: func(name string, options types.PluginInstallOptions) (io.ReadCloser, error) { - return nil, fmt.Errorf("should not try to install plugin") + return nil, errors.New("should not try to install plugin") }, }, test.EnableContentTrust) cli.SetNotaryClient(tc.notaryFunc) diff --git a/cli/command/plugin/list_test.go b/cli/command/plugin/list_test.go index ed30eb1c596f..a5e4e71d31a0 100644 --- a/cli/command/plugin/list_test.go +++ b/cli/command/plugin/list_test.go @@ -1,7 +1,7 @@ package plugin import ( - "fmt" + "errors" "io" "testing" @@ -32,7 +32,7 @@ func TestListErrors(t *testing.T) { args: []string{}, expectedError: "error listing plugins", listFunc: func(filter filters.Args) (types.PluginsListResponse, error) { - return types.PluginsListResponse{}, fmt.Errorf("error listing plugins") + return types.PluginsListResponse{}, errors.New("error listing plugins") }, }, { diff --git a/cli/command/plugin/remove_test.go b/cli/command/plugin/remove_test.go index 36cfe0ba4508..cf701cfa3b72 100644 --- a/cli/command/plugin/remove_test.go +++ b/cli/command/plugin/remove_test.go @@ -1,7 +1,7 @@ package plugin import ( - "fmt" + "errors" "io" "testing" @@ -24,9 +24,9 @@ func TestRemoveErrors(t *testing.T) { { args: []string{"plugin-foo"}, pluginRemoveFunc: func(name string, options types.PluginRemoveOptions) error { - return fmt.Errorf("Error removing plugin") + return errors.New("error removing plugin") }, - expectedError: "Error removing plugin", + expectedError: "error removing plugin", }, } diff --git a/cli/command/registry/login_test.go b/cli/command/registry/login_test.go index acdb7a93f6c1..c8baa9535ad7 100644 --- a/cli/command/registry/login_test.go +++ b/cli/command/registry/login_test.go @@ -3,6 +3,7 @@ package registry import ( "bytes" "context" + "errors" "fmt" "testing" @@ -33,7 +34,7 @@ func (c fakeClient) Info(context.Context) (system.Info, error) { func (c fakeClient) RegistryLogin(_ context.Context, auth registrytypes.AuthConfig) (registrytypes.AuthenticateOKBody, error) { if auth.Password == expiredPassword { - return registrytypes.AuthenticateOKBody{}, fmt.Errorf("Invalid Username or Password") + return registrytypes.AuthenticateOKBody{}, errors.New("Invalid Username or Password") } if auth.Password == useToken { return registrytypes.AuthenticateOKBody{ @@ -41,7 +42,7 @@ func (c fakeClient) RegistryLogin(_ context.Context, auth registrytypes.AuthConf }, nil } if auth.Username == unknownUser { - return registrytypes.AuthenticateOKBody{}, fmt.Errorf(errUnknownUser) + return registrytypes.AuthenticateOKBody{}, errors.New(errUnknownUser) } return registrytypes.AuthenticateOKBody{}, nil } diff --git a/cli/command/registry_test.go b/cli/command/registry_test.go index 88215fe51e88..65acd069e2bb 100644 --- a/cli/command/registry_test.go +++ b/cli/command/registry_test.go @@ -1,7 +1,6 @@ package command_test import ( - "fmt" "testing" "github.com/docker/cli/cli/command" @@ -29,13 +28,11 @@ func TestGetDefaultAuthConfig(t *testing.T) { testCases := []struct { checkCredStore bool inputServerAddress string - expectedErr string expectedAuthConfig registry.AuthConfig }{ { checkCredStore: false, inputServerAddress: "", - expectedErr: "", expectedAuthConfig: registry.AuthConfig{ ServerAddress: "", Username: "", @@ -45,19 +42,16 @@ func TestGetDefaultAuthConfig(t *testing.T) { { checkCredStore: true, inputServerAddress: testAuthConfigs[0].ServerAddress, - expectedErr: "", expectedAuthConfig: testAuthConfigs[0], }, { checkCredStore: true, inputServerAddress: testAuthConfigs[1].ServerAddress, - expectedErr: "", expectedAuthConfig: testAuthConfigs[1], }, { checkCredStore: true, - inputServerAddress: fmt.Sprintf("https://%s", testAuthConfigs[1].ServerAddress), - expectedErr: "", + inputServerAddress: "https://" + testAuthConfigs[1].ServerAddress, expectedAuthConfig: testAuthConfigs[1], }, } @@ -68,13 +62,8 @@ func TestGetDefaultAuthConfig(t *testing.T) { for _, tc := range testCases { serverAddress := tc.inputServerAddress authconfig, err := command.GetDefaultAuthConfig(cfg, tc.checkCredStore, serverAddress, serverAddress == "https://index.docker.io/v1/") - if tc.expectedErr != "" { - assert.Check(t, err != nil) - assert.Check(t, is.Equal(tc.expectedErr, err.Error())) - } else { - assert.NilError(t, err) - assert.Check(t, is.DeepEqual(tc.expectedAuthConfig, authconfig)) - } + assert.NilError(t, err) + assert.Check(t, is.DeepEqual(tc.expectedAuthConfig, authconfig)) } } diff --git a/cli/command/service/logs.go b/cli/command/service/logs.go index e31f992fb489..b9f964aec951 100644 --- a/cli/command/service/logs.go +++ b/cli/command/service/logs.go @@ -212,9 +212,9 @@ func (f *taskFormatter) format(ctx context.Context, logCtx logContext) (string, taskName := fmt.Sprintf("%s.%d", serviceName, task.Slot) if !f.opts.noTaskIDs { if f.opts.noTrunc { - taskName += fmt.Sprintf(".%s", task.ID) + taskName += "." + task.ID } else { - taskName += fmt.Sprintf(".%s", stringid.TruncateID(task.ID)) + taskName += "." + stringid.TruncateID(task.ID) } } diff --git a/cli/command/service/progress/progress_test.go b/cli/command/service/progress/progress_test.go index 19ba07a9e81c..7e5ed2643ba2 100644 --- a/cli/command/service/progress/progress_test.go +++ b/cli/command/service/progress/progress_test.go @@ -874,7 +874,7 @@ func TestGlobalJobProgressUpdaterLarge(t *testing.T) { tasks := []swarm.Task{} for nodeID := range activeNodes { tasks = append(tasks, swarm.Task{ - ID: fmt.Sprintf("task%s", nodeID), + ID: "task" + nodeID, NodeID: nodeID, DesiredState: swarm.TaskStateComplete, Status: swarm.TaskStatus{ diff --git a/cli/command/stack/swarm/remove.go b/cli/command/stack/swarm/remove.go index 6ccd0b1ad22f..cde317fe0a66 100644 --- a/cli/command/stack/swarm/remove.go +++ b/cli/command/stack/swarm/remove.go @@ -58,7 +58,7 @@ func RunRemove(ctx context.Context, dockerCli command.Cli, opts options.Remove) hasError = removeNetworks(ctx, dockerCli, networks) || hasError if hasError { - errs = append(errs, fmt.Sprintf("Failed to remove some resources from stack: %s", namespace)) + errs = append(errs, "Failed to remove some resources from stack: "+namespace) continue } diff --git a/cli/command/swarm/ipnet_slice_test.go b/cli/command/swarm/ipnet_slice_test.go index 04f07430fd49..675881f91e0a 100644 --- a/cli/command/swarm/ipnet_slice_test.go +++ b/cli/command/swarm/ipnet_slice_test.go @@ -29,7 +29,7 @@ func TestIPNets(t *testing.T) { f := setUpIPNetFlagSet(&ips) vals := []string{"192.168.1.1/24", "10.0.0.1/16", "fd00:0:0:0:0:0:0:2/64"} - arg := fmt.Sprintf("--cidrs=%s", strings.Join(vals, ",")) + arg := "--cidrs=" + strings.Join(vals, ",") err := f.Parse([]string{arg}) if err != nil { t.Fatal("expected no error; got", err) @@ -134,7 +134,7 @@ func TestIPNetBadQuoting(t *testing.T) { var cidrs []net.IPNet f := setUpIPNetFlagSet(&cidrs) - if err := f.Parse([]string{fmt.Sprintf("--cidrs=%s", strings.Join(test.FlagArg, ","))}); err != nil { + if err := f.Parse([]string{"--cidrs=" + strings.Join(test.FlagArg, ",")}); err != nil { t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%s", err, test.FlagArg, test.Want[i]) } diff --git a/cli/command/system/info.go b/cli/command/system/info.go index 6d6416460aab..29cacc47fe97 100644 --- a/cli/command/system/info.go +++ b/cli/command/system/info.go @@ -5,6 +5,7 @@ package system import ( "context" + "errors" "fmt" "io" "regexp" @@ -187,7 +188,7 @@ func prettyPrintInfo(streams command.Streams, info dockerInfo) error { } if len(info.ServerErrors) > 0 || len(info.ClientErrors) > 0 { - return fmt.Errorf("errors pretty printing info") + return errors.New("errors pretty printing info") } return nil } diff --git a/cli/command/system/prune.go b/cli/command/system/prune.go index 4861f14ca382..815efdef76cf 100644 --- a/cli/command/system/prune.go +++ b/cli/command/system/prune.go @@ -74,7 +74,7 @@ Are you sure you want to continue?` func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) error { // TODO version this once "until" filter is supported for volumes if options.pruneVolumes && options.filter.Value().Contains("until") { - return fmt.Errorf(`ERROR: The "until" filter is not supported with "--volumes"`) + return errors.New(`ERROR: The "until" filter is not supported with "--volumes"`) } if !options.force { r, err := command.PromptForConfirmation(ctx, dockerCli.In(), dockerCli.Out(), confirmationMessage(dockerCli, options)) @@ -105,11 +105,11 @@ func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) } spaceReclaimed += spc if output != "" { - fmt.Fprintln(dockerCli.Out(), output) + _, _ = fmt.Fprintln(dockerCli.Out(), output) } } - fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed))) + _, _ = fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed))) return nil } diff --git a/cli/command/system/version_test.go b/cli/command/system/version_test.go index 5d7483c66c31..c0cf6425975f 100644 --- a/cli/command/system/version_test.go +++ b/cli/command/system/version_test.go @@ -2,7 +2,7 @@ package system import ( "context" - "fmt" + "errors" "strings" "testing" @@ -16,7 +16,7 @@ import ( func TestVersionWithoutServer(t *testing.T) { cli := test.NewFakeCli(&fakeClient{ serverVersion: func(ctx context.Context) (types.Version, error) { - return types.Version{}, fmt.Errorf("no server") + return types.Version{}, errors.New("no server") }, }) cmd := NewVersionCommand(cli) diff --git a/cli/command/telemetry_docker.go b/cli/command/telemetry_docker.go index 5dc72e2bb525..281ca9131b04 100644 --- a/cli/command/telemetry_docker.go +++ b/cli/command/telemetry_docker.go @@ -5,7 +5,6 @@ package command import ( "context" - "fmt" "net/url" "os" "path" @@ -85,7 +84,7 @@ func dockerExporterOTLPEndpoint(cli Cli) (endpoint string, secure bool) { // needs the scheme to use the correct resolver. // // We'll just handle this in a special way and add the unix:// back to the endpoint. - endpoint = fmt.Sprintf("unix://%s", path.Join(u.Host, u.Path)) + endpoint = "unix://" + path.Join(u.Host, u.Path) case "https": secure = true fallthrough diff --git a/cli/command/trust/key_load.go b/cli/command/trust/key_load.go index bbb19e733e39..4a5bb2605578 100644 --- a/cli/command/trust/key_load.go +++ b/cli/command/trust/key_load.go @@ -109,7 +109,7 @@ func decodePrivKeyIfNecessary(privPemBytes []byte, passRet notary.PassRetriever) if _, ok := pemBlock.Headers["path"]; !ok { privKey, _, err := trustmanager.GetPasswdDecryptBytes(passRet, privPemBytes, "", "encrypted") if err != nil { - return []byte{}, fmt.Errorf("could not decrypt key") + return []byte{}, errors.New("could not decrypt key") } privPemBytes = privKey.Private() } diff --git a/cli/command/trust/revoke.go b/cli/command/trust/revoke.go index 4a0d6e3af30b..4e376b64546b 100644 --- a/cli/command/trust/revoke.go +++ b/cli/command/trust/revoke.go @@ -41,7 +41,7 @@ func revokeTrust(ctx context.Context, dockerCLI command.Cli, remote string, opti } tag := imgRefAndAuth.Tag() if imgRefAndAuth.Tag() == "" && imgRefAndAuth.Digest() != "" { - return fmt.Errorf("cannot use a digest reference for IMAGE:TAG") + return errors.New("cannot use a digest reference for IMAGE:TAG") } if imgRefAndAuth.Tag() == "" && !options.forceYes { deleteRemote, err := command.PromptForConfirmation(ctx, dockerCLI.In(), dockerCLI.Out(), fmt.Sprintf("Please confirm you would like to delete all signature data for %s?", remote)) @@ -65,7 +65,7 @@ func revokeTrust(ctx context.Context, dockerCLI command.Cli, remote string, opti if err := revokeSignature(notaryRepo, tag); err != nil { return errors.Wrapf(err, "could not remove signature for %s", remote) } - fmt.Fprintf(dockerCLI.Out(), "Successfully deleted signature for %s\n", remote) + _, _ = fmt.Fprintf(dockerCLI.Out(), "Successfully deleted signature for %s\n", remote) return nil } @@ -102,7 +102,7 @@ func revokeAllSigs(notaryRepo client.Repository) error { } if len(releasedTargetWithRoleList) == 0 { - return fmt.Errorf("no signed tags to remove") + return errors.New("no signed tags to remove") } // we need all the roles that signed each released target so we can remove from all roles. diff --git a/cli/command/trust/signer_add.go b/cli/command/trust/signer_add.go index db6bcd7c3480..b0f98e6f7bbb 100644 --- a/cli/command/trust/signer_add.go +++ b/cli/command/trust/signer_add.go @@ -53,11 +53,11 @@ func addSigner(ctx context.Context, dockerCLI command.Cli, options signerAddOpti return fmt.Errorf("signer name \"%s\" must start with lowercase alphanumeric characters and can include \"-\" or \"_\" after the first character", signerName) } if signerName == "releases" { - return fmt.Errorf("releases is a reserved keyword, please use a different signer name") + return errors.New("releases is a reserved keyword, please use a different signer name") } if options.keys.Len() == 0 { - return fmt.Errorf("path to a public key must be provided using the `--key` flag") + return errors.New("path to a public key must be provided using the `--key` flag") } signerPubKeys, err := ingestPublicKeys(options.keys.GetAll()) if err != nil { diff --git a/cli/compose/schema/schema.go b/cli/compose/schema/schema.go index 6d11f5d81765..aa8dd19bd95d 100644 --- a/cli/compose/schema/schema.go +++ b/cli/compose/schema/schema.go @@ -102,7 +102,7 @@ func getDescription(err validationError) string { switch err.parent.Type() { case "invalid_type": if expectedType, ok := err.parent.Details()["expected"].(string); ok { - return fmt.Sprintf("must be a %s", humanReadableType(expectedType)) + return "must be a " + humanReadableType(expectedType) } case jsonschemaOneOf, jsonschemaAnyOf: if err.child == nil { diff --git a/cli/manifest/store/store.go b/cli/manifest/store/store.go index dbf773063296..c4f8219cec7b 100644 --- a/cli/manifest/store/store.go +++ b/cli/manifest/store/store.go @@ -2,7 +2,6 @@ package store import ( "encoding/json" - "fmt" "os" "path/filepath" "strings" @@ -162,7 +161,7 @@ func newNotFoundError(ref string) *notFoundError { } func (n *notFoundError) Error() string { - return fmt.Sprintf("No such manifest: %s", n.object) + return "No such manifest: " + n.object } // NotFound interface diff --git a/cli/registry/client/endpoint.go b/cli/registry/client/endpoint.go index 1bf0b78eae3e..e06bfea50bc5 100644 --- a/cli/registry/client/endpoint.go +++ b/cli/registry/client/endpoint.go @@ -1,7 +1,6 @@ package client import ( - "fmt" "net" "net/http" "time" @@ -125,7 +124,7 @@ type existingTokenHandler struct { } func (th *existingTokenHandler) AuthorizeRequest(req *http.Request, _ map[string]string) error { - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", th.token)) + req.Header.Set("Authorization", "Bearer "+th.token) return nil } diff --git a/dockerfiles/Dockerfile.lint b/dockerfiles/Dockerfile.lint index 2e99812dbe8e..cb040d62f40a 100644 --- a/dockerfiles/Dockerfile.lint +++ b/dockerfiles/Dockerfile.lint @@ -2,7 +2,7 @@ ARG GO_VERSION=1.21.11 ARG ALPINE_VERSION=3.20 -ARG GOLANGCI_LINT_VERSION=v1.55.2 +ARG GOLANGCI_LINT_VERSION=v1.59.0 FROM golangci/golangci-lint:${GOLANGCI_LINT_VERSION}-alpine AS golangci-lint diff --git a/e2e/image/push_test.go b/e2e/image/push_test.go index 40696921972e..3ee86c535189 100644 --- a/e2e/image/push_test.go +++ b/e2e/image/push_test.go @@ -337,10 +337,10 @@ func createImage(t *testing.T, repo string, tags ...string) string { func withNotaryPassphrase(pwd string) func(*icmd.Cmd) { return func(c *icmd.Cmd) { c.Env = append(c.Env, []string{ - fmt.Sprintf("NOTARY_ROOT_PASSPHRASE=%s", pwd), - fmt.Sprintf("NOTARY_TARGETS_PASSPHRASE=%s", pwd), - fmt.Sprintf("NOTARY_SNAPSHOT_PASSPHRASE=%s", pwd), - fmt.Sprintf("NOTARY_DELEGATION_PASSPHRASE=%s", pwd), + "NOTARY_ROOT_PASSPHRASE=" + pwd, + "NOTARY_TARGETS_PASSPHRASE=" + pwd, + "NOTARY_SNAPSHOT_PASSPHRASE=" + pwd, + "NOTARY_DELEGATION_PASSPHRASE=" + pwd, }...) } } diff --git a/e2e/plugin/trust_test.go b/e2e/plugin/trust_test.go index b32bfaf5b072..1abf5f8c4ca5 100644 --- a/e2e/plugin/trust_test.go +++ b/e2e/plugin/trust_test.go @@ -2,7 +2,6 @@ package plugin import ( "context" - "fmt" "testing" "github.com/docker/cli/e2e/internal/fixtures" @@ -20,7 +19,7 @@ func TestInstallWithContentTrust(t *testing.T) { skip.If(t, versions.LessThan(environment.DaemonAPIVersion(t), "1.44")) skip.If(t, environment.SkipPluginTests()) - pluginName := fmt.Sprintf("%s/plugin-content-trust", registryPrefix) + const pluginName = registryPrefix + "/plugin-content-trust" dir := fixtures.SetupConfigFile(t) defer dir.Remove() @@ -50,7 +49,7 @@ func TestInstallWithContentTrust(t *testing.T) { fixtures.WithNotary, ) result.Assert(t, icmd.Expected{ - Out: fmt.Sprintf("Installed plugin %s", pluginName), + Out: "Installed plugin " + pluginName, }) } diff --git a/e2e/trust/revoke_test.go b/e2e/trust/revoke_test.go index b903ece5621c..8ee5dc4ad973 100644 --- a/e2e/trust/revoke_test.go +++ b/e2e/trust/revoke_test.go @@ -1,7 +1,6 @@ package trust import ( - "fmt" "testing" "github.com/docker/cli/e2e/internal/fixtures" @@ -59,15 +58,15 @@ func setupTrustedImagesForRevoke(t *testing.T, dir fs.Dir) { func setupTrustedImagesForRevokeRepo(t *testing.T, dir fs.Dir) { t.Helper() icmd.RunCmd(icmd.Command("docker", "pull", fixtures.AlpineImage)).Assert(t, icmd.Success) - icmd.RunCommand("docker", "tag", fixtures.AlpineImage, fmt.Sprintf("%s:v1", revokeRepo)).Assert(t, icmd.Success) + icmd.RunCommand("docker", "tag", fixtures.AlpineImage, revokeRepo+":v1").Assert(t, icmd.Success) icmd.RunCmd( - icmd.Command("docker", "-D", "trust", "sign", fmt.Sprintf("%s:v1", revokeRepo)), + icmd.Command("docker", "-D", "trust", "sign", revokeRepo+":v1"), fixtures.WithPassphrase("root_password", "repo_password"), fixtures.WithConfig(dir.Path()), fixtures.WithNotary).Assert(t, icmd.Success) icmd.RunCmd(icmd.Command("docker", "pull", fixtures.BusyboxImage)).Assert(t, icmd.Success) - icmd.RunCommand("docker", "tag", fixtures.BusyboxImage, fmt.Sprintf("%s:v2", revokeRepo)).Assert(t, icmd.Success) + icmd.RunCommand("docker", "tag", fixtures.BusyboxImage, revokeRepo+":v2").Assert(t, icmd.Success) icmd.RunCmd( - icmd.Command("docker", "-D", "trust", "sign", fmt.Sprintf("%s:v2", revokeRepo)), + icmd.Command("docker", "-D", "trust", "sign", revokeRepo+":v2"), fixtures.WithPassphrase("root_password", "repo_password"), fixtures.WithConfig(dir.Path()), fixtures.WithNotary).Assert(t, icmd.Success) } diff --git a/e2e/trust/sign_test.go b/e2e/trust/sign_test.go index 81a09f78dfa0..44bb007826c2 100644 --- a/e2e/trust/sign_test.go +++ b/e2e/trust/sign_test.go @@ -1,7 +1,6 @@ package trust import ( - "fmt" "testing" "github.com/docker/cli/e2e/internal/fixtures" @@ -33,7 +32,7 @@ func TestSignLocalImage(t *testing.T) { fixtures.WithPassphrase("root_password", "repo_password"), fixtures.WithConfig(dir.Path()), fixtures.WithNotary) result.Assert(t, icmd.Success) - assert.Check(t, is.Contains(result.Stdout(), fmt.Sprintf("v1: digest: sha256:%s", fixtures.AlpineSha))) + assert.Check(t, is.Contains(result.Stdout(), "v1: digest: sha256:"+fixtures.AlpineSha)) } func TestSignWithLocalFlag(t *testing.T) { @@ -50,7 +49,7 @@ func TestSignWithLocalFlag(t *testing.T) { fixtures.WithPassphrase("root_password", "repo_password"), fixtures.WithConfig(dir.Path()), fixtures.WithNotary) result.Assert(t, icmd.Success) - assert.Check(t, is.Contains(result.Stdout(), fmt.Sprintf("v1: digest: sha256:%s", fixtures.BusyboxSha))) + assert.Check(t, is.Contains(result.Stdout(), "v1: digest: sha256:"+fixtures.BusyboxSha)) } func setupTrustedImageForOverwrite(t *testing.T, dir fs.Dir) { @@ -62,7 +61,7 @@ func setupTrustedImageForOverwrite(t *testing.T, dir fs.Dir) { fixtures.WithPassphrase("root_password", "repo_password"), fixtures.WithConfig(dir.Path()), fixtures.WithNotary) result.Assert(t, icmd.Success) - assert.Check(t, is.Contains(result.Stdout(), fmt.Sprintf("v1: digest: sha256:%s", fixtures.AlpineSha))) + assert.Check(t, is.Contains(result.Stdout(), "v1: digest: sha256:"+fixtures.AlpineSha)) icmd.RunCmd(icmd.Command("docker", "pull", fixtures.BusyboxImage)).Assert(t, icmd.Success) icmd.RunCommand("docker", "tag", fixtures.BusyboxImage, localImage).Assert(t, icmd.Success) } diff --git a/internal/test/cli.go b/internal/test/cli.go index 2315a7a1f22b..588b80132a1b 100644 --- a/internal/test/cli.go +++ b/internal/test/cli.go @@ -2,7 +2,7 @@ package test import ( "bytes" - "fmt" + "errors" "io" "strings" @@ -172,7 +172,7 @@ func (c *FakeCli) NotaryClient(imgRefAndAuth trust.ImageRefAndAuth, actions []st if c.notaryClientFunc != nil { return c.notaryClientFunc(imgRefAndAuth, actions) } - return nil, fmt.Errorf("no notary client available unless defined") + return nil, errors.New("no notary client available unless defined") } // ManifestStore returns a fake store used for testing diff --git a/opts/config.go b/opts/config.go index 3be0fa93dde0..1423ae3be585 100644 --- a/opts/config.go +++ b/opts/config.go @@ -2,6 +2,7 @@ package opts import ( "encoding/csv" + "errors" "fmt" "os" "strconv" @@ -68,7 +69,7 @@ func (o *ConfigOpt) Set(value string) error { } if options.ConfigName == "" { - return fmt.Errorf("source is required") + return errors.New("source is required") } if options.File.Name == "" { options.File.Name = options.ConfigName diff --git a/opts/env_test.go b/opts/env_test.go index 3561ceb3140c..a8a565be2a6f 100644 --- a/opts/env_test.go +++ b/opts/env_test.go @@ -11,9 +11,9 @@ import ( func TestValidateEnv(t *testing.T) { type testCase struct { - value string - expected string - err error + value string + expected string + expectedErr string } tests := []testCase{ { @@ -53,8 +53,8 @@ func TestValidateEnv(t *testing.T) { expected: fmt.Sprintf("PATH=%v", os.Getenv("PATH")), }, { - value: "=a", - err: fmt.Errorf("invalid environment variable: =a"), + value: "=a", + expectedErr: "invalid environment variable: =a", }, { value: "PATH=", @@ -89,17 +89,17 @@ func TestValidateEnv(t *testing.T) { expected: "some space after ", }, { - value: "=", - err: fmt.Errorf("invalid environment variable: ="), + value: "=", + expectedErr: "invalid environment variable: =", }, } if runtime.GOOS == "windows" { // Environment variables are case in-sensitive on Windows tests = append(tests, testCase{ - value: "PaTh", - expected: fmt.Sprintf("PaTh=%v", os.Getenv("PATH")), - err: nil, + value: "PaTh", + expected: fmt.Sprintf("PaTh=%v", os.Getenv("PATH")), + expectedErr: "", }) } @@ -108,10 +108,10 @@ func TestValidateEnv(t *testing.T) { t.Run(tc.value, func(t *testing.T) { actual, err := ValidateEnv(tc.value) - if tc.err == nil { + if tc.expectedErr == "" { assert.NilError(t, err) } else { - assert.Error(t, err, tc.err.Error()) + assert.Error(t, err, tc.expectedErr) } assert.Equal(t, actual, tc.expected) }) diff --git a/opts/file.go b/opts/file.go index 72b90e117f73..5cdd8e1386d1 100644 --- a/opts/file.go +++ b/opts/file.go @@ -18,7 +18,7 @@ type ErrBadKey struct { } func (e ErrBadKey) Error() string { - return fmt.Sprintf("poorly formatted environment: %s", e.msg) + return "poorly formatted environment: " + e.msg } func parseKeyValueFile(filename string, emptyFn func(string) (string, bool)) ([]string, error) { diff --git a/opts/hosts_test.go b/opts/hosts_test.go index 326d975564df..f33c915f03fb 100644 --- a/opts/hosts_test.go +++ b/opts/hosts_test.go @@ -23,7 +23,7 @@ func TestParseHost(t *testing.T) { " ": defaultHost, "fd://": "fd://", "fd://something": "fd://something", - "tcp://host:": fmt.Sprintf("tcp://host:%s", defaultHTTPPort), + "tcp://host:": "tcp://host:" + defaultHTTPPort, "tcp://": defaultTCPHost, "tcp://:2375": fmt.Sprintf("tcp://%s:%s", defaultHTTPHost, defaultHTTPPort), "tcp://:2376": fmt.Sprintf("tcp://%s:%s", defaultHTTPHost, defaultTLSHTTPPort), diff --git a/opts/mount.go b/opts/mount.go index 430b858e8fae..3a4ee31a27c7 100644 --- a/opts/mount.go +++ b/opts/mount.go @@ -165,11 +165,11 @@ func (m *MountOpt) Set(value string) error { } if mount.Type == "" { - return fmt.Errorf("type is required") + return errors.New("type is required") } if mount.Target == "" { - return fmt.Errorf("target is required") + return errors.New("target is required") } if mount.VolumeOptions != nil && mount.Type != mounttypes.TypeVolume { diff --git a/opts/network.go b/opts/network.go index e36ef405d121..413aec7b52e6 100644 --- a/opts/network.go +++ b/opts/network.go @@ -2,6 +2,7 @@ package opts import ( "encoding/csv" + "errors" "fmt" "regexp" "strings" @@ -83,11 +84,11 @@ func (n *NetworkOpt) Set(value string) error { //nolint:gocyclo } netOpt.DriverOpts[key] = val default: - return fmt.Errorf("invalid field key %s", key) + return errors.New("invalid field key " + key) } } if len(netOpt.Target) == 0 { - return fmt.Errorf("network name/id is not specified") + return errors.New("network name/id is not specified") } } else { netOpt.Target = value @@ -126,7 +127,7 @@ func parseDriverOpt(driverOpt string) (string, string, error) { // TODO(thaJeztah): should value be converted to lowercase as well, or only the key? key, value, ok := strings.Cut(strings.ToLower(driverOpt), "=") if !ok || key == "" { - return "", "", fmt.Errorf("invalid key value pair format in driver options") + return "", "", errors.New("invalid key value pair format in driver options") } key = strings.TrimSpace(key) value = strings.TrimSpace(value) diff --git a/opts/opts.go b/opts/opts.go index 80de16052c62..254d7eb12853 100644 --- a/opts/opts.go +++ b/opts/opts.go @@ -401,7 +401,7 @@ func ParseCPUs(value string) (int64, error) { } nano := cpu.Mul(cpu, big.NewRat(1e9, 1)) if !nano.IsInt() { - return 0, fmt.Errorf("value is too precise") + return 0, errors.New("value is too precise") } return nano.Num().Int64(), nil } @@ -409,14 +409,14 @@ func ParseCPUs(value string) (int64, error) { // ParseLink parses and validates the specified string as a link format (name:alias) func ParseLink(val string) (string, string, error) { if val == "" { - return "", "", fmt.Errorf("empty string specified for links") + return "", "", errors.New("empty string specified for links") } // We expect two parts, but restrict to three to allow detecting invalid formats. arr := strings.SplitN(val, ":", 3) // TODO(thaJeztah): clean up this logic!! if len(arr) > 2 { - return "", "", fmt.Errorf("bad format for links: %s", val) + return "", "", errors.New("bad format for links: " + val) } // TODO(thaJeztah): this should trim the "/" prefix as well?? if len(arr) == 1 { diff --git a/opts/parse.go b/opts/parse.go index 381648fe7344..584b55ef61f4 100644 --- a/opts/parse.go +++ b/opts/parse.go @@ -1,7 +1,7 @@ package opts import ( - "fmt" + "errors" "os" "strconv" "strings" @@ -81,12 +81,12 @@ func ParseRestartPolicy(policy string) (container.RestartPolicy, error) { p := container.RestartPolicy{} k, v, ok := strings.Cut(policy, ":") if ok && k == "" { - return container.RestartPolicy{}, fmt.Errorf("invalid restart policy format: no policy provided before colon") + return container.RestartPolicy{}, errors.New("invalid restart policy format: no policy provided before colon") } if v != "" { count, err := strconv.Atoi(v) if err != nil { - return container.RestartPolicy{}, fmt.Errorf("invalid restart policy format: maximum retry count must be an integer") + return container.RestartPolicy{}, errors.New("invalid restart policy format: maximum retry count must be an integer") } p.MaximumRetryCount = count } diff --git a/opts/port.go b/opts/port.go index fe41cdd2881f..2f2aa329c8ee 100644 --- a/opts/port.go +++ b/opts/port.go @@ -2,6 +2,7 @@ package opts import ( "encoding/csv" + "errors" "fmt" "net" "regexp" @@ -102,7 +103,7 @@ func (p *PortOpt) Set(value string) error { for _, portBindings := range portBindingMap { for _, portBinding := range portBindings { if portBinding.HostIP != "" { - return fmt.Errorf("hostip is not supported") + return errors.New("hostip is not supported") } } } diff --git a/opts/secret.go b/opts/secret.go index 750dbe4f301d..09d2b2b3be0f 100644 --- a/opts/secret.go +++ b/opts/secret.go @@ -2,6 +2,7 @@ package opts import ( "encoding/csv" + "errors" "fmt" "os" "strconv" @@ -62,12 +63,12 @@ func (o *SecretOpt) Set(value string) error { options.File.Mode = os.FileMode(m) default: - return fmt.Errorf("invalid field in secret request: %s", key) + return errors.New("invalid field in secret request: " + key) } } if options.SecretName == "" { - return fmt.Errorf("source is required") + return errors.New("source is required") } if options.File.Name == "" { options.File.Name = options.SecretName