linting: address else/if/elseif statements found by gocritic

cli/command/formatter/tabwriter/tabwriter.go:579:10: elseif: can replace 'else {if cond {}}' with 'else if cond {}' (gocritic)
              } else {
                     ^
    cli/connhelper/connhelper.go:43:2: singleCaseSwitch: should rewrite switch statement to if statement (gocritic)
    	switch scheme := u.Scheme; scheme {
    	^
    cli/compose/loader/loader.go:666:10: elseif: can replace 'else {if cond {}}' with 'else if cond {}' (gocritic)
    		} else {
    		       ^
    opts/hosts_test.go:173:10: elseif: can replace 'else {if cond {}}' with 'else if cond {}' (gocritic)
    		} else {
    		       ^
    cli-plugins/manager/candidate_test.go:78:4: ifElseChain: rewrite if-else to switch statement (gocritic)
    			if tc.err != "" {
    			^
    cli/command/checkpoint/formatter.go:15:2: singleCaseSwitch: should rewrite switch statement to if statement (gocritic)
    	switch source {
    	^
    cli/command/image/formatter_history.go:25:2: singleCaseSwitch: should rewrite switch statement to if statement (gocritic)
    	switch source {
    	^
    cli/command/service/scale.go:107:2: ifElseChain: rewrite if-else to switch statement (gocritic)
    	if serviceMode.Replicated != nil {
    	^
    cli/command/service/update.go:804:9: elseif: can replace 'else {if cond {}}' with 'else if cond {}' (gocritic)
    	} else {
    	       ^
    cli/command/service/update.go:222:2: ifElseChain: rewrite if-else to switch statement (gocritic)
    	if sendAuth {
    	^
    cli/command/container/formatter_diff.go:17:2: singleCaseSwitch: should rewrite switch statement to if statement (gocritic)
    	switch source {
    	^
    cli/command/container/start.go:79:2: ifElseChain: rewrite if-else to switch statement (gocritic)
    	if opts.Attach || opts.OpenStdin {
    	^
    cli/command/container/utils.go:84:11: elseif: can replace 'else {if cond {}}' with 'else if cond {}' (gocritic)
    			} else {
    			       ^
    cli/command/container/exec_test.go:200:11: elseif: can replace 'else {if cond {}}' with 'else if cond {}' (gocritic)
    			} else {
    			       ^
    cli/command/container/logs_test.go:52:11: elseif: can replace 'else {if cond {}}' with 'else if cond {}' (gocritic)
    			} else {
    			       ^
    cli/command/container/opts_test.go:1014:10: elseif: can replace 'else {if cond {}}' with 'else if cond {}' (gocritic)
    		} else {
    		       ^
    cli/command/system/info.go:297:7: singleCaseSwitch: should rewrite switch statement to if statement (gocritic)
    						switch o.Key {
    						^
    cli/command/system/version.go:164:4: singleCaseSwitch: should rewrite switch statement to if statement (gocritic)
    			switch component.Name {
    			^
    cli/command/system/info_test.go:478:4: ifElseChain: rewrite if-else to switch statement (gocritic)
    			if tc.expectedOut != "" {
    			^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2023-11-20 13:54:53 +01:00
parent 888df09879
commit a2c9f3c6ce
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C
18 changed files with 54 additions and 71 deletions

View File

@ -75,13 +75,14 @@ func TestValidateCandidate(t *testing.T) {
} { } {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
p, err := newPlugin(tc.c, fakeroot.Commands()) p, err := newPlugin(tc.c, fakeroot.Commands())
if tc.err != "" { switch {
case tc.err != "":
assert.ErrorContains(t, err, tc.err) assert.ErrorContains(t, err, tc.err)
} else if tc.invalid != "" { case tc.invalid != "":
assert.NilError(t, err) assert.NilError(t, err)
assert.Assert(t, cmp.ErrorType(p.Err, reflect.TypeOf(&pluginError{}))) assert.Assert(t, cmp.ErrorType(p.Err, reflect.TypeOf(&pluginError{})))
assert.ErrorContains(t, p.Err, tc.invalid) assert.ErrorContains(t, p.Err, tc.invalid)
} else { default:
assert.NilError(t, err) assert.NilError(t, err)
assert.Equal(t, NamePrefix+p.Name, goodPluginName) assert.Equal(t, NamePrefix+p.Name, goodPluginName)
assert.Equal(t, p.SchemaVersion, "0.1.0") assert.Equal(t, p.SchemaVersion, "0.1.0")

View File

@ -12,8 +12,7 @@ const (
// NewFormat returns a format for use with a checkpoint Context // NewFormat returns a format for use with a checkpoint Context
func NewFormat(source string) formatter.Format { func NewFormat(source string) formatter.Format {
switch source { if source == formatter.TableFormatKey {
case formatter.TableFormatKey:
return defaultCheckpointFormat return defaultCheckpointFormat
} }
return formatter.Format(source) return formatter.Format(source)

View File

@ -197,11 +197,9 @@ func TestRunExec(t *testing.T) {
err := RunExec(context.Background(), cli, "thecontainer", testcase.options) err := RunExec(context.Background(), cli, "thecontainer", testcase.options)
if testcase.expectedError != "" { if testcase.expectedError != "" {
assert.ErrorContains(t, err, testcase.expectedError) assert.ErrorContains(t, err, testcase.expectedError)
} else { } else if !assert.Check(t, err) {
if !assert.Check(t, err) {
return return
} }
}
assert.Check(t, is.Equal(testcase.expectedOut, cli.OutBuffer().String())) assert.Check(t, is.Equal(testcase.expectedOut, cli.OutBuffer().String()))
assert.Check(t, is.Equal(testcase.expectedErr, cli.ErrBuffer().String())) assert.Check(t, is.Equal(testcase.expectedErr, cli.ErrBuffer().String()))
}) })

View File

@ -14,8 +14,7 @@ const (
// NewDiffFormat returns a format for use with a diff Context // NewDiffFormat returns a format for use with a diff Context
func NewDiffFormat(source string) formatter.Format { func NewDiffFormat(source string) formatter.Format {
switch source { if source == formatter.TableFormatKey {
case formatter.TableFormatKey:
return defaultDiffTableFormat return defaultDiffTableFormat
} }
return formatter.Format(source) return formatter.Format(source)

View File

@ -49,11 +49,9 @@ func TestRunLogs(t *testing.T) {
err := runLogs(cli, testcase.options) err := runLogs(cli, testcase.options)
if testcase.expectedError != "" { if testcase.expectedError != "" {
assert.ErrorContains(t, err, testcase.expectedError) assert.ErrorContains(t, err, testcase.expectedError)
} else { } else if !assert.Check(t, err) {
if !assert.Check(t, err) {
return return
} }
}
assert.Check(t, is.Equal(testcase.expectedOut, cli.OutBuffer().String())) assert.Check(t, is.Equal(testcase.expectedOut, cli.OutBuffer().String()))
assert.Check(t, is.Equal(testcase.expectedErr, cli.ErrBuffer().String())) assert.Check(t, is.Equal(testcase.expectedErr, cli.ErrBuffer().String()))
}) })

View File

@ -1011,12 +1011,10 @@ func TestValidateDevice(t *testing.T) {
for path, expectedError := range invalid { for path, expectedError := range invalid {
if _, err := validateDevice(path, runtime.GOOS); err == nil { if _, err := validateDevice(path, runtime.GOOS); err == nil {
t.Fatalf("ValidateDevice(`%q`) should have failed validation", path) t.Fatalf("ValidateDevice(`%q`) should have failed validation", path)
} else { } else if err.Error() != expectedError {
if err.Error() != expectedError {
t.Fatalf("ValidateDevice(`%q`) error should contain %q, got %q", path, expectedError, err.Error()) t.Fatalf("ValidateDevice(`%q`) error should contain %q, got %q", path, expectedError, err.Error())
} }
} }
}
} }
func TestParseSystemPaths(t *testing.T) { func TestParseSystemPaths(t *testing.T) {

View File

@ -76,7 +76,8 @@ func RunStart(dockerCli command.Cli, opts *StartOptions) error {
ctx, cancelFun := context.WithCancel(context.Background()) ctx, cancelFun := context.WithCancel(context.Background())
defer cancelFun() defer cancelFun()
if opts.Attach || opts.OpenStdin { switch {
case opts.Attach || opts.OpenStdin:
// We're going to attach to a container. // We're going to attach to a container.
// 1. Ensure we only have one container. // 1. Ensure we only have one container.
if len(opts.Containers) > 1 { if len(opts.Containers) > 1 {
@ -180,7 +181,8 @@ func RunStart(dockerCli command.Cli, opts *StartOptions) error {
if status := <-statusChan; status != 0 { if status := <-statusChan; status != 0 {
return cli.StatusError{StatusCode: status} return cli.StatusError{StatusCode: status}
} }
} else if opts.Checkpoint != "" { return nil
case opts.Checkpoint != "":
if len(opts.Containers) > 1 { if len(opts.Containers) > 1 {
return errors.New("you cannot restore multiple containers at once") return errors.New("you cannot restore multiple containers at once")
} }
@ -189,14 +191,11 @@ func RunStart(dockerCli command.Cli, opts *StartOptions) error {
CheckpointID: opts.Checkpoint, CheckpointID: opts.Checkpoint,
CheckpointDir: opts.CheckpointDir, CheckpointDir: opts.CheckpointDir,
}) })
default:
} else {
// We're not going to attach to anything. // We're not going to attach to anything.
// Start as many containers as we want. // Start as many containers as we want.
return startContainersWithoutAttachments(ctx, dockerCli, opts.Containers) return startContainersWithoutAttachments(ctx, dockerCli, opts.Containers)
} }
return nil
} }
func startContainersWithoutAttachments(ctx context.Context, dockerCli command.Cli, containers []string) error { func startContainersWithoutAttachments(ctx context.Context, dockerCli command.Cli, containers []string) error {

View File

@ -81,10 +81,9 @@ func legacyWaitExitOrRemoved(ctx context.Context, apiClient client.APIClient, co
} }
if !waitRemove { if !waitRemove {
stopProcessing = true stopProcessing = true
} else { } else if versions.LessThan(apiClient.ClientVersion(), "1.25") {
// If we are talking to an older daemon, `AutoRemove` is not supported. // If we are talking to an older daemon, `AutoRemove` is not supported.
// We need to fall back to the old behavior, which is client-side removal // We need to fall back to the old behavior, which is client-side removal
if versions.LessThan(apiClient.ClientVersion(), "1.25") {
go func() { go func() {
removeErr = apiClient.ContainerRemove(ctx, containerID, container.RemoveOptions{RemoveVolumes: true}) removeErr = apiClient.ContainerRemove(ctx, containerID, container.RemoveOptions{RemoveVolumes: true})
if removeErr != nil { if removeErr != nil {
@ -93,7 +92,6 @@ func legacyWaitExitOrRemoved(ctx context.Context, apiClient client.APIClient, co
} }
}() }()
} }
}
case "detach": case "detach":
exitCode = 0 exitCode = 0
stopProcessing = true stopProcessing = true

View File

@ -576,9 +576,8 @@ func (b *Writer) Write(buf []byte) (n int, err error) {
b.startEscape(ch) b.startEscape(ch)
} }
} }
} else { } else if ch == b.endChar {
// inside escape // inside escape
if ch == b.endChar {
// end of tag/entity // end of tag/entity
j := i + 1 j := i + 1
if ch == Escape && b.flags&StripEscape != 0 { if ch == Escape && b.flags&StripEscape != 0 {
@ -589,7 +588,6 @@ func (b *Writer) Write(buf []byte) (n int, err error) {
b.endEscape() b.endEscape()
} }
} }
}
// append leftover text // append leftover text
b.append(buf[n:]) b.append(buf[n:])

View File

@ -22,8 +22,7 @@ const (
// NewHistoryFormat returns a format for rendering an HistoryContext // NewHistoryFormat returns a format for rendering an HistoryContext
func NewHistoryFormat(source string, quiet bool, human bool) formatter.Format { func NewHistoryFormat(source string, quiet bool, human bool) formatter.Format {
switch source { if source == formatter.TableFormatKey {
case formatter.TableFormatKey:
switch { switch {
case quiet: case quiet:
return formatter.DefaultQuietFormat return formatter.DefaultQuietFormat

View File

@ -104,11 +104,12 @@ func runServiceScale(ctx context.Context, dockerCli command.Cli, serviceID strin
} }
serviceMode := &service.Spec.Mode serviceMode := &service.Spec.Mode
if serviceMode.Replicated != nil { switch {
case serviceMode.Replicated != nil:
serviceMode.Replicated.Replicas = &scale serviceMode.Replicated.Replicas = &scale
} else if serviceMode.ReplicatedJob != nil { case serviceMode.ReplicatedJob != nil:
serviceMode.ReplicatedJob.TotalCompletions = &scale serviceMode.ReplicatedJob.TotalCompletions = &scale
} else { default:
return errors.Errorf("scale can only be used with replicated or replicated-job mode") return errors.Errorf("scale can only be used with replicated or replicated-job mode")
} }

View File

@ -219,7 +219,8 @@ func runUpdate(dockerCli command.Cli, flags *pflag.FlagSet, options *serviceOpti
if err != nil { if err != nil {
return err return err
} }
if sendAuth { switch {
case sendAuth:
// Retrieve encoded auth token from the image reference // Retrieve encoded auth token from the image reference
// This would be the old image if it didn't change in this update // This would be the old image if it didn't change in this update
image := spec.TaskTemplate.ContainerSpec.Image image := spec.TaskTemplate.ContainerSpec.Image
@ -228,9 +229,9 @@ func runUpdate(dockerCli command.Cli, flags *pflag.FlagSet, options *serviceOpti
return err return err
} }
updateOpts.EncodedRegistryAuth = encodedAuth updateOpts.EncodedRegistryAuth = encodedAuth
} else if clientSideRollback { case clientSideRollback:
updateOpts.RegistryAuthFrom = types.RegistryAuthFromPreviousSpec updateOpts.RegistryAuthFrom = types.RegistryAuthFromPreviousSpec
} else { default:
updateOpts.RegistryAuthFrom = types.RegistryAuthFromSpec updateOpts.RegistryAuthFrom = types.RegistryAuthFromSpec
} }
@ -801,7 +802,7 @@ func getUpdatedConfigs(apiClient client.ConfigAPIClient, flags *pflag.FlagSet, s
if flags.Changed(flagCredentialSpec) { if flags.Changed(flagCredentialSpec) {
credSpec := flags.Lookup(flagCredentialSpec).Value.(*credentialSpecOpt).Value() credSpec := flags.Lookup(flagCredentialSpec).Value.(*credentialSpecOpt).Value()
credSpecConfigName = credSpec.Config credSpecConfigName = credSpec.Config
} else { } else { //nolint:gocritic // ignore elseif: can replace 'else {if cond {}}' with 'else if cond {}'
// if the credential spec flag has not changed, then check if there // if the credential spec flag has not changed, then check if there
// already is a credentialSpec. if there is one, and it's for a Config, // already is a credentialSpec. if there is one, and it's for a Config,
// then it's from the old object, and its value is the config ID. we // then it's from the old object, and its value is the config ID. we

View File

@ -294,8 +294,7 @@ func prettyPrintServerInfo(streams command.Streams, info *info) []error {
for _, so := range kvs { for _, so := range kvs {
fprintln(output, " "+so.Name) fprintln(output, " "+so.Name)
for _, o := range so.Options { for _, o := range so.Options {
switch o.Key { if o.Key == "profile" {
case "profile":
fprintln(output, " Profile:", o.Value) fprintln(output, " Profile:", o.Value)
} }
} }

View File

@ -475,12 +475,13 @@ func TestFormatInfo(t *testing.T) {
ClientInfo: &clientInfo{Debug: true}, ClientInfo: &clientInfo{Debug: true},
} }
err := formatInfo(cli.Out(), info, tc.template) err := formatInfo(cli.Out(), info, tc.template)
if tc.expectedOut != "" { switch {
case tc.expectedOut != "":
assert.NilError(t, err) assert.NilError(t, err)
assert.Equal(t, cli.OutBuffer().String(), tc.expectedOut) assert.Equal(t, cli.OutBuffer().String(), tc.expectedOut)
} else if tc.expectedError != "" { case tc.expectedError != "":
assert.Error(t, err, tc.expectedError) assert.Error(t, err, tc.expectedError)
} else { default:
t.Fatal("test expected to neither pass nor fail") t.Fatal("test expected to neither pass nor fail")
} }
}) })

View File

@ -161,8 +161,7 @@ func runVersion(dockerCli command.Cli, opts *versionOptions) error {
vd.Server = &sv vd.Server = &sv
foundEngine := false foundEngine := false
for _, component := range sv.Components { for _, component := range sv.Components {
switch component.Name { if component.Name == "Engine" {
case "Engine":
foundEngine = true foundEngine = true
buildTime, ok := component.Details["BuildTime"] buildTime, ok := component.Details["BuildTime"]
if ok { if ok {

View File

@ -663,11 +663,9 @@ func loadFileObjectConfig(name string, objType string, obj types.FileObjectConfi
} }
obj.Name = obj.External.Name obj.Name = obj.External.Name
obj.External.Name = "" obj.External.Name = ""
} else { } else if obj.Name == "" {
if obj.Name == "" {
obj.Name = name obj.Name = name
} }
}
// if not "external: true" // if not "external: true"
case obj.Driver != "": case obj.Driver != "":
if obj.File != "" { if obj.File != "" {

View File

@ -40,8 +40,7 @@ func getConnectionHelper(daemonURL string, sshFlags []string) (*ConnectionHelper
if err != nil { if err != nil {
return nil, err return nil, err
} }
switch scheme := u.Scheme; scheme { if u.Scheme == "ssh" {
case "ssh":
sp, err := ssh.ParseURL(daemonURL) sp, err := ssh.ParseURL(daemonURL)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "ssh host connection is not valid") return nil, errors.Wrap(err, "ssh host connection is not valid")

View File

@ -170,10 +170,8 @@ func TestValidateExtraHosts(t *testing.T) {
for extraHost, expectedError := range invalid { for extraHost, expectedError := range invalid {
if _, err := ValidateExtraHost(extraHost); err == nil { if _, err := ValidateExtraHost(extraHost); err == nil {
t.Fatalf("ValidateExtraHost(`%q`) should have failed validation", extraHost) t.Fatalf("ValidateExtraHost(`%q`) should have failed validation", extraHost)
} else { } else if !strings.Contains(err.Error(), expectedError) {
if !strings.Contains(err.Error(), expectedError) {
t.Fatalf("ValidateExtraHost(`%q`) error should contain %q", extraHost, expectedError) t.Fatalf("ValidateExtraHost(`%q`) error should contain %q", extraHost, expectedError)
} }
} }
}
} }