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) {
p, err := newPlugin(tc.c, fakeroot.Commands())
if tc.err != "" {
switch {
case tc.err != "":
assert.ErrorContains(t, err, tc.err)
} else if tc.invalid != "" {
case tc.invalid != "":
assert.NilError(t, err)
assert.Assert(t, cmp.ErrorType(p.Err, reflect.TypeOf(&pluginError{})))
assert.ErrorContains(t, p.Err, tc.invalid)
} else {
default:
assert.NilError(t, err)
assert.Equal(t, NamePrefix+p.Name, goodPluginName)
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
func NewFormat(source string) formatter.Format {
switch source {
case formatter.TableFormatKey:
if source == formatter.TableFormatKey {
return defaultCheckpointFormat
}
return formatter.Format(source)

View File

@ -197,10 +197,8 @@ func TestRunExec(t *testing.T) {
err := RunExec(context.Background(), cli, "thecontainer", testcase.options)
if testcase.expectedError != "" {
assert.ErrorContains(t, err, testcase.expectedError)
} else {
if !assert.Check(t, err) {
return
}
} else if !assert.Check(t, err) {
return
}
assert.Check(t, is.Equal(testcase.expectedOut, cli.OutBuffer().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
func NewDiffFormat(source string) formatter.Format {
switch source {
case formatter.TableFormatKey:
if source == formatter.TableFormatKey {
return defaultDiffTableFormat
}
return formatter.Format(source)

View File

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

View File

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

View File

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

View File

@ -81,18 +81,16 @@ func legacyWaitExitOrRemoved(ctx context.Context, apiClient client.APIClient, co
}
if !waitRemove {
stopProcessing = true
} else {
} else if versions.LessThan(apiClient.ClientVersion(), "1.25") {
// 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
if versions.LessThan(apiClient.ClientVersion(), "1.25") {
go func() {
removeErr = apiClient.ContainerRemove(ctx, containerID, container.RemoveOptions{RemoveVolumes: true})
if removeErr != nil {
logrus.Errorf("error removing container: %v", removeErr)
cancel() // cancel the event Q
}
}()
}
go func() {
removeErr = apiClient.ContainerRemove(ctx, containerID, container.RemoveOptions{RemoveVolumes: true})
if removeErr != nil {
logrus.Errorf("error removing container: %v", removeErr)
cancel() // cancel the event Q
}
}()
}
case "detach":
exitCode = 0

View File

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

View File

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

View File

@ -104,11 +104,12 @@ func runServiceScale(ctx context.Context, dockerCli command.Cli, serviceID strin
}
serviceMode := &service.Spec.Mode
if serviceMode.Replicated != nil {
switch {
case serviceMode.Replicated != nil:
serviceMode.Replicated.Replicas = &scale
} else if serviceMode.ReplicatedJob != nil {
case serviceMode.ReplicatedJob != nil:
serviceMode.ReplicatedJob.TotalCompletions = &scale
} else {
default:
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 {
return err
}
if sendAuth {
switch {
case sendAuth:
// Retrieve encoded auth token from the image reference
// This would be the old image if it didn't change in this update
image := spec.TaskTemplate.ContainerSpec.Image
@ -228,9 +229,9 @@ func runUpdate(dockerCli command.Cli, flags *pflag.FlagSet, options *serviceOpti
return err
}
updateOpts.EncodedRegistryAuth = encodedAuth
} else if clientSideRollback {
case clientSideRollback:
updateOpts.RegistryAuthFrom = types.RegistryAuthFromPreviousSpec
} else {
default:
updateOpts.RegistryAuthFrom = types.RegistryAuthFromSpec
}
@ -801,7 +802,7 @@ func getUpdatedConfigs(apiClient client.ConfigAPIClient, flags *pflag.FlagSet, s
if flags.Changed(flagCredentialSpec) {
credSpec := flags.Lookup(flagCredentialSpec).Value.(*credentialSpecOpt).Value()
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
// 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

View File

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

View File

@ -475,12 +475,13 @@ func TestFormatInfo(t *testing.T) {
ClientInfo: &clientInfo{Debug: true},
}
err := formatInfo(cli.Out(), info, tc.template)
if tc.expectedOut != "" {
switch {
case tc.expectedOut != "":
assert.NilError(t, err)
assert.Equal(t, cli.OutBuffer().String(), tc.expectedOut)
} else if tc.expectedError != "" {
case tc.expectedError != "":
assert.Error(t, err, tc.expectedError)
} else {
default:
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
foundEngine := false
for _, component := range sv.Components {
switch component.Name {
case "Engine":
if component.Name == "Engine" {
foundEngine = true
buildTime, ok := component.Details["BuildTime"]
if ok {

View File

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

View File

@ -40,8 +40,7 @@ func getConnectionHelper(daemonURL string, sshFlags []string) (*ConnectionHelper
if err != nil {
return nil, err
}
switch scheme := u.Scheme; scheme {
case "ssh":
if u.Scheme == "ssh" {
sp, err := ssh.ParseURL(daemonURL)
if err != nil {
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 {
if _, err := ValidateExtraHost(extraHost); err == nil {
t.Fatalf("ValidateExtraHost(`%q`) should have failed validation", extraHost)
} else {
if !strings.Contains(err.Error(), expectedError) {
t.Fatalf("ValidateExtraHost(`%q`) error should contain %q", extraHost, expectedError)
}
} else if !strings.Contains(err.Error(), expectedError) {
t.Fatalf("ValidateExtraHost(`%q`) error should contain %q", extraHost, expectedError)
}
}
}