Merge pull request #4055 from corhere/20.10_backport_update_golangci_lint_v1.49.0

[20.10 backport] Prepare for Go 1.19 upgrade
This commit is contained in:
Sebastiaan van Stijn 2023-03-02 14:30:29 +01:00 committed by GitHub
commit 44c3028550
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
192 changed files with 792 additions and 1121 deletions

View File

@ -1,7 +1,6 @@
linters: linters:
enable: enable:
- bodyclose - bodyclose
- deadcode
- dogsled - dogsled
- gocyclo - gocyclo
- goimports - goimports
@ -13,14 +12,12 @@ linters:
- megacheck - megacheck
- misspell - misspell
- nakedret - nakedret
- revive
- staticcheck - staticcheck
- structcheck
- typecheck - typecheck
- unconvert - unconvert
- unparam - unparam
- unused - unused
- revive
- varcheck
disable: disable:
- errcheck - errcheck
@ -93,6 +90,12 @@ issues:
linters: linters:
- gosec - gosec
# G113 Potential uncontrolled memory consumption in Rat.SetString (CVE-2022-23772)
# only affects gp < 1.16.14. and go < 1.17.7
- text: "(G113)"
linters:
- gosec
# Looks like the match in "EXC0007" above doesn't catch this one # Looks like the match in "EXC0007" above doesn't catch this one
# TODO: consider upstreaming this to golangci-lint's default exclusion rules # TODO: consider upstreaming this to golangci-lint's default exclusion rules
- text: "G204: Subprocess launched with a potential tainted input or cmd arguments" - text: "G204: Subprocess launched with a potential tainted input or cmd arguments"
@ -104,12 +107,23 @@ issues:
linters: linters:
- gosec - gosec
# TODO: make sure all packages have a description. Currently, there's 67 packages without.
- text: "package-comments: should have a package comment"
linters:
- revive
# Exclude some linters from running on tests files. # Exclude some linters from running on tests files.
- path: _test\.go - path: _test\.go
linters: linters:
- errcheck - errcheck
- gosec - gosec
# Fixing these lints would change user-facing output, which would be
# undesirable to introduce in a patch release.
- text: "ST1005: error strings should not be capitalized"
linters:
- stylecheck
# Maximum issues count per one linter. Set to 0 to disable. Default is 50. # Maximum issues count per one linter. Set to 0 to disable. Default is 50.
max-issues-per-linter: 0 max-issues-per-linter: 0

View File

@ -1,7 +1,6 @@
package manager package manager
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"sort" "sort"
@ -57,12 +56,12 @@ func getPluginDirs(dockerCli command.Cli) ([]string, error) {
} }
func addPluginCandidatesFromDir(res map[string][]string, d string) error { func addPluginCandidatesFromDir(res map[string][]string, d string) error {
dentries, err := ioutil.ReadDir(d) dentries, err := os.ReadDir(d)
if err != nil { if err != nil {
return err return err
} }
for _, dentry := range dentries { for _, dentry := range dentries {
switch dentry.Mode() & os.ModeType { switch dentry.Type() & os.ModeType {
case 0, os.ModeSymlink: case 0, os.ModeSymlink:
// Regular file or symlink, keep going // Regular file or symlink, keep going
default: default:

View File

@ -33,8 +33,6 @@ type Plugin struct {
// is set, and is always a `pluginError`, but the `Plugin` is still // is set, and is always a `pluginError`, but the `Plugin` is still
// returned with no error. An error is only returned due to a // returned with no error. An error is only returned due to a
// non-recoverable error. // non-recoverable error.
//
// nolint: gocyclo
func newPlugin(c Candidate, rootcmd *cobra.Command) (Plugin, error) { func newPlugin(c Candidate, rootcmd *cobra.Command) (Plugin, error) {
path := c.Path() path := c.Path()
if path == "" { if path == "" {

View File

@ -1,7 +1,7 @@
package checkpoint package checkpoint
import ( import (
"io/ioutil" "io"
"strings" "strings"
"testing" "testing"
@ -41,7 +41,7 @@ func TestCheckpointCreateErrors(t *testing.T) {
}) })
cmd := newCreateCommand(cli) cmd := newCreateCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -1,7 +1,7 @@
package checkpoint package checkpoint
import ( import (
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -41,7 +41,7 @@ func TestCheckpointListErrors(t *testing.T) {
}) })
cmd := newListCommand(cli) cmd := newListCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -1,7 +1,7 @@
package checkpoint package checkpoint
import ( import (
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -40,7 +40,7 @@ func TestCheckpointRemoveErrors(t *testing.T) {
}) })
cmd := newRemoveCommand(cli) cmd := newRemoveCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -3,7 +3,6 @@ package command
import ( import (
"context" "context"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -279,7 +278,7 @@ func NewAPIClientFromFlags(opts *cliflags.CommonOptions, configFile *configfile.
store := &ContextStoreWithDefault{ store := &ContextStoreWithDefault{
Store: store.New(cliconfig.ContextStoreDir(), storeConfig), Store: store.New(cliconfig.ContextStoreDir(), storeConfig),
Resolver: func() (*DefaultContext, error) { Resolver: func() (*DefaultContext, error) {
return ResolveDefaultContext(opts, configFile, storeConfig, ioutil.Discard) return ResolveDefaultContext(opts, configFile, storeConfig, io.Discard)
}, },
} }
contextName, err := resolveContextName(opts, configFile, store) contextName, err := resolveContextName(opts, configFile, store)

View File

@ -15,23 +15,13 @@ func contentTrustEnabled(t *testing.T) bool {
// NB: Do not t.Parallel() this test -- it messes with the process environment. // NB: Do not t.Parallel() this test -- it messes with the process environment.
func TestWithContentTrustFromEnv(t *testing.T) { func TestWithContentTrustFromEnv(t *testing.T) {
envvar := "DOCKER_CONTENT_TRUST" const envvar = "DOCKER_CONTENT_TRUST"
if orig, ok := os.LookupEnv(envvar); ok { t.Setenv(envvar, "true")
defer func() { assert.Check(t, contentTrustEnabled(t))
os.Setenv(envvar, orig) t.Setenv(envvar, "false")
}() assert.Check(t, !contentTrustEnabled(t))
} else { t.Setenv(envvar, "invalid")
defer func() { assert.Check(t, contentTrustEnabled(t))
os.Unsetenv(envvar)
}()
}
os.Setenv(envvar, "true")
assert.Assert(t, contentTrustEnabled(t))
os.Setenv(envvar, "false")
assert.Assert(t, !contentTrustEnabled(t))
os.Setenv(envvar, "invalid")
assert.Assert(t, contentTrustEnabled(t))
os.Unsetenv(envvar) os.Unsetenv(envvar)
assert.Assert(t, !contentTrustEnabled(t)) assert.Check(t, !contentTrustEnabled(t))
} }

View File

@ -5,7 +5,7 @@ import (
"context" "context"
"crypto/x509" "crypto/x509"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"runtime" "runtime"
"testing" "testing"
@ -275,23 +275,23 @@ func TestNewDockerCliAndOperators(t *testing.T) {
outbuf := bytes.NewBuffer(nil) outbuf := bytes.NewBuffer(nil)
errbuf := bytes.NewBuffer(nil) errbuf := bytes.NewBuffer(nil)
err = cli.Apply( err = cli.Apply(
WithInputStream(ioutil.NopCloser(inbuf)), WithInputStream(io.NopCloser(inbuf)),
WithOutputStream(outbuf), WithOutputStream(outbuf),
WithErrorStream(errbuf), WithErrorStream(errbuf),
) )
assert.NilError(t, err) assert.NilError(t, err)
// Check input stream // Check input stream
inputStream, err := ioutil.ReadAll(cli.In()) inputStream, err := io.ReadAll(cli.In())
assert.NilError(t, err) assert.NilError(t, err)
assert.Equal(t, string(inputStream), "input") assert.Equal(t, string(inputStream), "input")
// Check output stream // Check output stream
fmt.Fprintf(cli.Out(), "output") fmt.Fprintf(cli.Out(), "output")
outputStream, err := ioutil.ReadAll(outbuf) outputStream, err := io.ReadAll(outbuf)
assert.NilError(t, err) assert.NilError(t, err)
assert.Equal(t, string(outputStream), "output") assert.Equal(t, string(outputStream), "output")
// Check error stream // Check error stream
fmt.Fprintf(cli.Err(), "error") fmt.Fprintf(cli.Err(), "error")
errStream, err := ioutil.ReadAll(errbuf) errStream, err := io.ReadAll(errbuf)
assert.NilError(t, err) assert.NilError(t, err)
assert.Equal(t, string(errStream), "error") assert.Equal(t, string(errStream), "error")
} }

View File

@ -4,7 +4,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"github.com/docker/cli/cli" "github.com/docker/cli/cli"
"github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command"
@ -61,7 +60,7 @@ func RunConfigCreate(dockerCli command.Cli, options CreateOptions) error {
defer file.Close() defer file.Close()
} }
configData, err := ioutil.ReadAll(in) configData, err := io.ReadAll(in)
if err != nil { if err != nil {
return errors.Errorf("Error reading content from %q: %v", options.File, err) return errors.Errorf("Error reading content from %q: %v", options.File, err)
} }

View File

@ -1,7 +1,8 @@
package config package config
import ( import (
"io/ioutil" "io"
"os"
"path/filepath" "path/filepath"
"reflect" "reflect"
"strings" "strings"
@ -46,7 +47,7 @@ func TestConfigCreateErrors(t *testing.T) {
}), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
@ -82,7 +83,7 @@ func TestConfigCreateWithLabels(t *testing.T) {
} }
name := "foo" name := "foo"
data, err := ioutil.ReadFile(filepath.Join("testdata", configDataFile)) data, err := os.ReadFile(filepath.Join("testdata", configDataFile))
assert.NilError(t, err) assert.NilError(t, err)
expected := swarm.ConfigSpec{ expected := swarm.ConfigSpec{

View File

@ -2,7 +2,7 @@ package config
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"time" "time"
@ -59,7 +59,7 @@ func TestConfigInspectErrors(t *testing.T) {
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -1,7 +1,7 @@
package config package config
import ( import (
"io/ioutil" "io"
"testing" "testing"
"time" "time"
@ -40,7 +40,7 @@ func TestConfigListErrors(t *testing.T) {
}), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -1,7 +1,7 @@
package config package config
import ( import (
"io/ioutil" "io"
"strings" "strings"
"testing" "testing"
@ -36,7 +36,7 @@ func TestConfigRemoveErrors(t *testing.T) {
}), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
@ -73,7 +73,7 @@ func TestConfigRemoveContinueAfterError(t *testing.T) {
cmd := newConfigRemoveCommand(cli) cmd := newConfigRemoveCommand(cli)
cmd.SetArgs(names) cmd.SetArgs(names)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.Error(t, cmd.Execute(), "error removing config: foo") assert.Error(t, cmd.Execute(), "error removing config: foo")
assert.Check(t, is.DeepEqual(names, removedConfigs)) assert.Check(t, is.DeepEqual(names, removedConfigs))
} }

View File

@ -2,7 +2,7 @@ package container
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/cli" "github.com/docker/cli/cli"
@ -71,7 +71,7 @@ func TestNewAttachCommandErrors(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
cmd := NewAttachCommand(test.NewFakeCli(&fakeClient{inspectFunc: tc.containerInspectFunc})) cmd := NewAttachCommand(test.NewFakeCli(&fakeClient{inspectFunc: tc.containerInspectFunc}))
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }

View File

@ -285,10 +285,12 @@ func copyToContainer(ctx context.Context, dockerCli command.Cli, copyConfig cpCo
// in a valid LOCALPATH, like `file:name.txt`. We can resolve this ambiguity by // in a valid LOCALPATH, like `file:name.txt`. We can resolve this ambiguity by
// requiring a LOCALPATH with a `:` to be made explicit with a relative or // requiring a LOCALPATH with a `:` to be made explicit with a relative or
// absolute path: // absolute path:
// `/path/to/file:name.txt` or `./file:name.txt` //
// `/path/to/file:name.txt` or `./file:name.txt`
// //
// This is apparently how `scp` handles this as well: // This is apparently how `scp` handles this as well:
// http://www.cyberciti.biz/faq/rsync-scp-file-name-with-colon-punctuation-in-it/ //
// http://www.cyberciti.biz/faq/rsync-scp-file-name-with-colon-punctuation-in-it/
// //
// We can't simply check for a filepath separator because container names may // We can't simply check for a filepath separator because container names may
// have a separator, e.g., "host0/cname1" if container is in a Docker cluster, // have a separator, e.g., "host0/cname1" if container is in a Docker cluster,

View File

@ -2,7 +2,6 @@ package container
import ( import (
"io" "io"
"io/ioutil"
"os" "os"
"runtime" "runtime"
"strings" "strings"
@ -54,7 +53,7 @@ func TestRunCopyFromContainerToStdout(t *testing.T) {
fakeClient := &fakeClient{ fakeClient := &fakeClient{
containerCopyFromFunc: func(container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) { containerCopyFromFunc: func(container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) {
assert.Check(t, is.Equal("container", container)) assert.Check(t, is.Equal("container", container))
return ioutil.NopCloser(strings.NewReader(tarContent)), types.ContainerPathStat{}, nil return io.NopCloser(strings.NewReader(tarContent)), types.ContainerPathStat{}, nil
}, },
} }
options := copyOptions{source: "container:/path", destination: "-"} options := copyOptions{source: "container:/path", destination: "-"}
@ -84,7 +83,7 @@ func TestRunCopyFromContainerToFilesystem(t *testing.T) {
assert.Check(t, is.Equal("", cli.OutBuffer().String())) assert.Check(t, is.Equal("", cli.OutBuffer().String()))
assert.Check(t, is.Equal("", cli.ErrBuffer().String())) assert.Check(t, is.Equal("", cli.ErrBuffer().String()))
content, err := ioutil.ReadFile(destDir.Join("file1")) content, err := os.ReadFile(destDir.Join("file1"))
assert.NilError(t, err) assert.NilError(t, err)
assert.Check(t, is.Equal("content\n", string(content))) assert.Check(t, is.Equal("content\n", string(content)))
} }

View File

@ -188,7 +188,7 @@ func newCIDFile(path string) (*cidFile, error) {
return &cidFile{path: path, file: f}, nil return &cidFile{path: path, file: f}, nil
} }
// nolint: gocyclo //nolint:gocyclo
func createContainer(ctx context.Context, dockerCli command.Cli, containerConfig *containerConfig, opts *createOptions) (*container.ContainerCreateCreatedBody, error) { func createContainer(ctx context.Context, dockerCli command.Cli, containerConfig *containerConfig, opts *createOptions) (*container.ContainerCreateCreatedBody, error) {
config := containerConfig.Config config := containerConfig.Config
hostConfig := containerConfig.HostConfig hostConfig := containerConfig.HostConfig

View File

@ -4,7 +4,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"runtime" "runtime"
"sort" "sort"
@ -67,7 +66,7 @@ func TestCIDFileCloseWithWrite(t *testing.T) {
content := "id" content := "id"
assert.NilError(t, file.Write(content)) assert.NilError(t, file.Write(content))
actual, err := ioutil.ReadFile(path) actual, err := os.ReadFile(path)
assert.NilError(t, err) assert.NilError(t, err)
assert.Check(t, is.Equal(content, string(actual))) assert.Check(t, is.Equal(content, string(actual)))
@ -130,7 +129,7 @@ func TestCreateContainerImagePullPolicy(t *testing.T) {
}, },
imageCreateFunc: func(parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) { imageCreateFunc: func(parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) {
defer func() { pullCounter++ }() defer func() { pullCounter++ }()
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
}, },
infoFunc: func() (types.Info, error) { infoFunc: func() (types.Info, error) {
return types.Info{IndexServerAddress: "https://indexserver.example.com"}, nil return types.Info{IndexServerAddress: "https://indexserver.example.com"}, nil
@ -194,7 +193,7 @@ func TestNewCreateCommandWithContentTrustErrors(t *testing.T) {
}, test.EnableContentTrust) }, test.EnableContentTrust)
cli.SetNotaryClient(tc.notaryFunc) cli.SetNotaryClient(tc.notaryFunc)
cmd := NewCreateCommand(cli) cmd := NewCreateCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.ErrorContains(t, err, tc.expectedError) assert.ErrorContains(t, err, tc.expectedError)
@ -254,7 +253,7 @@ func TestNewCreateCommandWithWarnings(t *testing.T) {
}, },
}) })
cmd := NewCreateCommand(cli) cmd := NewCreateCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.NilError(t, err) assert.NilError(t, err)
@ -303,7 +302,7 @@ func TestCreateContainerWithProxyConfig(t *testing.T) {
}, },
}) })
cmd := NewCreateCommand(cli) cmd := NewCreateCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"image:tag"}) cmd.SetArgs([]string{"image:tag"})
err := cmd.Execute() err := cmd.Execute()
assert.NilError(t, err) assert.NilError(t, err)

View File

@ -2,7 +2,7 @@ package container
import ( import (
"context" "context"
"io/ioutil" "io"
"os" "os"
"testing" "testing"
@ -267,7 +267,7 @@ func TestNewExecCommandErrors(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
cli := test.NewFakeCli(&fakeClient{inspectFunc: tc.containerInspectFunc}) cli := test.NewFakeCli(&fakeClient{inspectFunc: tc.containerInspectFunc})
cmd := NewExecCommand(cli) cmd := NewExecCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }

View File

@ -2,7 +2,6 @@ package container
import ( import (
"io" "io"
"io/ioutil"
"strings" "strings"
"testing" "testing"
@ -17,11 +16,11 @@ func TestContainerExportOutputToFile(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
containerExportFunc: func(container string) (io.ReadCloser, error) { containerExportFunc: func(container string) (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader("bar")), nil return io.NopCloser(strings.NewReader("bar")), nil
}, },
}) })
cmd := NewExportCommand(cli) cmd := NewExportCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"-o", dir.Join("foo"), "container"}) cmd.SetArgs([]string{"-o", dir.Join("foo"), "container"})
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())
@ -35,11 +34,11 @@ func TestContainerExportOutputToFile(t *testing.T) {
func TestContainerExportOutputToIrregularFile(t *testing.T) { func TestContainerExportOutputToIrregularFile(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
containerExportFunc: func(container string) (io.ReadCloser, error) { containerExportFunc: func(container string) (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader("foo")), nil return io.NopCloser(strings.NewReader("foo")), nil
}, },
}) })
cmd := NewExportCommand(cli) cmd := NewExportCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"-o", "/dev/random", "container"}) cmd.SetArgs([]string{"-o", "/dev/random", "container"})
err := cmd.Execute() err := cmd.Execute()

View File

@ -2,7 +2,7 @@ package container
import ( import (
"context" "context"
"io/ioutil" "io"
"github.com/docker/cli/cli" "github.com/docker/cli/cli"
"github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command"
@ -89,7 +89,7 @@ func buildContainerListOptions(opts *psOptions) (*types.ContainerListOptions, er
// This shouldn't error out but swallowing the error makes it harder // This shouldn't error out but swallowing the error makes it harder
// to track down if preProcessor issues come up. // to track down if preProcessor issues come up.
if err := tmpl.Execute(ioutil.Discard, optionsProcessor); err != nil { if err := tmpl.Execute(io.Discard, optionsProcessor); err != nil {
return nil, errors.Wrap(err, "failed to execute template") return nil, errors.Wrap(err, "failed to execute template")
} }

View File

@ -2,7 +2,7 @@ package container
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/cli/config/configfile" "github.com/docker/cli/cli/config/configfile"
@ -161,7 +161,7 @@ func TestContainerListErrors(t *testing.T) {
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -2,7 +2,6 @@ package container
import ( import (
"io" "io"
"io/ioutil"
"strings" "strings"
"testing" "testing"
@ -15,7 +14,7 @@ import (
var logFn = func(expectedOut string) func(string, types.ContainerLogsOptions) (io.ReadCloser, error) { var logFn = func(expectedOut string) func(string, types.ContainerLogsOptions) (io.ReadCloser, error) {
return func(container string, opts types.ContainerLogsOptions) (io.ReadCloser, error) { return func(container string, opts types.ContainerLogsOptions) (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader(expectedOut)), nil return io.NopCloser(strings.NewReader(expectedOut)), nil
} }
} }

View File

@ -4,7 +4,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "os"
"path" "path"
"reflect" "reflect"
"regexp" "regexp"
@ -310,7 +310,8 @@ type containerConfig struct {
// parse parses the args for the specified command and generates a Config, // parse parses the args for the specified command and generates a Config,
// a HostConfig and returns them with the specified command. // a HostConfig and returns them with the specified command.
// If the specified args are not valid, it will return an error. // If the specified args are not valid, it will return an error.
// nolint: gocyclo //
//nolint:gocyclo
func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*containerConfig, error) { func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*containerConfig, error) {
var ( var (
attachStdin = copts.attach.Get("stdin") attachStdin = copts.attach.Get("stdin")
@ -848,7 +849,7 @@ func parseSecurityOpts(securityOpts []string) ([]string, error) {
} }
} }
if con[0] == "seccomp" && con[1] != "unconfined" { if con[0] == "seccomp" && con[1] != "unconfined" {
f, err := ioutil.ReadFile(con[1]) f, err := os.ReadFile(con[1])
if err != nil { if err != nil {
return securityOpts, errors.Errorf("opening seccomp profile (%s) failed: %v", con[1], err) return securityOpts, errors.Errorf("opening seccomp profile (%s) failed: %v", con[1], err)
} }
@ -910,8 +911,7 @@ func parseDevice(device, serverOS string) (container.DeviceMapping, error) {
// parseLinuxDevice parses a device mapping string to a container.DeviceMapping struct // parseLinuxDevice parses a device mapping string to a container.DeviceMapping struct
// knowing that the target is a Linux daemon // knowing that the target is a Linux daemon
func parseLinuxDevice(device string) (container.DeviceMapping, error) { func parseLinuxDevice(device string) (container.DeviceMapping, error) {
src := "" var src, dst string
dst := ""
permissions := "rwm" permissions := "rwm"
arr := strings.Split(device, ":") arr := strings.Split(device, ":")
switch len(arr) { switch len(arr) {
@ -951,7 +951,8 @@ func parseWindowsDevice(device string) (container.DeviceMapping, error) {
// validateDeviceCgroupRule validates a device cgroup rule string format // validateDeviceCgroupRule validates a device cgroup rule string format
// It will make sure 'val' is in the form: // It will make sure 'val' is in the form:
// 'type major:minor mode' //
// 'type major:minor mode'
func validateDeviceCgroupRule(val string) (string, error) { func validateDeviceCgroupRule(val string) (string, error) {
if deviceCgroupRuleRegexp.MatchString(val) { if deviceCgroupRuleRegexp.MatchString(val) {
return val, nil return val, nil
@ -995,7 +996,9 @@ func validateDevice(val string, serverOS string) (string, error) {
// validateLinuxPath is the implementation of validateDevice knowing that the // validateLinuxPath is the implementation of validateDevice knowing that the
// target server operating system is a Linux daemon. // target server operating system is a Linux daemon.
// It will make sure 'val' is in the form: // It will make sure 'val' is in the form:
// [host-dir:]container-path[:mode] //
// [host-dir:]container-path[:mode]
//
// It also validates the device mode. // It also validates the device mode.
func validateLinuxPath(val string, validator func(string) bool) (string, error) { func validateLinuxPath(val string, validator func(string) bool) (string, error) {
var containerPath string var containerPath string

View File

@ -2,7 +2,7 @@ package container
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"runtime" "runtime"
"strings" "strings"
@ -58,7 +58,7 @@ func parseRun(args []string) (*container.Config, *container.HostConfig, *network
func setupRunFlags() (*pflag.FlagSet, *containerOptions) { func setupRunFlags() (*pflag.FlagSet, *containerOptions) {
flags := pflag.NewFlagSet("run", pflag.ContinueOnError) flags := pflag.NewFlagSet("run", pflag.ContinueOnError)
flags.SetOutput(ioutil.Discard) flags.SetOutput(io.Discard)
flags.Usage = nil flags.Usage = nil
copts := addFlags(flags) copts := addFlags(flags)
return flags, copts return flags, copts
@ -182,7 +182,7 @@ func TestParseRunWithInvalidArgs(t *testing.T) {
} }
} }
// nolint: gocyclo //nolint:gocyclo
func TestParseWithVolumes(t *testing.T) { func TestParseWithVolumes(t *testing.T) {
// A single volume // A single volume

View File

@ -3,7 +3,7 @@ package container
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"sort" "sort"
"sync" "sync"
"testing" "testing"
@ -44,7 +44,7 @@ func TestRemoveForce(t *testing.T) {
Version: "1.36", Version: "1.36",
}) })
cmd := NewRmCommand(cli) cmd := NewRmCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()

View File

@ -91,7 +91,7 @@ func runRun(dockerCli command.Cli, flags *pflag.FlagSet, ropts *runOptions, copt
return runContainer(dockerCli, ropts, copts, containerConfig) return runContainer(dockerCli, ropts, copts, containerConfig)
} }
// nolint: gocyclo //nolint:gocyclo
func runContainer(dockerCli command.Cli, opts *runOptions, copts *containerOptions, containerConfig *containerConfig) error { func runContainer(dockerCli command.Cli, opts *runOptions, copts *containerOptions, containerConfig *containerConfig) error {
config := containerConfig.Config config := containerConfig.Config
hostConfig := containerConfig.HostConfig hostConfig := containerConfig.HostConfig

View File

@ -2,7 +2,7 @@ package container
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -68,7 +68,7 @@ func TestRunCommandWithContentTrustErrors(t *testing.T) {
cli.SetNotaryClient(tc.notaryFunc) cli.SetNotaryClient(tc.notaryFunc)
cmd := NewRunCommand(cli) cmd := NewRunCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
err := cmd.Execute() err := cmd.Execute()
assert.Assert(t, err != nil) assert.Assert(t, err != nil)
assert.Assert(t, is.Contains(cli.ErrBuffer().String(), tc.expectedError)) assert.Assert(t, is.Contains(cli.ErrBuffer().String(), tc.expectedError))

View File

@ -53,7 +53,7 @@ func NewStartCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
// nolint: gocyclo //nolint:gocyclo
func runStart(dockerCli command.Cli, opts *startOptions) error { func runStart(dockerCli command.Cli, opts *startOptions) error {
ctx, cancelFun := context.WithCancel(context.Background()) ctx, cancelFun := context.WithCancel(context.Background())
defer cancelFun() defer cancelFun()

View File

@ -50,7 +50,8 @@ func NewStatsCommand(dockerCli command.Cli) *cobra.Command {
// runStats displays a live stream of resource usage statistics for one or more containers. // runStats displays a live stream of resource usage statistics for one or more containers.
// This shows real-time information on CPU usage, memory usage, and network I/O. // This shows real-time information on CPU usage, memory usage, and network I/O.
// nolint: gocyclo //
//nolint:gocyclo
func runStats(dockerCli command.Cli, opts *statsOptions) error { func runStats(dockerCli command.Cli, opts *statsOptions) error {
showAll := len(opts.containers) == 0 showAll := len(opts.containers) == 0
closeChan := make(chan error) closeChan := make(chan error)

View File

@ -2,8 +2,6 @@ package context
import ( import (
"fmt" "fmt"
"io/ioutil"
"os"
"testing" "testing"
"github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command"
@ -16,9 +14,9 @@ import (
"gotest.tools/v3/env" "gotest.tools/v3/env"
) )
func makeFakeCli(t *testing.T, opts ...func(*test.FakeCli)) (*test.FakeCli, func()) { func makeFakeCli(t *testing.T, opts ...func(*test.FakeCli)) *test.FakeCli {
dir, err := ioutil.TempDir("", t.Name()) t.Helper()
assert.NilError(t, err) dir := t.TempDir()
storeConfig := store.NewConfig( storeConfig := store.NewConfig(
func() interface{} { return &command.DockerContext{} }, func() interface{} { return &command.DockerContext{} },
store.EndpointTypeGetter(docker.DockerEndpoint, func() interface{} { return &docker.EndpointMeta{} }), store.EndpointTypeGetter(docker.DockerEndpoint, func() interface{} { return &docker.EndpointMeta{} }),
@ -44,15 +42,12 @@ func makeFakeCli(t *testing.T, opts ...func(*test.FakeCli)) (*test.FakeCli, func
}, nil }, nil
}, },
} }
cleanup := func() {
os.RemoveAll(dir)
}
result := test.NewFakeCli(nil, opts...) result := test.NewFakeCli(nil, opts...)
for _, o := range opts { for _, o := range opts {
o(result) o(result)
} }
result.SetContextStore(store) result.SetContextStore(store)
return result, cleanup return result
} }
func withCliConfig(configFile *configfile.ConfigFile) func(*test.FakeCli) { func withCliConfig(configFile *configfile.ConfigFile) func(*test.FakeCli) {
@ -62,8 +57,7 @@ func withCliConfig(configFile *configfile.ConfigFile) func(*test.FakeCli) {
} }
func TestCreateInvalids(t *testing.T) { func TestCreateInvalids(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
assert.NilError(t, cli.ContextStore().CreateOrUpdate(store.Metadata{Name: "existing-context"})) assert.NilError(t, cli.ContextStore().CreateOrUpdate(store.Metadata{Name: "existing-context"}))
tests := []struct { tests := []struct {
options CreateOptions options CreateOptions
@ -138,8 +132,7 @@ func assertContextCreateLogging(t *testing.T, cli *test.FakeCli, n string) {
} }
func TestCreateOrchestratorSwarm(t *testing.T) { func TestCreateOrchestratorSwarm(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
err := RunCreate(cli, &CreateOptions{ err := RunCreate(cli, &CreateOptions{
Name: "test", Name: "test",
@ -151,8 +144,7 @@ func TestCreateOrchestratorSwarm(t *testing.T) {
} }
func TestCreateOrchestratorEmpty(t *testing.T) { func TestCreateOrchestratorEmpty(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
err := RunCreate(cli, &CreateOptions{ err := RunCreate(cli, &CreateOptions{
Name: "test", Name: "test",
@ -192,8 +184,7 @@ func createTestContextWithKube(t *testing.T, cli command.Cli) {
} }
func TestCreateOrchestratorAllKubernetesEndpointFromCurrent(t *testing.T) { func TestCreateOrchestratorAllKubernetesEndpointFromCurrent(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
createTestContextWithKube(t, cli) createTestContextWithKube(t, cli)
assertContextCreateLogging(t, cli, "test") assertContextCreateLogging(t, cli, "test")
validateTestKubeEndpoint(t, cli.ContextStore(), "test") validateTestKubeEndpoint(t, cli.ContextStore(), "test")
@ -228,8 +219,7 @@ func TestCreateFromContext(t *testing.T) {
}, },
} }
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
revert := env.Patch(t, "KUBECONFIG", "./testdata/test-kubeconfig") revert := env.Patch(t, "KUBECONFIG", "./testdata/test-kubeconfig")
defer revert() defer revert()
cli.ResetOutputBuffers() cli.ResetOutputBuffers()
@ -319,8 +309,7 @@ func TestCreateFromCurrent(t *testing.T) {
}, },
} }
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
revert := env.Patch(t, "KUBECONFIG", "./testdata/test-kubeconfig") revert := env.Patch(t, "KUBECONFIG", "./testdata/test-kubeconfig")
defer revert() defer revert()
cli.ResetOutputBuffers() cli.ResetOutputBuffers()

View File

@ -3,7 +3,7 @@ package context
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -13,12 +13,8 @@ import (
) )
func TestExportImportWithFile(t *testing.T) { func TestExportImportWithFile(t *testing.T) {
contextDir, err := ioutil.TempDir("", t.Name()+"context") contextFile := filepath.Join(t.TempDir(), "exported")
assert.NilError(t, err) cli := makeFakeCli(t)
defer os.RemoveAll(contextDir)
contextFile := filepath.Join(contextDir, "exported")
cli, cleanup := makeFakeCli(t)
defer cleanup()
createTestContextWithKube(t, cli) createTestContextWithKube(t, cli)
cli.ErrBuffer().Reset() cli.ErrBuffer().Reset()
assert.NilError(t, RunExport(cli, &ExportOptions{ assert.NilError(t, RunExport(cli, &ExportOptions{
@ -43,8 +39,7 @@ func TestExportImportWithFile(t *testing.T) {
} }
func TestExportImportPipe(t *testing.T) { func TestExportImportPipe(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
createTestContextWithKube(t, cli) createTestContextWithKube(t, cli)
cli.ErrBuffer().Reset() cli.ErrBuffer().Reset()
cli.OutBuffer().Reset() cli.OutBuffer().Reset()
@ -53,7 +48,7 @@ func TestExportImportPipe(t *testing.T) {
Dest: "-", Dest: "-",
})) }))
assert.Equal(t, cli.ErrBuffer().String(), "") assert.Equal(t, cli.ErrBuffer().String(), "")
cli.SetIn(streams.NewIn(ioutil.NopCloser(bytes.NewBuffer(cli.OutBuffer().Bytes())))) cli.SetIn(streams.NewIn(io.NopCloser(bytes.NewBuffer(cli.OutBuffer().Bytes()))))
cli.OutBuffer().Reset() cli.OutBuffer().Reset()
cli.ErrBuffer().Reset() cli.ErrBuffer().Reset()
assert.NilError(t, RunImport(cli, "test2", "-")) assert.NilError(t, RunImport(cli, "test2", "-"))
@ -71,12 +66,8 @@ func TestExportImportPipe(t *testing.T) {
} }
func TestExportKubeconfig(t *testing.T) { func TestExportKubeconfig(t *testing.T) {
contextDir, err := ioutil.TempDir("", t.Name()+"context") contextFile := filepath.Join(t.TempDir(), "exported")
assert.NilError(t, err) cli := makeFakeCli(t)
defer os.RemoveAll(contextDir)
contextFile := filepath.Join(contextDir, "exported")
cli, cleanup := makeFakeCli(t)
defer cleanup()
createTestContextWithKube(t, cli) createTestContextWithKube(t, cli)
cli.ErrBuffer().Reset() cli.ErrBuffer().Reset()
assert.NilError(t, RunExport(cli, &ExportOptions{ assert.NilError(t, RunExport(cli, &ExportOptions{
@ -96,15 +87,11 @@ func TestExportKubeconfig(t *testing.T) {
} }
func TestExportExistingFile(t *testing.T) { func TestExportExistingFile(t *testing.T) {
contextDir, err := ioutil.TempDir("", t.Name()+"context") contextFile := filepath.Join(t.TempDir(), "exported")
assert.NilError(t, err) cli := makeFakeCli(t)
defer os.RemoveAll(contextDir)
contextFile := filepath.Join(contextDir, "exported")
cli, cleanup := makeFakeCli(t)
defer cleanup()
createTestContextWithKube(t, cli) createTestContextWithKube(t, cli)
cli.ErrBuffer().Reset() cli.ErrBuffer().Reset()
assert.NilError(t, ioutil.WriteFile(contextFile, []byte{}, 0644)) assert.NilError(t, os.WriteFile(contextFile, []byte{}, 0644))
err = RunExport(cli, &ExportOptions{ContextName: "test", Dest: contextFile}) err := RunExport(cli, &ExportOptions{ContextName: "test", Dest: contextFile})
assert.Assert(t, os.IsExist(err)) assert.Assert(t, os.IsExist(err))
} }

View File

@ -9,8 +9,7 @@ import (
) )
func TestInspect(t *testing.T) { func TestInspect(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "current", "all")
cli.OutBuffer().Reset() cli.OutBuffer().Reset()
assert.NilError(t, runInspect(cli, inspectOptions{ assert.NilError(t, runInspect(cli, inspectOptions{

View File

@ -24,8 +24,7 @@ func createTestContextWithKubeAndSwarm(t *testing.T, cli command.Cli, name strin
} }
func TestList(t *testing.T) { func TestList(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "current", "all")
createTestContextWithKubeAndSwarm(t, cli, "other", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all")
createTestContextWithKubeAndSwarm(t, cli, "unset", "unset") createTestContextWithKubeAndSwarm(t, cli, "unset", "unset")
@ -36,8 +35,7 @@ func TestList(t *testing.T) {
} }
func TestListQuiet(t *testing.T) { func TestListQuiet(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "current", "all")
createTestContextWithKubeAndSwarm(t, cli, "other", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all")
cli.SetCurrentContext("current") cli.SetCurrentContext("current")

View File

@ -1,8 +1,6 @@
package context package context
import ( import (
"io/ioutil"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -13,8 +11,7 @@ import (
) )
func TestRemove(t *testing.T) { func TestRemove(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "current", "all")
createTestContextWithKubeAndSwarm(t, cli, "other", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all")
assert.NilError(t, RunRemove(cli, RemoveOptions{}, []string{"other"})) assert.NilError(t, RunRemove(cli, RemoveOptions{}, []string{"other"}))
@ -25,8 +22,7 @@ func TestRemove(t *testing.T) {
} }
func TestRemoveNotAContext(t *testing.T) { func TestRemoveNotAContext(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "current", "all")
createTestContextWithKubeAndSwarm(t, cli, "other", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all")
err := RunRemove(cli, RemoveOptions{}, []string{"not-a-context"}) err := RunRemove(cli, RemoveOptions{}, []string{"not-a-context"})
@ -34,8 +30,7 @@ func TestRemoveNotAContext(t *testing.T) {
} }
func TestRemoveCurrent(t *testing.T) { func TestRemoveCurrent(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "current", "all")
createTestContextWithKubeAndSwarm(t, cli, "other", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all")
cli.SetCurrentContext("current") cli.SetCurrentContext("current")
@ -44,16 +39,13 @@ func TestRemoveCurrent(t *testing.T) {
} }
func TestRemoveCurrentForce(t *testing.T) { func TestRemoveCurrentForce(t *testing.T) {
configDir, err := ioutil.TempDir("", t.Name()+"config") configDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(configDir)
configFilePath := filepath.Join(configDir, "config.json") configFilePath := filepath.Join(configDir, "config.json")
testCfg := configfile.New(configFilePath) testCfg := configfile.New(configFilePath)
testCfg.CurrentContext = "current" testCfg.CurrentContext = "current"
assert.NilError(t, testCfg.Save()) assert.NilError(t, testCfg.Save())
cli, cleanup := makeFakeCli(t, withCliConfig(testCfg)) cli := makeFakeCli(t, withCliConfig(testCfg))
defer cleanup()
createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "current", "all")
createTestContextWithKubeAndSwarm(t, cli, "other", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all")
cli.SetCurrentContext("current") cli.SetCurrentContext("current")
@ -64,8 +56,7 @@ func TestRemoveCurrentForce(t *testing.T) {
} }
func TestRemoveDefault(t *testing.T) { func TestRemoveDefault(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
createTestContextWithKubeAndSwarm(t, cli, "other", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all")
cli.SetCurrentContext("current") cli.SetCurrentContext("current")
err := RunRemove(cli, RemoveOptions{}, []string{"default"}) err := RunRemove(cli, RemoveOptions{}, []string{"default"})

View File

@ -11,8 +11,7 @@ import (
) )
func TestUpdateDescriptionOnly(t *testing.T) { func TestUpdateDescriptionOnly(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
err := RunCreate(cli, &CreateOptions{ err := RunCreate(cli, &CreateOptions{
Name: "test", Name: "test",
DefaultStackOrchestrator: "swarm", DefaultStackOrchestrator: "swarm",
@ -37,8 +36,7 @@ func TestUpdateDescriptionOnly(t *testing.T) {
} }
func TestUpdateDockerOnly(t *testing.T) { func TestUpdateDockerOnly(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
createTestContextWithKubeAndSwarm(t, cli, "test", "swarm") createTestContextWithKubeAndSwarm(t, cli, "test", "swarm")
assert.NilError(t, RunUpdate(cli, &UpdateOptions{ assert.NilError(t, RunUpdate(cli, &UpdateOptions{
Name: "test", Name: "test",
@ -58,8 +56,7 @@ func TestUpdateDockerOnly(t *testing.T) {
} }
func TestUpdateStackOrchestratorStrategy(t *testing.T) { func TestUpdateStackOrchestratorStrategy(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
err := RunCreate(cli, &CreateOptions{ err := RunCreate(cli, &CreateOptions{
Name: "test", Name: "test",
DefaultStackOrchestrator: "swarm", DefaultStackOrchestrator: "swarm",
@ -74,8 +71,7 @@ func TestUpdateStackOrchestratorStrategy(t *testing.T) {
} }
func TestUpdateStackOrchestratorStrategyRemoveKubeEndpoint(t *testing.T) { func TestUpdateStackOrchestratorStrategyRemoveKubeEndpoint(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
createTestContextWithKubeAndSwarm(t, cli, "test", "kubernetes") createTestContextWithKubeAndSwarm(t, cli, "test", "kubernetes")
err := RunUpdate(cli, &UpdateOptions{ err := RunUpdate(cli, &UpdateOptions{
Name: "test", Name: "test",
@ -85,8 +81,7 @@ func TestUpdateStackOrchestratorStrategyRemoveKubeEndpoint(t *testing.T) {
} }
func TestUpdateInvalidDockerHost(t *testing.T) { func TestUpdateInvalidDockerHost(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
err := RunCreate(cli, &CreateOptions{ err := RunCreate(cli, &CreateOptions{
Name: "test", Name: "test",
Docker: map[string]string{}, Docker: map[string]string{},

View File

@ -1,8 +1,6 @@
package context package context
import ( import (
"io/ioutil"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -13,14 +11,11 @@ import (
) )
func TestUse(t *testing.T) { func TestUse(t *testing.T) {
configDir, err := ioutil.TempDir("", t.Name()+"config") configDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(configDir)
configFilePath := filepath.Join(configDir, "config.json") configFilePath := filepath.Join(configDir, "config.json")
testCfg := configfile.New(configFilePath) testCfg := configfile.New(configFilePath)
cli, cleanup := makeFakeCli(t, withCliConfig(testCfg)) cli := makeFakeCli(t, withCliConfig(testCfg))
defer cleanup() err := RunCreate(cli, &CreateOptions{
err = RunCreate(cli, &CreateOptions{
Name: "test", Name: "test",
Docker: map[string]string{}, Docker: map[string]string{},
}) })
@ -42,8 +37,7 @@ func TestUse(t *testing.T) {
} }
func TestUseNoExist(t *testing.T) { func TestUseNoExist(t *testing.T) {
cli, cleanup := makeFakeCli(t) cli := makeFakeCli(t)
defer cleanup()
err := newUseCommand(cli).RunE(nil, []string{"test"}) err := newUseCommand(cli).RunE(nil, []string{"test"})
assert.Check(t, store.IsErrContextDoesNotExist(err)) assert.Check(t, store.IsErrContextDoesNotExist(err))
} }

View File

@ -2,8 +2,6 @@ package command
import ( import (
"crypto/rand" "crypto/rand"
"io/ioutil"
"os"
"testing" "testing"
"github.com/docker/cli/cli/config/configfile" "github.com/docker/cli/cli/config/configfile"
@ -39,11 +37,10 @@ func testDefaultMetadata() store.Metadata {
} }
} }
func testStore(t *testing.T, meta store.Metadata, tls store.ContextTLSData) (store.Store, func()) { func testStore(t *testing.T, meta store.Metadata, tls store.ContextTLSData) store.Store {
testDir, err := ioutil.TempDir("", t.Name()) t.Helper()
assert.NilError(t, err) return &ContextStoreWithDefault{
s := &ContextStoreWithDefault{ Store: store.New(t.TempDir(), testCfg),
Store: store.New(testDir, testCfg),
Resolver: func() (*DefaultContext, error) { Resolver: func() (*DefaultContext, error) {
return &DefaultContext{ return &DefaultContext{
Meta: meta, Meta: meta,
@ -51,9 +48,6 @@ func testStore(t *testing.T, meta store.Metadata, tls store.ContextTLSData) (sto
}, nil }, nil
}, },
} }
return s, func() {
_ = os.RemoveAll(testDir)
}
} }
func TestDefaultContextInitializer(t *testing.T) { func TestDefaultContextInitializer(t *testing.T) {
@ -81,7 +75,7 @@ func TestExportDefaultImport(t *testing.T) {
rand.Read(file1) rand.Read(file1)
file2 := make([]byte, 3700) file2 := make([]byte, 3700)
rand.Read(file2) rand.Read(file2)
s, cleanup := testStore(t, testDefaultMetadata(), store.ContextTLSData{ s := testStore(t, testDefaultMetadata(), store.ContextTLSData{
Endpoints: map[string]store.EndpointTLSData{ Endpoints: map[string]store.EndpointTLSData{
"ep2": { "ep2": {
Files: map[string][]byte{ Files: map[string][]byte{
@ -91,7 +85,6 @@ func TestExportDefaultImport(t *testing.T) {
}, },
}, },
}) })
defer cleanup()
r := store.Export("default", s) r := store.Export("default", s)
defer r.Close() defer r.Close()
err := store.Import("dest", s, r) err := store.Import("dest", s, r)
@ -130,8 +123,7 @@ func TestExportDefaultImport(t *testing.T) {
func TestListDefaultContext(t *testing.T) { func TestListDefaultContext(t *testing.T) {
meta := testDefaultMetadata() meta := testDefaultMetadata()
s, cleanup := testStore(t, meta, store.ContextTLSData{}) s := testStore(t, meta, store.ContextTLSData{})
defer cleanup()
result, err := s.List() result, err := s.List()
assert.NilError(t, err) assert.NilError(t, err)
assert.Equal(t, 1, len(result)) assert.Equal(t, 1, len(result))
@ -139,8 +131,7 @@ func TestListDefaultContext(t *testing.T) {
} }
func TestGetDefaultContextStorageInfo(t *testing.T) { func TestGetDefaultContextStorageInfo(t *testing.T) {
s, cleanup := testStore(t, testDefaultMetadata(), store.ContextTLSData{}) s := testStore(t, testDefaultMetadata(), store.ContextTLSData{})
defer cleanup()
result := s.GetStorageInfo(DefaultContextName) result := s.GetStorageInfo(DefaultContextName)
assert.Equal(t, "<IN MEMORY>", result.MetadataPath) assert.Equal(t, "<IN MEMORY>", result.MetadataPath)
assert.Equal(t, "<IN MEMORY>", result.TLSPath) assert.Equal(t, "<IN MEMORY>", result.TLSPath)
@ -148,8 +139,7 @@ func TestGetDefaultContextStorageInfo(t *testing.T) {
func TestGetDefaultContextMetadata(t *testing.T) { func TestGetDefaultContextMetadata(t *testing.T) {
meta := testDefaultMetadata() meta := testDefaultMetadata()
s, cleanup := testStore(t, meta, store.ContextTLSData{}) s := testStore(t, meta, store.ContextTLSData{})
defer cleanup()
result, err := s.GetMetadata(DefaultContextName) result, err := s.GetMetadata(DefaultContextName)
assert.NilError(t, err) assert.NilError(t, err)
assert.Equal(t, DefaultContextName, result.Name) assert.Equal(t, DefaultContextName, result.Name)
@ -159,8 +149,7 @@ func TestGetDefaultContextMetadata(t *testing.T) {
func TestErrCreateDefault(t *testing.T) { func TestErrCreateDefault(t *testing.T) {
meta := testDefaultMetadata() meta := testDefaultMetadata()
s, cleanup := testStore(t, meta, store.ContextTLSData{}) s := testStore(t, meta, store.ContextTLSData{})
defer cleanup()
err := s.CreateOrUpdate(store.Metadata{ err := s.CreateOrUpdate(store.Metadata{
Endpoints: map[string]interface{}{ Endpoints: map[string]interface{}{
"ep1": endpoint{Foo: "bar"}, "ep1": endpoint{Foo: "bar"},
@ -173,16 +162,14 @@ func TestErrCreateDefault(t *testing.T) {
func TestErrRemoveDefault(t *testing.T) { func TestErrRemoveDefault(t *testing.T) {
meta := testDefaultMetadata() meta := testDefaultMetadata()
s, cleanup := testStore(t, meta, store.ContextTLSData{}) s := testStore(t, meta, store.ContextTLSData{})
defer cleanup()
err := s.Remove("default") err := s.Remove("default")
assert.Error(t, err, "default context cannot be removed") assert.Error(t, err, "default context cannot be removed")
} }
func TestErrTLSDataError(t *testing.T) { func TestErrTLSDataError(t *testing.T) {
meta := testDefaultMetadata() meta := testDefaultMetadata()
s, cleanup := testStore(t, meta, store.ContextTLSData{}) s := testStore(t, meta, store.ContextTLSData{})
defer cleanup()
_, err := s.GetTLSData("default", "noop", "noop") _, err := s.GetTLSData("default", "noop", "noop")
assert.Check(t, store.IsErrTLSDataDoesNotExist(err)) assert.Check(t, store.IsErrTLSDataDoesNotExist(err))
} }

View File

@ -436,7 +436,7 @@ type ports struct {
expected string expected string
} }
// nolint: lll //nolint:lll
func TestDisplayablePorts(t *testing.T) { func TestDisplayablePorts(t *testing.T) {
cases := []ports{ cases := []ports{
{ {

View File

@ -12,7 +12,7 @@ func (d *dummy) Func1() string {
return "Func1" return "Func1"
} }
func (d *dummy) func2() string { // nolint: unused func (d *dummy) func2() string { //nolint:unused
return "func2(should not be marshalled)" return "func2(should not be marshalled)"
} }

View File

@ -9,7 +9,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
@ -205,7 +204,7 @@ func (out *lastProgressOutput) WriteProgress(prog progress.Progress) error {
return out.output.WriteProgress(prog) return out.output.WriteProgress(prog)
} }
// nolint: gocyclo //nolint:gocyclo
func runBuild(dockerCli command.Cli, options buildOptions) error { func runBuild(dockerCli command.Cli, options buildOptions) error {
buildkitEnabled, err := command.BuildKitEnabled(dockerCli.ServerInfo()) buildkitEnabled, err := command.BuildKitEnabled(dockerCli.ServerInfo())
if err != nil { if err != nil {
@ -340,7 +339,7 @@ func runBuild(dockerCli command.Cli, options buildOptions) error {
if err != nil { if err != nil {
return err return err
} }
dockerfileCtx = ioutil.NopCloser(bytes.NewBuffer(newDockerfile)) dockerfileCtx = io.NopCloser(bytes.NewBuffer(newDockerfile))
} }
} }
@ -436,7 +435,7 @@ func runBuild(dockerCli command.Cli, options buildOptions) error {
if imageID == "" { if imageID == "" {
return errors.Errorf("Server did not provide an image ID. Cannot write %s", options.imageIDFile) return errors.Errorf("Server did not provide an image ID. Cannot write %s", options.imageIDFile)
} }
if err := ioutil.WriteFile(options.imageIDFile, []byte(imageID), 0666); err != nil { if err := os.WriteFile(options.imageIDFile, []byte(imageID), 0666); err != nil {
return err return err
} }
} }

View File

@ -6,7 +6,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@ -117,13 +116,13 @@ func DetectArchiveReader(input io.ReadCloser) (rc io.ReadCloser, isArchive bool,
// temporary directory containing the Dockerfile. // temporary directory containing the Dockerfile.
func WriteTempDockerfile(rc io.ReadCloser) (dockerfileDir string, err error) { func WriteTempDockerfile(rc io.ReadCloser) (dockerfileDir string, err error) {
// err is a named return value, due to the defer call below. // err is a named return value, due to the defer call below.
dockerfileDir, err = ioutil.TempDir("", "docker-build-tempdockerfile-") dockerfileDir, err = os.MkdirTemp("", "docker-build-tempdockerfile-")
if err != nil { if err != nil {
return "", errors.Errorf("unable to create temporary context directory: %v", err) return "", errors.Errorf("unable to create temporary context directory: %v", err)
} }
defer func() { defer func() {
if err != nil { if err != nil {
os.RemoveAll(dockerfileDir) _ = os.RemoveAll(dockerfileDir)
} }
}() }()
@ -236,11 +235,11 @@ func getWithStatusError(url string) (resp *http.Response, err error) {
if resp, err = http.Get(url); err != nil { if resp, err = http.Get(url); err != nil {
return nil, err return nil, err
} }
if resp.StatusCode < 400 { if resp.StatusCode < http.StatusBadRequest {
return resp, nil return resp, nil
} }
msg := fmt.Sprintf("failed to GET %s with status %s", url, resp.Status) msg := fmt.Sprintf("failed to GET %s with status %s", url, resp.Status)
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
resp.Body.Close() resp.Body.Close()
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "%s: error reading body", msg) return nil, errors.Wrapf(err, "%s: error reading body", msg)
@ -372,7 +371,7 @@ func isUNC(path string) bool {
// AddDockerfileToBuildContext from a ReadCloser, returns a new archive and // AddDockerfileToBuildContext from a ReadCloser, returns a new archive and
// the relative path to the dockerfile in the context. // the relative path to the dockerfile in the context.
func AddDockerfileToBuildContext(dockerfileCtx io.ReadCloser, buildCtx io.ReadCloser) (io.ReadCloser, string, error) { func AddDockerfileToBuildContext(dockerfileCtx io.ReadCloser, buildCtx io.ReadCloser) (io.ReadCloser, string, error) {
file, err := ioutil.ReadAll(dockerfileCtx) file, err := io.ReadAll(dockerfileCtx)
dockerfileCtx.Close() dockerfileCtx.Close()
if err != nil { if err != nil {
return nil, "", err return nil, "", err

View File

@ -4,7 +4,6 @@ import (
"archive/tar" "archive/tar"
"bytes" "bytes"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -19,40 +18,34 @@ import (
const dockerfileContents = "FROM busybox" const dockerfileContents = "FROM busybox"
var prepareEmpty = func(t *testing.T) (string, func()) { func prepareEmpty(t *testing.T) string {
return "", func() {} return ""
} }
var prepareNoFiles = func(t *testing.T) (string, func()) { func prepareNoFiles(t *testing.T) string {
return createTestTempDir(t, "builder-context-test") return createTestTempDir(t)
} }
var prepareOneFile = func(t *testing.T) (string, func()) { func prepareOneFile(t *testing.T) string {
contextDir, cleanup := createTestTempDir(t, "builder-context-test") contextDir := createTestTempDir(t)
createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents) createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents)
return contextDir, cleanup return contextDir
} }
func testValidateContextDirectory(t *testing.T, prepare func(t *testing.T) (string, func()), excludes []string) { func testValidateContextDirectory(t *testing.T, prepare func(t *testing.T) string, excludes []string) {
contextDir, cleanup := prepare(t) contextDir := prepare(t)
defer cleanup()
err := ValidateContextDirectory(contextDir, excludes) err := ValidateContextDirectory(contextDir, excludes)
assert.NilError(t, err) assert.NilError(t, err)
} }
func TestGetContextFromLocalDirNoDockerfile(t *testing.T) { func TestGetContextFromLocalDirNoDockerfile(t *testing.T) {
contextDir, cleanup := createTestTempDir(t, "builder-context-test") contextDir := createTestTempDir(t)
defer cleanup()
_, _, err := GetContextFromLocalDir(contextDir, "") _, _, err := GetContextFromLocalDir(contextDir, "")
assert.ErrorContains(t, err, "Dockerfile") assert.ErrorContains(t, err, "Dockerfile")
} }
func TestGetContextFromLocalDirNotExistingDir(t *testing.T) { func TestGetContextFromLocalDirNotExistingDir(t *testing.T) {
contextDir, cleanup := createTestTempDir(t, "builder-context-test") contextDir := createTestTempDir(t)
defer cleanup()
fakePath := filepath.Join(contextDir, "fake") fakePath := filepath.Join(contextDir, "fake")
_, _, err := GetContextFromLocalDir(fakePath, "") _, _, err := GetContextFromLocalDir(fakePath, "")
@ -60,9 +53,7 @@ func TestGetContextFromLocalDirNotExistingDir(t *testing.T) {
} }
func TestGetContextFromLocalDirNotExistingDockerfile(t *testing.T) { func TestGetContextFromLocalDirNotExistingDockerfile(t *testing.T) {
contextDir, cleanup := createTestTempDir(t, "builder-context-test") contextDir := createTestTempDir(t)
defer cleanup()
fakePath := filepath.Join(contextDir, "fake") fakePath := filepath.Join(contextDir, "fake")
_, _, err := GetContextFromLocalDir(contextDir, fakePath) _, _, err := GetContextFromLocalDir(contextDir, fakePath)
@ -70,13 +61,10 @@ func TestGetContextFromLocalDirNotExistingDockerfile(t *testing.T) {
} }
func TestGetContextFromLocalDirWithNoDirectory(t *testing.T) { func TestGetContextFromLocalDirWithNoDirectory(t *testing.T) {
contextDir, dirCleanup := createTestTempDir(t, "builder-context-test") contextDir := createTestTempDir(t)
defer dirCleanup()
createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents) createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents)
chdirCleanup := chdir(t, contextDir) chdir(t, contextDir)
defer chdirCleanup()
absContextDir, relDockerfile, err := GetContextFromLocalDir(contextDir, "") absContextDir, relDockerfile, err := GetContextFromLocalDir(contextDir, "")
assert.NilError(t, err) assert.NilError(t, err)
@ -86,9 +74,7 @@ func TestGetContextFromLocalDirWithNoDirectory(t *testing.T) {
} }
func TestGetContextFromLocalDirWithDockerfile(t *testing.T) { func TestGetContextFromLocalDirWithDockerfile(t *testing.T) {
contextDir, cleanup := createTestTempDir(t, "builder-context-test") contextDir := createTestTempDir(t)
defer cleanup()
createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents) createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents)
absContextDir, relDockerfile, err := GetContextFromLocalDir(contextDir, "") absContextDir, relDockerfile, err := GetContextFromLocalDir(contextDir, "")
@ -99,9 +85,7 @@ func TestGetContextFromLocalDirWithDockerfile(t *testing.T) {
} }
func TestGetContextFromLocalDirLocalFile(t *testing.T) { func TestGetContextFromLocalDirLocalFile(t *testing.T) {
contextDir, cleanup := createTestTempDir(t, "builder-context-test") contextDir := createTestTempDir(t)
defer cleanup()
createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents) createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents)
testFilename := createTestTempFile(t, contextDir, "tmpTest", "test") testFilename := createTestTempFile(t, contextDir, "tmpTest", "test")
@ -121,11 +105,8 @@ func TestGetContextFromLocalDirLocalFile(t *testing.T) {
} }
func TestGetContextFromLocalDirWithCustomDockerfile(t *testing.T) { func TestGetContextFromLocalDirWithCustomDockerfile(t *testing.T) {
contextDir, cleanup := createTestTempDir(t, "builder-context-test") contextDir := createTestTempDir(t)
defer cleanup() chdir(t, contextDir)
chdirCleanup := chdir(t, contextDir)
defer chdirCleanup()
createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents) createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents)
@ -137,7 +118,7 @@ func TestGetContextFromLocalDirWithCustomDockerfile(t *testing.T) {
} }
func TestGetContextFromReaderString(t *testing.T) { func TestGetContextFromReaderString(t *testing.T) {
tarArchive, relDockerfile, err := GetContextFromReader(ioutil.NopCloser(strings.NewReader(dockerfileContents)), "") tarArchive, relDockerfile, err := GetContextFromReader(io.NopCloser(strings.NewReader(dockerfileContents)), "")
if err != nil { if err != nil {
t.Fatalf("Error when executing GetContextFromReader: %s", err) t.Fatalf("Error when executing GetContextFromReader: %s", err)
@ -173,9 +154,7 @@ func TestGetContextFromReaderString(t *testing.T) {
} }
func TestGetContextFromReaderTar(t *testing.T) { func TestGetContextFromReaderTar(t *testing.T) {
contextDir, cleanup := createTestTempDir(t, "builder-context-test") contextDir := createTestTempDir(t)
defer cleanup()
createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents) createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents)
tarStream, err := archive.Tar(contextDir, archive.Uncompressed) tarStream, err := archive.Tar(contextDir, archive.Uncompressed)
@ -238,21 +217,24 @@ func TestValidateContextDirectoryWithOneFileExcludes(t *testing.T) {
testValidateContextDirectory(t, prepareOneFile, []string{DefaultDockerfileName}) testValidateContextDirectory(t, prepareOneFile, []string{DefaultDockerfileName})
} }
// createTestTempDir creates a temporary directory for testing. // createTestTempDir creates a temporary directory for testing. It returns the
// It returns the created path and a cleanup function which is meant to be used as deferred call. // created path. When an error occurs, it terminates the test.
// When an error occurs, it terminates the test. func createTestTempDir(t *testing.T) string {
//nolint: unparam t.Helper()
func createTestTempDir(t *testing.T, prefix string) (string, func()) { path := t.TempDir()
path, err := ioutil.TempDir("", prefix)
// Eval Symlinks is needed to account for macOS TMP using symlinks
path, err := filepath.EvalSymlinks(path)
assert.NilError(t, err) assert.NilError(t, err)
return path, func() { assert.NilError(t, os.RemoveAll(path)) } return path
} }
// createTestTempFile creates a temporary file within dir with specific contents and permissions. // createTestTempFile creates a temporary file within dir with specific contents and permissions.
// When an error occurs, it terminates the test // When an error occurs, it terminates the test
func createTestTempFile(t *testing.T, dir, filename, contents string) string { func createTestTempFile(t *testing.T, dir, filename, contents string) string {
t.Helper()
filePath := filepath.Join(dir, filename) filePath := filepath.Join(dir, filename)
err := ioutil.WriteFile(filePath, []byte(contents), 0777) err := os.WriteFile(filePath, []byte(contents), 0777)
assert.NilError(t, err) assert.NilError(t, err)
return filePath return filePath
} }
@ -261,11 +243,13 @@ func createTestTempFile(t *testing.T, dir, filename, contents string) string {
// It returns a function which changes working directory back to the previous one. // It returns a function which changes working directory back to the previous one.
// This function is meant to be executed as a deferred call. // This function is meant to be executed as a deferred call.
// When an error occurs, it terminates the test. // When an error occurs, it terminates the test.
func chdir(t *testing.T, dir string) func() { func chdir(t *testing.T, dir string) {
workingDirectory, err := os.Getwd() workingDirectory, err := os.Getwd()
assert.NilError(t, err) assert.NilError(t, err)
assert.NilError(t, os.Chdir(dir)) assert.NilError(t, os.Chdir(dir))
return func() { assert.NilError(t, os.Chdir(workingDirectory)) } t.Cleanup(func() {
assert.NilError(t, os.Chdir(workingDirectory))
})
} }
func TestIsArchive(t *testing.T) { func TestIsArchive(t *testing.T) {

View File

@ -7,7 +7,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
@ -43,7 +42,7 @@ const uploadRequestRemote = "upload-request"
var errDockerfileConflict = errors.New("ambiguous Dockerfile source: both stdin and flag correspond to Dockerfiles") var errDockerfileConflict = errors.New("ambiguous Dockerfile source: both stdin and flag correspond to Dockerfiles")
//nolint: gocyclo // nolint: gocyclo
func runBuildBuildKit(dockerCli command.Cli, options buildOptions) error { func runBuildBuildKit(dockerCli command.Cli, options buildOptions) error {
ctx := appcontext.Context() ctx := appcontext.Context()
@ -92,7 +91,7 @@ func runBuildBuildKit(dockerCli command.Cli, options buildOptions) error {
dockerfileReader = rc dockerfileReader = rc
remote = clientSessionRemote remote = clientSessionRemote
// TODO: make fssync handle empty contextdir // TODO: make fssync handle empty contextdir
contextDir, _ = ioutil.TempDir("", "empty-dir") contextDir, _ = os.MkdirTemp("", "empty-dir")
defer os.RemoveAll(contextDir) defer os.RemoveAll(contextDir)
} }
case isLocalDir(options.context): case isLocalDir(options.context):
@ -249,7 +248,7 @@ func runBuildBuildKit(dockerCli command.Cli, options buildOptions) error {
return eg.Wait() return eg.Wait()
} }
//nolint: gocyclo // nolint: gocyclo
func doBuild(ctx context.Context, eg *errgroup.Group, dockerCli command.Cli, stdoutUsed bool, options buildOptions, buildOptions types.ImageBuildOptions, at session.Attachable) (finalErr error) { func doBuild(ctx context.Context, eg *errgroup.Group, dockerCli command.Cli, stdoutUsed bool, options buildOptions, buildOptions types.ImageBuildOptions, at session.Attachable) (finalErr error) {
response, err := dockerCli.Client().ImageBuild(context.Background(), nil, buildOptions) response, err := dockerCli.Client().ImageBuild(context.Background(), nil, buildOptions)
if err != nil { if err != nil {
@ -360,7 +359,7 @@ func doBuild(ctx context.Context, eg *errgroup.Group, dockerCli command.Cli, std
return errors.Errorf("cannot write %s because server did not provide an image ID", options.imageIDFile) return errors.Errorf("cannot write %s because server did not provide an image ID", options.imageIDFile)
} }
imageID = strings.TrimSpace(imageID) imageID = strings.TrimSpace(imageID)
if err := ioutil.WriteFile(options.imageIDFile, []byte(imageID), 0666); err != nil { if err := os.WriteFile(options.imageIDFile, []byte(imageID), 0666); err != nil {
return errors.Wrap(err, "cannot write image ID file") return errors.Wrap(err, "cannot write image ID file")
} }
} }

View File

@ -6,7 +6,6 @@ import (
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
@ -54,13 +53,13 @@ func tryNodeIdentifier() string {
if _, err := rand.Read(b); err != nil { if _, err := rand.Read(b); err != nil {
return out return out
} }
if err := ioutil.WriteFile(sessionFile, []byte(hex.EncodeToString(b)), 0600); err != nil { if err := os.WriteFile(sessionFile, []byte(hex.EncodeToString(b)), 0600); err != nil {
return out return out
} }
} }
} }
dt, err := ioutil.ReadFile(sessionFile) dt, err := os.ReadFile(sessionFile)
if err == nil { if err == nil {
return string(dt) return string(dt)
} }

View File

@ -7,7 +7,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"sort" "sort"
@ -41,7 +40,7 @@ func TestRunBuildDockerfileFromStdinWithCompress(t *testing.T) {
FROM alpine:3.6 FROM alpine:3.6
COPY foo / COPY foo /
`) `)
cli.SetIn(streams.NewIn(ioutil.NopCloser(dockerfile))) cli.SetIn(streams.NewIn(io.NopCloser(dockerfile)))
dir := fs.NewDir(t, t.Name(), dir := fs.NewDir(t, t.Name(),
fs.WithFile("foo", "some content")) fs.WithFile("foo", "some content"))
@ -130,7 +129,7 @@ func TestRunBuildFromGitHubSpecialCase(t *testing.T) {
cmd := NewBuildCommand(test.NewFakeCli(&fakeClient{})) cmd := NewBuildCommand(test.NewFakeCli(&fakeClient{}))
// Clone a small repo that exists so git doesn't prompt for credentials // Clone a small repo that exists so git doesn't prompt for credentials
cmd.SetArgs([]string{"github.com/docker/for-win"}) cmd.SetArgs([]string{"github.com/docker/for-win"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
err := cmd.Execute() err := cmd.Execute()
assert.ErrorContains(t, err, "unable to prepare context") assert.ErrorContains(t, err, "unable to prepare context")
assert.ErrorContains(t, err, "docker-build-git") assert.ErrorContains(t, err, "docker-build-git")
@ -141,20 +140,17 @@ func TestRunBuildFromGitHubSpecialCase(t *testing.T) {
// case. // case.
func TestRunBuildFromLocalGitHubDir(t *testing.T) { func TestRunBuildFromLocalGitHubDir(t *testing.T) {
defer env.Patch(t, "DOCKER_BUILDKIT", "0")() defer env.Patch(t, "DOCKER_BUILDKIT", "0")()
tmpDir, err := ioutil.TempDir("", "docker-build-from-local-dir-")
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
buildDir := filepath.Join(tmpDir, "github.com", "docker", "no-such-repository") buildDir := filepath.Join(t.TempDir(), "github.com", "docker", "no-such-repository")
err = os.MkdirAll(buildDir, 0777) err := os.MkdirAll(buildDir, 0777)
assert.NilError(t, err) assert.NilError(t, err)
err = ioutil.WriteFile(filepath.Join(buildDir, "Dockerfile"), []byte("FROM busybox\n"), 0644) err = os.WriteFile(filepath.Join(buildDir, "Dockerfile"), []byte("FROM busybox\n"), 0644)
assert.NilError(t, err) assert.NilError(t, err)
client := test.NewFakeCli(&fakeClient{}) client := test.NewFakeCli(&fakeClient{})
cmd := NewBuildCommand(client) cmd := NewBuildCommand(client)
cmd.SetArgs([]string{buildDir}) cmd.SetArgs([]string{buildDir})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
err = cmd.Execute() err = cmd.Execute()
assert.NilError(t, err) assert.NilError(t, err)
} }
@ -264,7 +260,7 @@ func (f *fakeBuild) build(_ context.Context, context io.Reader, options types.Im
f.context = tar.NewReader(context) f.context = tar.NewReader(context)
f.options = options f.options = options
body := new(bytes.Buffer) body := new(bytes.Buffer)
return types.ImageBuildResponse{Body: ioutil.NopCloser(body)}, nil return types.ImageBuildResponse{Body: io.NopCloser(body)}, nil
} }
func (f *fakeBuild) headers(t *testing.T) []*tar.Header { func (f *fakeBuild) headers(t *testing.T) []*tar.Header {

View File

@ -3,7 +3,6 @@ package image
import ( import (
"context" "context"
"io" "io"
"io/ioutil"
"strings" "strings"
"time" "time"
@ -41,7 +40,7 @@ func (cli *fakeClient) ImageSave(_ context.Context, images []string) (io.ReadClo
if cli.imageSaveFunc != nil { if cli.imageSaveFunc != nil {
return cli.imageSaveFunc(images) return cli.imageSaveFunc(images)
} }
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
} }
func (cli *fakeClient) ImageRemove(_ context.Context, image string, func (cli *fakeClient) ImageRemove(_ context.Context, image string,
@ -56,7 +55,7 @@ func (cli *fakeClient) ImagePush(_ context.Context, ref string, options types.Im
if cli.imagePushFunc != nil { if cli.imagePushFunc != nil {
return cli.imagePushFunc(ref, options) return cli.imagePushFunc(ref, options)
} }
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
} }
func (cli *fakeClient) Info(_ context.Context) (types.Info, error) { func (cli *fakeClient) Info(_ context.Context) (types.Info, error) {
@ -70,7 +69,7 @@ func (cli *fakeClient) ImagePull(_ context.Context, ref string, options types.Im
if cli.imagePullFunc != nil { if cli.imagePullFunc != nil {
cli.imagePullFunc(ref, options) cli.imagePullFunc(ref, options)
} }
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
} }
func (cli *fakeClient) ImagesPrune(_ context.Context, pruneFilter filters.Args) (types.ImagesPruneReport, error) { func (cli *fakeClient) ImagesPrune(_ context.Context, pruneFilter filters.Args) (types.ImagesPruneReport, error) {
@ -106,7 +105,7 @@ func (cli *fakeClient) ImageImport(_ context.Context, source types.ImageImportSo
if cli.imageImportFunc != nil { if cli.imageImportFunc != nil {
return cli.imageImportFunc(source, ref, options) return cli.imageImportFunc(source, ref, options)
} }
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
} }
func (cli *fakeClient) ImageHistory(_ context.Context, img string) ([]image.HistoryResponseItem, error) { func (cli *fakeClient) ImageHistory(_ context.Context, img string) ([]image.HistoryResponseItem, error) {
@ -120,5 +119,5 @@ func (cli *fakeClient) ImageBuild(ctx context.Context, context io.Reader, option
if cli.imageBuildFunc != nil { if cli.imageBuildFunc != nil {
return cli.imageBuildFunc(ctx, context, options) return cli.imageBuildFunc(ctx, context, options)
} }
return types.ImageBuildResponse{Body: ioutil.NopCloser(strings.NewReader(""))}, nil return types.ImageBuildResponse{Body: io.NopCloser(strings.NewReader(""))}, nil
} }

View File

@ -84,8 +84,8 @@ func TestHistoryContext_CreatedSince(t *testing.T) {
} }
func TestHistoryContext_CreatedBy(t *testing.T) { func TestHistoryContext_CreatedBy(t *testing.T) {
withTabs := `/bin/sh -c apt-key adv --keyserver hkp://pgp.mit.edu:80 --recv-keys 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62 && echo "deb http://nginx.org/packages/mainline/debian/ jessie nginx" >> /etc/apt/sources.list && apt-get update && apt-get install --no-install-recommends --no-install-suggests -y ca-certificates nginx=${NGINX_VERSION} nginx-module-xslt nginx-module-geoip nginx-module-image-filter nginx-module-perl nginx-module-njs gettext-base && rm -rf /var/lib/apt/lists/*` // nolint: lll withTabs := `/bin/sh -c apt-key adv --keyserver hkp://pgp.mit.edu:80 --recv-keys 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62 && echo "deb http://nginx.org/packages/mainline/debian/ jessie nginx" >> /etc/apt/sources.list && apt-get update && apt-get install --no-install-recommends --no-install-suggests -y ca-certificates nginx=${NGINX_VERSION} nginx-module-xslt nginx-module-geoip nginx-module-image-filter nginx-module-perl nginx-module-njs gettext-base && rm -rf /var/lib/apt/lists/*` //nolint:lll
expected := `/bin/sh -c apt-key adv --keyserver hkp://pgp.mit.edu:80 --recv-keys 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62 && echo "deb http://nginx.org/packages/mainline/debian/ jessie nginx" >> /etc/apt/sources.list && apt-get update && apt-get install --no-install-recommends --no-install-suggests -y ca-certificates nginx=${NGINX_VERSION} nginx-module-xslt nginx-module-geoip nginx-module-image-filter nginx-module-perl nginx-module-njs gettext-base && rm -rf /var/lib/apt/lists/*` // nolint: lll expected := `/bin/sh -c apt-key adv --keyserver hkp://pgp.mit.edu:80 --recv-keys 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62 && echo "deb http://nginx.org/packages/mainline/debian/ jessie nginx" >> /etc/apt/sources.list && apt-get update && apt-get install --no-install-recommends --no-install-suggests -y ca-certificates nginx=${NGINX_VERSION} nginx-module-xslt nginx-module-geoip nginx-module-image-filter nginx-module-perl nginx-module-njs gettext-base && rm -rf /var/lib/apt/lists/*` //nolint:lll
var ctx historyContext var ctx historyContext
cases := []historyCase{ cases := []historyCase{
@ -186,7 +186,6 @@ func TestHistoryContext_Table(t *testing.T) {
{ID: "imageID3", Created: unixTime, CreatedBy: "/bin/bash ls", Size: int64(182964289), Comment: "Hi", Tags: []string{"image:tag2"}}, {ID: "imageID3", Created: unixTime, CreatedBy: "/bin/bash ls", Size: int64(182964289), Comment: "Hi", Tags: []string{"image:tag2"}},
{ID: "imageID4", Created: unixTime, CreatedBy: "/bin/bash grep", Size: int64(182964289), Comment: "Hi", Tags: []string{"image:tag2"}}, {ID: "imageID4", Created: unixTime, CreatedBy: "/bin/bash grep", Size: int64(182964289), Comment: "Hi", Tags: []string{"image:tag2"}},
} }
// nolint: lll
expectedNoTrunc := `IMAGE CREATED CREATED BY SIZE COMMENT expectedNoTrunc := `IMAGE CREATED CREATED BY SIZE COMMENT
imageID1 24 hours ago /bin/bash ls && npm i && npm run test && karma -c karma.conf.js start && npm start && more commands here && the list goes on 183MB Hi imageID1 24 hours ago /bin/bash ls && npm i && npm run test && karma -c karma.conf.js start && npm start && more commands here && the list goes on 183MB Hi
imageID2 24 hours ago /bin/bash echo 183MB Hi imageID2 24 hours ago /bin/bash echo 183MB Hi

View File

@ -2,7 +2,7 @@ package image
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"time" "time"
@ -37,7 +37,7 @@ func TestNewHistoryCommandErrors(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
cmd := NewHistoryCommand(test.NewFakeCli(&fakeClient{imageHistoryFunc: tc.imageHistoryFunc})) cmd := NewHistoryCommand(test.NewFakeCli(&fakeClient{imageHistoryFunc: tc.imageHistoryFunc}))
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
@ -95,7 +95,7 @@ func TestNewHistoryCommandSuccess(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
cli := test.NewFakeCli(&fakeClient{imageHistoryFunc: tc.imageHistoryFunc}) cli := test.NewFakeCli(&fakeClient{imageHistoryFunc: tc.imageHistoryFunc})
cmd := NewHistoryCommand(cli) cmd := NewHistoryCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.NilError(t, err) assert.NilError(t, err)

View File

@ -2,7 +2,6 @@ package image
import ( import (
"io" "io"
"io/ioutil"
"strings" "strings"
"testing" "testing"
@ -36,7 +35,7 @@ func TestNewImportCommandErrors(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
cmd := NewImportCommand(test.NewFakeCli(&fakeClient{imageImportFunc: tc.imageImportFunc})) cmd := NewImportCommand(test.NewFakeCli(&fakeClient{imageImportFunc: tc.imageImportFunc}))
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
@ -44,7 +43,7 @@ func TestNewImportCommandErrors(t *testing.T) {
func TestNewImportCommandInvalidFile(t *testing.T) { func TestNewImportCommandInvalidFile(t *testing.T) {
cmd := NewImportCommand(test.NewFakeCli(&fakeClient{})) cmd := NewImportCommand(test.NewFakeCli(&fakeClient{}))
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"testdata/import-command-success.unexistent-file"}) cmd.SetArgs([]string{"testdata/import-command-success.unexistent-file"})
assert.ErrorContains(t, cmd.Execute(), "testdata/import-command-success.unexistent-file") assert.ErrorContains(t, cmd.Execute(), "testdata/import-command-success.unexistent-file")
} }
@ -68,7 +67,7 @@ func TestNewImportCommandSuccess(t *testing.T) {
args: []string{"-", "image:local"}, args: []string{"-", "image:local"},
imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) {
assert.Check(t, is.Equal("image:local", ref)) assert.Check(t, is.Equal("image:local", ref))
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
}, },
}, },
{ {
@ -76,7 +75,7 @@ func TestNewImportCommandSuccess(t *testing.T) {
args: []string{"--message", "test message", "-"}, args: []string{"--message", "test message", "-"},
imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) {
assert.Check(t, is.Equal("test message", options.Message)) assert.Check(t, is.Equal("test message", options.Message))
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
}, },
}, },
{ {
@ -84,7 +83,7 @@ func TestNewImportCommandSuccess(t *testing.T) {
args: []string{"--change", "ENV DEBUG=true", "-"}, args: []string{"--change", "ENV DEBUG=true", "-"},
imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) {
assert.Check(t, is.Equal("ENV DEBUG=true", options.Changes[0])) assert.Check(t, is.Equal("ENV DEBUG=true", options.Changes[0]))
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
}, },
}, },
{ {
@ -92,13 +91,13 @@ func TestNewImportCommandSuccess(t *testing.T) {
args: []string{"--change", "ENV DEBUG true", "-"}, args: []string{"--change", "ENV DEBUG true", "-"},
imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) {
assert.Check(t, is.Equal("ENV DEBUG true", options.Changes[0])) assert.Check(t, is.Equal("ENV DEBUG true", options.Changes[0]))
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
}, },
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
cmd := NewImportCommand(test.NewFakeCli(&fakeClient{imageImportFunc: tc.imageImportFunc})) cmd := NewImportCommand(test.NewFakeCli(&fakeClient{imageImportFunc: tc.imageImportFunc}))
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())
} }

View File

@ -2,7 +2,7 @@ package image
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -26,7 +26,7 @@ func TestNewInspectCommandErrors(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
cmd := newInspectCommand(test.NewFakeCli(&fakeClient{})) cmd := newInspectCommand(test.NewFakeCli(&fakeClient{}))
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
@ -78,7 +78,7 @@ func TestNewInspectCommandSuccess(t *testing.T) {
imageInspectInvocationCount = 0 imageInspectInvocationCount = 0
cli := test.NewFakeCli(&fakeClient{imageInspectFunc: tc.imageInspectFunc}) cli := test.NewFakeCli(&fakeClient{imageInspectFunc: tc.imageInspectFunc})
cmd := newInspectCommand(cli) cmd := newInspectCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.NilError(t, err) assert.NilError(t, err)

View File

@ -2,7 +2,7 @@ package image
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/cli/config/configfile" "github.com/docker/cli/cli/config/configfile"
@ -36,7 +36,7 @@ func TestNewImagesCommandErrors(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
cmd := NewImagesCommand(test.NewFakeCli(&fakeClient{imageListFunc: tc.imageListFunc})) cmd := NewImagesCommand(test.NewFakeCli(&fakeClient{imageListFunc: tc.imageListFunc}))
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
@ -82,7 +82,7 @@ func TestNewImagesCommandSuccess(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{imageListFunc: tc.imageListFunc}) cli := test.NewFakeCli(&fakeClient{imageListFunc: tc.imageListFunc})
cli.SetConfigFile(&configfile.ConfigFile{ImagesFormat: tc.imageFormat}) cli.SetConfigFile(&configfile.ConfigFile{ImagesFormat: tc.imageFormat})
cmd := NewImagesCommand(cli) cmd := NewImagesCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.NilError(t, err) assert.NilError(t, err)

View File

@ -3,7 +3,6 @@ package image
import ( import (
"fmt" "fmt"
"io" "io"
"io/ioutil"
"strings" "strings"
"testing" "testing"
@ -44,7 +43,7 @@ func TestNewLoadCommandErrors(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{imageLoadFunc: tc.imageLoadFunc}) cli := test.NewFakeCli(&fakeClient{imageLoadFunc: tc.imageLoadFunc})
cli.In().SetIsTerminal(tc.isTerminalIn) cli.In().SetIsTerminal(tc.isTerminalIn)
cmd := NewLoadCommand(cli) cmd := NewLoadCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
@ -53,7 +52,7 @@ func TestNewLoadCommandErrors(t *testing.T) {
func TestNewLoadCommandInvalidInput(t *testing.T) { func TestNewLoadCommandInvalidInput(t *testing.T) {
expectedError := "open *" expectedError := "open *"
cmd := NewLoadCommand(test.NewFakeCli(&fakeClient{})) cmd := NewLoadCommand(test.NewFakeCli(&fakeClient{}))
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"--input", "*"}) cmd.SetArgs([]string{"--input", "*"})
err := cmd.Execute() err := cmd.Execute()
assert.ErrorContains(t, err, expectedError) assert.ErrorContains(t, err, expectedError)
@ -68,7 +67,7 @@ func TestNewLoadCommandSuccess(t *testing.T) {
{ {
name: "simple", name: "simple",
imageLoadFunc: func(input io.Reader, quiet bool) (types.ImageLoadResponse, error) { imageLoadFunc: func(input io.Reader, quiet bool) (types.ImageLoadResponse, error) {
return types.ImageLoadResponse{Body: ioutil.NopCloser(strings.NewReader("Success"))}, nil return types.ImageLoadResponse{Body: io.NopCloser(strings.NewReader("Success"))}, nil
}, },
}, },
{ {
@ -76,7 +75,7 @@ func TestNewLoadCommandSuccess(t *testing.T) {
imageLoadFunc: func(input io.Reader, quiet bool) (types.ImageLoadResponse, error) { imageLoadFunc: func(input io.Reader, quiet bool) (types.ImageLoadResponse, error) {
json := "{\"ID\": \"1\"}" json := "{\"ID\": \"1\"}"
return types.ImageLoadResponse{ return types.ImageLoadResponse{
Body: ioutil.NopCloser(strings.NewReader(json)), Body: io.NopCloser(strings.NewReader(json)),
JSON: true, JSON: true,
}, nil }, nil
}, },
@ -85,14 +84,14 @@ func TestNewLoadCommandSuccess(t *testing.T) {
name: "input-file", name: "input-file",
args: []string{"--input", "testdata/load-command-success.input.txt"}, args: []string{"--input", "testdata/load-command-success.input.txt"},
imageLoadFunc: func(input io.Reader, quiet bool) (types.ImageLoadResponse, error) { imageLoadFunc: func(input io.Reader, quiet bool) (types.ImageLoadResponse, error) {
return types.ImageLoadResponse{Body: ioutil.NopCloser(strings.NewReader("Success"))}, nil return types.ImageLoadResponse{Body: io.NopCloser(strings.NewReader("Success"))}, nil
}, },
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
cli := test.NewFakeCli(&fakeClient{imageLoadFunc: tc.imageLoadFunc}) cli := test.NewFakeCli(&fakeClient{imageLoadFunc: tc.imageLoadFunc})
cmd := NewLoadCommand(cli) cmd := NewLoadCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.NilError(t, err) assert.NilError(t, err)

View File

@ -2,7 +2,7 @@ package image
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -39,7 +39,7 @@ func TestNewPruneCommandErrors(t *testing.T) {
cmd := NewPruneCommand(test.NewFakeCli(&fakeClient{ cmd := NewPruneCommand(test.NewFakeCli(&fakeClient{
imagesPruneFunc: tc.imagesPruneFunc, imagesPruneFunc: tc.imagesPruneFunc,
})) }))
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
@ -93,7 +93,7 @@ func TestNewPruneCommandSuccess(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
cli := test.NewFakeCli(&fakeClient{imagesPruneFunc: tc.imagesPruneFunc}) cli := test.NewFakeCli(&fakeClient{imagesPruneFunc: tc.imagesPruneFunc})
cmd := NewPruneCommand(cli) cmd := NewPruneCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.NilError(t, err) assert.NilError(t, err)

View File

@ -3,7 +3,6 @@ package image
import ( import (
"fmt" "fmt"
"io" "io"
"io/ioutil"
"strings" "strings"
"testing" "testing"
@ -40,7 +39,7 @@ func TestNewPullCommandErrors(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
cmd := NewPullCommand(cli) cmd := NewPullCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
@ -72,11 +71,11 @@ func TestNewPullCommandSuccess(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
imagePullFunc: func(ref string, options types.ImagePullOptions) (io.ReadCloser, error) { imagePullFunc: func(ref string, options types.ImagePullOptions) (io.ReadCloser, error) {
assert.Check(t, is.Equal(tc.expectedTag, ref), tc.name) assert.Check(t, is.Equal(tc.expectedTag, ref), tc.name)
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
}, },
}) })
cmd := NewPullCommand(cli) cmd := NewPullCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.NilError(t, err) assert.NilError(t, err)
@ -113,12 +112,12 @@ func TestNewPullCommandWithContentTrustErrors(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
cli := test.NewFakeCli(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
imagePullFunc: func(ref string, options types.ImagePullOptions) (io.ReadCloser, error) { imagePullFunc: func(ref string, options types.ImagePullOptions) (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader("")), fmt.Errorf("shouldn't try to pull image") return io.NopCloser(strings.NewReader("")), fmt.Errorf("shouldn't try to pull image")
}, },
}, test.EnableContentTrust) }, test.EnableContentTrust)
cli.SetNotaryClient(tc.notaryFunc) cli.SetNotaryClient(tc.notaryFunc)
cmd := NewPullCommand(cli) cmd := NewPullCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.ErrorContains(t, err, tc.expectedError) assert.ErrorContains(t, err, tc.expectedError)

View File

@ -3,7 +3,7 @@ package image
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"github.com/docker/cli/cli" "github.com/docker/cli/cli"
"github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command"
@ -93,7 +93,7 @@ func RunPush(dockerCli command.Cli, opts pushOptions) error {
} }
if opts.quiet { if opts.quiet {
err = jsonmessage.DisplayJSONMessagesToStream(responseBody, streams.NewOut(ioutil.Discard), nil) err = jsonmessage.DisplayJSONMessagesToStream(responseBody, streams.NewOut(io.Discard), nil)
if err == nil { if err == nil {
fmt.Fprintln(dockerCli.Out(), ref.String()) fmt.Fprintln(dockerCli.Out(), ref.String())
} }

View File

@ -2,7 +2,6 @@ package image
import ( import (
"io" "io"
"io/ioutil"
"strings" "strings"
"testing" "testing"
@ -34,14 +33,14 @@ func TestNewPushCommandErrors(t *testing.T) {
args: []string{"image:repo"}, args: []string{"image:repo"},
expectedError: "Failed to push", expectedError: "Failed to push",
imagePushFunc: func(ref string, options types.ImagePushOptions) (io.ReadCloser, error) { imagePushFunc: func(ref string, options types.ImagePushOptions) (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader("")), errors.Errorf("Failed to push") return io.NopCloser(strings.NewReader("")), errors.Errorf("Failed to push")
}, },
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
cli := test.NewFakeCli(&fakeClient{imagePushFunc: tc.imagePushFunc}) cli := test.NewFakeCli(&fakeClient{imagePushFunc: tc.imagePushFunc})
cmd := NewPushCommand(cli) cmd := NewPushCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
@ -69,7 +68,7 @@ func TestNewPushCommandSuccess(t *testing.T) {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
imagePushFunc: func(ref string, options types.ImagePushOptions) (io.ReadCloser, error) { imagePushFunc: func(ref string, options types.ImagePushOptions) (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
}, },
}) })
cmd := NewPushCommand(cli) cmd := NewPushCommand(cli)

View File

@ -2,7 +2,7 @@ package image
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -68,7 +68,7 @@ func TestNewRemoveCommandErrors(t *testing.T) {
cmd := NewRemoveCommand(test.NewFakeCli(&fakeClient{ cmd := NewRemoveCommand(test.NewFakeCli(&fakeClient{
imageRemoveFunc: tc.imageRemoveFunc, imageRemoveFunc: tc.imageRemoveFunc,
})) }))
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
}) })
@ -124,7 +124,7 @@ func TestNewRemoveCommandSuccess(t *testing.T) {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{imageRemoveFunc: tc.imageRemoveFunc}) cli := test.NewFakeCli(&fakeClient{imageRemoveFunc: tc.imageRemoveFunc})
cmd := NewRemoveCommand(cli) cmd := NewRemoveCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())
assert.Check(t, is.Equal(tc.expectedStderr, cli.ErrBuffer().String())) assert.Check(t, is.Equal(tc.expectedStderr, cli.ErrBuffer().String()))

View File

@ -2,7 +2,6 @@ package image
import ( import (
"io" "io"
"io/ioutil"
"os" "os"
"strings" "strings"
"testing" "testing"
@ -38,7 +37,7 @@ func TestNewSaveCommandErrors(t *testing.T) {
isTerminal: false, isTerminal: false,
expectedError: "error saving image", expectedError: "error saving image",
imageSaveFunc: func(images []string) (io.ReadCloser, error) { imageSaveFunc: func(images []string) (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader("")), errors.Errorf("error saving image") return io.NopCloser(strings.NewReader("")), errors.Errorf("error saving image")
}, },
}, },
{ {
@ -56,7 +55,7 @@ func TestNewSaveCommandErrors(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{imageSaveFunc: tc.imageSaveFunc}) cli := test.NewFakeCli(&fakeClient{imageSaveFunc: tc.imageSaveFunc})
cli.Out().SetIsTerminal(tc.isTerminal) cli.Out().SetIsTerminal(tc.isTerminal)
cmd := NewSaveCommand(cli) cmd := NewSaveCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
@ -75,7 +74,7 @@ func TestNewSaveCommandSuccess(t *testing.T) {
imageSaveFunc: func(images []string) (io.ReadCloser, error) { imageSaveFunc: func(images []string) (io.ReadCloser, error) {
assert.Assert(t, is.Len(images, 1)) assert.Assert(t, is.Len(images, 1))
assert.Check(t, is.Equal("arg1", images[0])) assert.Check(t, is.Equal("arg1", images[0]))
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
}, },
deferredFunc: func() { deferredFunc: func() {
os.Remove("save_tmp_file") os.Remove("save_tmp_file")
@ -88,17 +87,17 @@ func TestNewSaveCommandSuccess(t *testing.T) {
assert.Assert(t, is.Len(images, 2)) assert.Assert(t, is.Len(images, 2))
assert.Check(t, is.Equal("arg1", images[0])) assert.Check(t, is.Equal("arg1", images[0]))
assert.Check(t, is.Equal("arg2", images[1])) assert.Check(t, is.Equal("arg2", images[1]))
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
}, },
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
cmd := NewSaveCommand(test.NewFakeCli(&fakeClient{ cmd := NewSaveCommand(test.NewFakeCli(&fakeClient{
imageSaveFunc: func(images []string) (io.ReadCloser, error) { imageSaveFunc: func(images []string) (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
}, },
})) }))
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())
if tc.deferredFunc != nil { if tc.deferredFunc != nil {

View File

@ -1,7 +1,7 @@
package image package image
import ( import (
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -19,7 +19,7 @@ func TestCliNewTagCommandErrors(t *testing.T) {
for _, args := range testCases { for _, args := range testCases {
cmd := NewTagCommand(test.NewFakeCli(&fakeClient{})) cmd := NewTagCommand(test.NewFakeCli(&fakeClient{}))
cmd.SetArgs(args) cmd.SetArgs(args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), expectedError) assert.ErrorContains(t, cmd.Execute(), expectedError)
} }
} }
@ -34,7 +34,7 @@ func TestCliNewTagCommand(t *testing.T) {
}, },
})) }))
cmd.SetArgs([]string{"image1", "image2"}) cmd.SetArgs([]string{"image1", "image2"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())
value, _ := cmd.Flags().GetBool("interspersed") value, _ := cmd.Flags().GetBool("interspersed")
assert.Check(t, !value) assert.Check(t, !value)

View File

@ -6,7 +6,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"sort" "sort"
"github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command"
@ -43,7 +42,8 @@ func TrustedPush(ctx context.Context, cli command.Cli, repoInfo *registry.Reposi
} }
// PushTrustedReference pushes a canonical reference to the trust server. // PushTrustedReference pushes a canonical reference to the trust server.
// nolint: gocyclo //
//nolint:gocyclo
func PushTrustedReference(streams command.Streams, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig types.AuthConfig, in io.Reader) error { func PushTrustedReference(streams command.Streams, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig types.AuthConfig, in io.Reader) error {
// If it is a trusted push we would like to find the target entry which match the // If it is a trusted push we would like to find the target entry which match the
// tag provided in the function and then do an AddTarget later. // tag provided in the function and then do an AddTarget later.
@ -283,7 +283,7 @@ func imagePullPrivileged(ctx context.Context, cli command.Cli, imgRefAndAuth tru
out := cli.Out() out := cli.Out()
if opts.quiet { if opts.quiet {
out = streams.NewOut(ioutil.Discard) out = streams.NewOut(io.Discard)
} }
return jsonmessage.DisplayJSONMessagesToStream(responseBody, out, nil) return jsonmessage.DisplayJSONMessagesToStream(responseBody, out, nil)
} }

View File

@ -1,8 +1,6 @@
package image package image
import ( import (
"io/ioutil"
"os"
"testing" "testing"
"github.com/docker/cli/cli/trust" "github.com/docker/cli/cli/trust"
@ -51,11 +49,7 @@ func TestNonOfficialTrustServer(t *testing.T) {
} }
func TestAddTargetToAllSignableRolesError(t *testing.T) { func TestAddTargetToAllSignableRolesError(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "notary-test-") notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{})
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{})
assert.NilError(t, err) assert.NilError(t, err)
target := client.Target{} target := client.Target{}
err = AddTargetToAllSignableRoles(notaryRepo, &target) err = AddTargetToAllSignableRoles(notaryRepo, &target)

View File

@ -1,9 +1,10 @@
package manifest package manifest
import ( import (
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/cli/manifest/store"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
"gotest.tools/v3/assert" "gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp" is "gotest.tools/v3/assert/cmp"
@ -33,14 +34,13 @@ func TestManifestAnnotateError(t *testing.T) {
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cmd := newAnnotateCommand(cli) cmd := newAnnotateCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
func TestManifestAnnotate(t *testing.T) { func TestManifestAnnotate(t *testing.T) {
store, cleanup := newTempManifestStore(t) store := store.NewStore(t.TempDir())
defer cleanup()
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cli.SetManifestStore(store) cli.SetManifestStore(store)
@ -51,7 +51,7 @@ func TestManifestAnnotate(t *testing.T) {
cmd := newAnnotateCommand(cli) cmd := newAnnotateCommand(cli)
cmd.SetArgs([]string{"example.com/list:v1", "example.com/fake:0.0"}) cmd.SetArgs([]string{"example.com/list:v1", "example.com/fake:0.0"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
expectedError := "manifest for image example.com/fake:0.0 does not exist" expectedError := "manifest for image example.com/fake:0.0 does not exist"
assert.ErrorContains(t, cmd.Execute(), expectedError) assert.ErrorContains(t, cmd.Execute(), expectedError)

View File

@ -2,9 +2,10 @@ package manifest
import ( import (
"context" "context"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/cli/manifest/store"
manifesttypes "github.com/docker/cli/cli/manifest/types" manifesttypes "github.com/docker/cli/cli/manifest/types"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
@ -33,15 +34,14 @@ func TestManifestCreateErrors(t *testing.T) {
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cmd := newCreateListCommand(cli) cmd := newCreateListCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
// create a manifest list, then overwrite it, and inspect to see if the old one is still there // create a manifest list, then overwrite it, and inspect to see if the old one is still there
func TestManifestCreateAmend(t *testing.T) { func TestManifestCreateAmend(t *testing.T) {
store, cleanup := newTempManifestStore(t) store := store.NewStore(t.TempDir())
defer cleanup()
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cli.SetManifestStore(store) cli.SetManifestStore(store)
@ -58,7 +58,7 @@ func TestManifestCreateAmend(t *testing.T) {
cmd := newCreateListCommand(cli) cmd := newCreateListCommand(cli)
cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.1"}) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.1"})
cmd.Flags().Set("amend", "true") cmd.Flags().Set("amend", "true")
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
err = cmd.Execute() err = cmd.Execute()
assert.NilError(t, err) assert.NilError(t, err)
@ -75,8 +75,7 @@ func TestManifestCreateAmend(t *testing.T) {
// attempt to overwrite a saved manifest and get refused // attempt to overwrite a saved manifest and get refused
func TestManifestCreateRefuseAmend(t *testing.T) { func TestManifestCreateRefuseAmend(t *testing.T) {
store, cleanup := newTempManifestStore(t) store := store.NewStore(t.TempDir())
defer cleanup()
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cli.SetManifestStore(store) cli.SetManifestStore(store)
@ -87,15 +86,14 @@ func TestManifestCreateRefuseAmend(t *testing.T) {
cmd := newCreateListCommand(cli) cmd := newCreateListCommand(cli)
cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"}) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
err = cmd.Execute() err = cmd.Execute()
assert.Error(t, err, "refusing to amend an existing manifest list with no --amend flag") assert.Error(t, err, "refusing to amend an existing manifest list with no --amend flag")
} }
// attempt to make a manifest list without valid images // attempt to make a manifest list without valid images
func TestManifestCreateNoManifest(t *testing.T) { func TestManifestCreateNoManifest(t *testing.T) {
store, cleanup := newTempManifestStore(t) store := store.NewStore(t.TempDir())
defer cleanup()
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cli.SetManifestStore(store) cli.SetManifestStore(store)
@ -110,7 +108,7 @@ func TestManifestCreateNoManifest(t *testing.T) {
cmd := newCreateListCommand(cli) cmd := newCreateListCommand(cli)
cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"}) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
err := cmd.Execute() err := cmd.Execute()
assert.Error(t, err, "No such image: example.com/alpine:3.0") assert.Error(t, err, "No such image: example.com/alpine:3.0")
} }

View File

@ -2,13 +2,11 @@ package manifest
import ( import (
"context" "context"
"io/ioutil" "io"
"os"
"testing" "testing"
"github.com/docker/cli/cli/manifest/store" "github.com/docker/cli/cli/manifest/store"
"github.com/docker/cli/cli/manifest/types" "github.com/docker/cli/cli/manifest/types"
manifesttypes "github.com/docker/cli/cli/manifest/types"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/manifest/schema2" "github.com/docker/distribution/manifest/schema2"
@ -21,13 +19,6 @@ import (
"gotest.tools/v3/golden" "gotest.tools/v3/golden"
) )
func newTempManifestStore(t *testing.T) (store.Store, func()) {
tmpdir, err := ioutil.TempDir("", "test-manifest-storage")
assert.NilError(t, err)
return store.NewStore(tmpdir), func() { os.RemoveAll(tmpdir) }
}
func ref(t *testing.T, name string) reference.Named { func ref(t *testing.T, name string) reference.Named {
named, err := reference.ParseNamed("example.com/" + name) named, err := reference.ParseNamed("example.com/" + name)
assert.NilError(t, err) assert.NilError(t, err)
@ -70,44 +61,41 @@ func fullImageManifest(t *testing.T, ref reference.Named) types.ImageManifest {
} }
func TestInspectCommandLocalManifestNotFound(t *testing.T) { func TestInspectCommandLocalManifestNotFound(t *testing.T) {
store, cleanup := newTempManifestStore(t) store := store.NewStore(t.TempDir())
defer cleanup()
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cli.SetManifestStore(store) cli.SetManifestStore(store)
cmd := newInspectCommand(cli) cmd := newInspectCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"}) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"})
err := cmd.Execute() err := cmd.Execute()
assert.Error(t, err, "No such manifest: example.com/alpine:3.0") assert.Error(t, err, "No such manifest: example.com/alpine:3.0")
} }
func TestInspectCommandNotFound(t *testing.T) { func TestInspectCommandNotFound(t *testing.T) {
store, cleanup := newTempManifestStore(t) store := store.NewStore(t.TempDir())
defer cleanup()
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cli.SetManifestStore(store) cli.SetManifestStore(store)
cli.SetRegistryClient(&fakeRegistryClient{ cli.SetRegistryClient(&fakeRegistryClient{
getManifestFunc: func(_ context.Context, _ reference.Named) (manifesttypes.ImageManifest, error) { getManifestFunc: func(_ context.Context, _ reference.Named) (types.ImageManifest, error) {
return manifesttypes.ImageManifest{}, errors.New("missing") return types.ImageManifest{}, errors.New("missing")
}, },
getManifestListFunc: func(ctx context.Context, ref reference.Named) ([]manifesttypes.ImageManifest, error) { getManifestListFunc: func(ctx context.Context, ref reference.Named) ([]types.ImageManifest, error) {
return nil, errors.Errorf("No such manifest: %s", ref) return nil, errors.Errorf("No such manifest: %s", ref)
}, },
}) })
cmd := newInspectCommand(cli) cmd := newInspectCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"example.com/alpine:3.0"}) cmd.SetArgs([]string{"example.com/alpine:3.0"})
err := cmd.Execute() err := cmd.Execute()
assert.Error(t, err, "No such manifest: example.com/alpine:3.0") assert.Error(t, err, "No such manifest: example.com/alpine:3.0")
} }
func TestInspectCommandLocalManifest(t *testing.T) { func TestInspectCommandLocalManifest(t *testing.T) {
store, cleanup := newTempManifestStore(t) store := store.NewStore(t.TempDir())
defer cleanup()
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cli.SetManifestStore(store) cli.SetManifestStore(store)
@ -125,19 +113,18 @@ func TestInspectCommandLocalManifest(t *testing.T) {
} }
func TestInspectcommandRemoteManifest(t *testing.T) { func TestInspectcommandRemoteManifest(t *testing.T) {
store, cleanup := newTempManifestStore(t) store := store.NewStore(t.TempDir())
defer cleanup()
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cli.SetManifestStore(store) cli.SetManifestStore(store)
cli.SetRegistryClient(&fakeRegistryClient{ cli.SetRegistryClient(&fakeRegistryClient{
getManifestFunc: func(_ context.Context, ref reference.Named) (manifesttypes.ImageManifest, error) { getManifestFunc: func(_ context.Context, ref reference.Named) (types.ImageManifest, error) {
return fullImageManifest(t, ref), nil return fullImageManifest(t, ref), nil
}, },
}) })
cmd := newInspectCommand(cli) cmd := newInspectCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"example.com/alpine:3.0"}) cmd.SetArgs([]string{"example.com/alpine:3.0"})
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())
actual := cli.OutBuffer() actual := cli.OutBuffer()

View File

@ -2,9 +2,10 @@ package manifest
import ( import (
"context" "context"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/cli/manifest/store"
manifesttypes "github.com/docker/cli/cli/manifest/types" manifesttypes "github.com/docker/cli/cli/manifest/types"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
@ -42,14 +43,13 @@ func TestManifestPushErrors(t *testing.T) {
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cmd := newPushListCommand(cli) cmd := newPushListCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
func TestManifestPush(t *testing.T) { func TestManifestPush(t *testing.T) {
store, sCleanup := newTempManifestStore(t) store := store.NewStore(t.TempDir())
defer sCleanup()
registry := newFakeRegistryClient() registry := newFakeRegistryClient()

View File

@ -1,17 +1,17 @@
package manifest package manifest
import ( import (
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/cli/manifest/store"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
"gotest.tools/v3/assert" "gotest.tools/v3/assert"
) )
// create two manifest lists and remove them both // create two manifest lists and remove them both
func TestRmSeveralManifests(t *testing.T) { func TestRmSeveralManifests(t *testing.T) {
store, cleanup := newTempManifestStore(t) store := store.NewStore(t.TempDir())
defer cleanup()
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cli.SetManifestStore(store) cli.SetManifestStore(store)
@ -31,7 +31,7 @@ func TestRmSeveralManifests(t *testing.T) {
cmd := newRmManifestListCommand(cli) cmd := newRmManifestListCommand(cli)
cmd.SetArgs([]string{"example.com/first:1", "example.com/second:2"}) cmd.SetArgs([]string{"example.com/first:1", "example.com/second:2"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
err = cmd.Execute() err = cmd.Execute()
assert.NilError(t, err) assert.NilError(t, err)
@ -43,8 +43,7 @@ func TestRmSeveralManifests(t *testing.T) {
// attempt to remove a manifest list which was never created // attempt to remove a manifest list which was never created
func TestRmManifestNotCreated(t *testing.T) { func TestRmManifestNotCreated(t *testing.T) {
store, cleanup := newTempManifestStore(t) store := store.NewStore(t.TempDir())
defer cleanup()
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cli.SetManifestStore(store) cli.SetManifestStore(store)
@ -56,7 +55,7 @@ func TestRmManifestNotCreated(t *testing.T) {
cmd := newRmManifestListCommand(cli) cmd := newRmManifestListCommand(cli)
cmd.SetArgs([]string{"example.com/first:1", "example.com/second:2"}) cmd.SetArgs([]string{"example.com/first:1", "example.com/second:2"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
err = cmd.Execute() err = cmd.Execute()
assert.Error(t, err, "No such manifest: example.com/first:1") assert.Error(t, err, "No such manifest: example.com/first:1")

View File

@ -68,7 +68,7 @@ func normalizeReference(ref string) (reference.Named, error) {
} }
// getManifest from the local store, and fallback to the remote registry if it // getManifest from the local store, and fallback to the remote registry if it
// doesn't exist locally // doesn't exist locally
func getManifest(ctx context.Context, dockerCli command.Cli, listRef, namedRef reference.Named, insecure bool) (types.ImageManifest, error) { func getManifest(ctx context.Context, dockerCli command.Cli, listRef, namedRef reference.Named, insecure bool) (types.ImageManifest, error) {
data, err := dockerCli.ManifestStore().Get(listRef, namedRef) data, err := dockerCli.ManifestStore().Get(listRef, namedRef)
switch { switch {

View File

@ -2,7 +2,7 @@ package network
import ( import (
"context" "context"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -37,7 +37,7 @@ func TestNetworkConnectErrors(t *testing.T) {
}), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }

View File

@ -128,7 +128,8 @@ func runCreate(dockerCli command.Cli, options createOptions) error {
// possible to correlate the various related parameters and consolidate them. // possible to correlate the various related parameters and consolidate them.
// consolidateIpam consolidates subnets, ip-ranges, gateways and auxiliary addresses into // consolidateIpam consolidates subnets, ip-ranges, gateways and auxiliary addresses into
// structured ipam data. // structured ipam data.
// nolint: gocyclo //
//nolint:gocyclo
func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]string) ([]network.IPAMConfig, error) { func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]string) ([]network.IPAMConfig, error) {
if len(subnets) < len(ranges) || len(subnets) < len(gateways) { if len(subnets) < len(ranges) || len(subnets) < len(gateways) {
return nil, errors.Errorf("every ip-range or gateway must have a corresponding subnet") return nil, errors.Errorf("every ip-range or gateway must have a corresponding subnet")

View File

@ -2,7 +2,7 @@ package network
import ( import (
"context" "context"
"io/ioutil" "io"
"strings" "strings"
"testing" "testing"
@ -137,7 +137,7 @@ func TestNetworkCreateErrors(t *testing.T) {
for key, value := range tc.flags { for key, value := range tc.flags {
assert.NilError(t, cmd.Flags().Set(key, value)) assert.NilError(t, cmd.Flags().Set(key, value))
} }
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }

View File

@ -2,7 +2,7 @@ package network
import ( import (
"context" "context"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -35,7 +35,7 @@ func TestNetworkDisconnectErrors(t *testing.T) {
}), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -2,7 +2,7 @@ package network
import ( import (
"context" "context"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -35,7 +35,7 @@ func TestNetworkListErrors(t *testing.T) {
networkListFunc: tc.networkListFunc, networkListFunc: tc.networkListFunc,
}), }),
) )
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -1,7 +1,7 @@
package node package node
import ( import (
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -43,7 +43,7 @@ func TestNodeDemoteErrors(t *testing.T) {
nodeUpdateFunc: tc.nodeUpdateFunc, nodeUpdateFunc: tc.nodeUpdateFunc,
})) }))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -2,7 +2,7 @@ package node
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -73,7 +73,7 @@ func TestNodeInspectErrors(t *testing.T) {
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -1,7 +1,7 @@
package node package node
import ( import (
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/cli/config/configfile" "github.com/docker/cli/cli/config/configfile"
@ -47,7 +47,7 @@ func TestNodeListErrorOnAPIFailure(t *testing.T) {
infoFunc: tc.infoFunc, infoFunc: tc.infoFunc,
}) })
cmd := newListCommand(cli) cmd := newListCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.Error(t, cmd.Execute(), tc.expectedError) assert.Error(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -1,7 +1,7 @@
package node package node
import ( import (
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -43,7 +43,7 @@ func TestNodePromoteErrors(t *testing.T) {
nodeUpdateFunc: tc.nodeUpdateFunc, nodeUpdateFunc: tc.nodeUpdateFunc,
})) }))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -3,7 +3,7 @@ package node
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"time" "time"
@ -59,7 +59,7 @@ func TestNodePsErrors(t *testing.T) {
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.Error(t, cmd.Execute(), tc.expectedError) assert.Error(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -1,7 +1,7 @@
package node package node
import ( import (
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -32,7 +32,7 @@ func TestNodeRemoveErrors(t *testing.T) {
nodeRemoveFunc: tc.nodeRemoveFunc, nodeRemoveFunc: tc.nodeRemoveFunc,
})) }))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -1,7 +1,7 @@
package node package node
import ( import (
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -63,7 +63,7 @@ func TestNodeUpdateErrors(t *testing.T) {
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -1,7 +1,7 @@
package command package command
import ( import (
"io/ioutil" "io"
"testing" "testing"
"gotest.tools/v3/assert" "gotest.tools/v3/assert"
@ -91,7 +91,7 @@ func TestOrchestratorSwitch(t *testing.T) {
if testcase.envOrchestrator != "" { if testcase.envOrchestrator != "" {
defer env.Patch(t, "DOCKER_STACK_ORCHESTRATOR", testcase.envOrchestrator)() defer env.Patch(t, "DOCKER_STACK_ORCHESTRATOR", testcase.envOrchestrator)()
} }
orchestrator, err := GetStackOrchestrator(testcase.flagOrchestrator, testcase.contextOrchestrator, testcase.globalOrchestrator, ioutil.Discard) orchestrator, err := GetStackOrchestrator(testcase.flagOrchestrator, testcase.contextOrchestrator, testcase.globalOrchestrator, io.Discard)
assert.NilError(t, err) assert.NilError(t, err)
assert.Check(t, is.Equal(testcase.expectedKubernetes, orchestrator.HasKubernetes())) assert.Check(t, is.Equal(testcase.expectedKubernetes, orchestrator.HasKubernetes()))
assert.Check(t, is.Equal(testcase.expectedSwarm, orchestrator.HasSwarm())) assert.Check(t, is.Equal(testcase.expectedSwarm, orchestrator.HasSwarm()))

View File

@ -3,7 +3,6 @@ package plugin
import ( import (
"fmt" "fmt"
"io" "io"
"io/ioutil"
"runtime" "runtime"
"testing" "testing"
@ -41,7 +40,7 @@ func TestCreateErrors(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
cmd := newCreateCommand(cli) cmd := newCreateCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
@ -53,7 +52,7 @@ func TestCreateErrorOnFileAsContextDir(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
cmd := newCreateCommand(cli) cmd := newCreateCommand(cli)
cmd.SetArgs([]string{"plugin-foo", tmpFile.Path()}) cmd.SetArgs([]string{"plugin-foo", tmpFile.Path()})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), "context must be a directory") assert.ErrorContains(t, cmd.Execute(), "context must be a directory")
} }
@ -64,7 +63,7 @@ func TestCreateErrorOnContextDirWithoutConfig(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
cmd := newCreateCommand(cli) cmd := newCreateCommand(cli)
cmd.SetArgs([]string{"plugin-foo", tmpDir.Path()}) cmd.SetArgs([]string{"plugin-foo", tmpDir.Path()})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
expectedErr := "config.json: no such file or directory" expectedErr := "config.json: no such file or directory"
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
@ -82,7 +81,7 @@ func TestCreateErrorOnInvalidConfig(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
cmd := newCreateCommand(cli) cmd := newCreateCommand(cli)
cmd.SetArgs([]string{"plugin-foo", tmpDir.Path()}) cmd.SetArgs([]string{"plugin-foo", tmpDir.Path()})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), "invalid") assert.ErrorContains(t, cmd.Execute(), "invalid")
} }
@ -100,7 +99,7 @@ func TestCreateErrorFromDaemon(t *testing.T) {
cmd := newCreateCommand(cli) cmd := newCreateCommand(cli)
cmd.SetArgs([]string{"plugin-foo", tmpDir.Path()}) cmd.SetArgs([]string{"plugin-foo", tmpDir.Path()})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), "Error creating plugin") assert.ErrorContains(t, cmd.Execute(), "Error creating plugin")
} }

View File

@ -2,7 +2,7 @@ package plugin
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -40,7 +40,7 @@ func TestPluginDisableErrors(t *testing.T) {
pluginDisableFunc: tc.pluginDisableFunc, pluginDisableFunc: tc.pluginDisableFunc,
})) }))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -2,7 +2,7 @@ package plugin
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -51,7 +51,7 @@ func TestPluginEnableErrors(t *testing.T) {
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -2,7 +2,7 @@ package plugin
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -73,7 +73,7 @@ func TestInspectErrors(t *testing.T) {
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
}) })
} }

View File

@ -3,7 +3,6 @@ package plugin
import ( import (
"fmt" "fmt"
"io" "io"
"io/ioutil"
"strings" "strings"
"testing" "testing"
@ -58,7 +57,7 @@ func TestInstallErrors(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{pluginInstallFunc: tc.installFunc}) cli := test.NewFakeCli(&fakeClient{pluginInstallFunc: tc.installFunc})
cmd := newInstallCommand(cli) cmd := newInstallCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
@ -100,7 +99,7 @@ func TestInstallContentTrustErrors(t *testing.T) {
cli.SetNotaryClient(tc.notaryFunc) cli.SetNotaryClient(tc.notaryFunc)
cmd := newInstallCommand(cli) cmd := newInstallCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
@ -117,7 +116,7 @@ func TestInstall(t *testing.T) {
args: []string{"foo"}, args: []string{"foo"},
expectedOutput: "Installed plugin foo\n", expectedOutput: "Installed plugin foo\n",
installFunc: func(name string, options types.PluginInstallOptions) (io.ReadCloser, error) { installFunc: func(name string, options types.PluginInstallOptions) (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
}, },
}, },
{ {
@ -126,7 +125,7 @@ func TestInstall(t *testing.T) {
expectedOutput: "Installed plugin foo\n", expectedOutput: "Installed plugin foo\n",
installFunc: func(name string, options types.PluginInstallOptions) (io.ReadCloser, error) { installFunc: func(name string, options types.PluginInstallOptions) (io.ReadCloser, error) {
assert.Check(t, options.Disabled) assert.Check(t, options.Disabled)
return ioutil.NopCloser(strings.NewReader("")), nil return io.NopCloser(strings.NewReader("")), nil
}, },
}, },
} }

View File

@ -2,7 +2,7 @@ package plugin
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -52,7 +52,7 @@ func TestListErrors(t *testing.T) {
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -2,7 +2,7 @@ package plugin
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -37,7 +37,7 @@ func TestRemoveErrors(t *testing.T) {
}) })
cmd := newRemoveCommand(cli) cmd := newRemoveCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -3,7 +3,7 @@ package registry
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"strings" "strings"
"github.com/docker/cli/cli" "github.com/docker/cli/cli"
@ -84,7 +84,7 @@ func verifyloginOptions(dockerCli command.Cli, opts *loginOptions) error {
return errors.New("Must provide --username with --password-stdin") return errors.New("Must provide --username with --password-stdin")
} }
contents, err := ioutil.ReadAll(dockerCli.In()) contents, err := io.ReadAll(dockerCli.In())
if err != nil { if err != nil {
return err return err
} }
@ -95,7 +95,7 @@ func verifyloginOptions(dockerCli command.Cli, opts *loginOptions) error {
return nil return nil
} }
func runLogin(dockerCli command.Cli, opts loginOptions) error { //nolint: gocyclo func runLogin(dockerCli command.Cli, opts loginOptions) error { //nolint:gocyclo
ctx := context.Background() ctx := context.Background()
clnt := dockerCli.Client() clnt := dockerCli.Client()
if err := verifyloginOptions(dockerCli, &opts); err != nil { if err := verifyloginOptions(dockerCli, &opts); err != nil {

View File

@ -4,7 +4,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"github.com/docker/cli/cli" "github.com/docker/cli/cli"
"github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command"
@ -101,7 +100,7 @@ func readSecretData(in io.ReadCloser, file string) ([]byte, error) {
} }
defer in.Close() defer in.Close()
} }
data, err := ioutil.ReadAll(in) data, err := io.ReadAll(in)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -1,7 +1,8 @@
package secret package secret
import ( import (
"io/ioutil" "io"
"os"
"path/filepath" "path/filepath"
"reflect" "reflect"
"strings" "strings"
@ -44,14 +45,14 @@ func TestSecretCreateErrors(t *testing.T) {
}), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
func TestSecretCreateWithName(t *testing.T) { func TestSecretCreateWithName(t *testing.T) {
name := "foo" name := "foo"
data, err := ioutil.ReadFile(filepath.Join("testdata", secretDataFile)) data, err := os.ReadFile(filepath.Join("testdata", secretDataFile))
assert.NilError(t, err) assert.NilError(t, err)
expected := swarm.SecretSpec{ expected := swarm.SecretSpec{

View File

@ -2,7 +2,7 @@ package secret
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"time" "time"
@ -59,7 +59,7 @@ func TestSecretInspectErrors(t *testing.T) {
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -1,7 +1,7 @@
package secret package secret
import ( import (
"io/ioutil" "io"
"testing" "testing"
"time" "time"
@ -40,7 +40,7 @@ func TestSecretListErrors(t *testing.T) {
}), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

View File

@ -1,7 +1,7 @@
package secret package secret
import ( import (
"io/ioutil" "io"
"strings" "strings"
"testing" "testing"
@ -36,7 +36,7 @@ func TestSecretRemoveErrors(t *testing.T) {
}), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
@ -72,7 +72,7 @@ func TestSecretRemoveContinueAfterError(t *testing.T) {
}) })
cmd := newSecretRemoveCommand(cli) cmd := newSecretRemoveCommand(cli)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.SetArgs(names) cmd.SetArgs(names)
assert.Error(t, cmd.Execute(), "error removing secret: foo") assert.Error(t, cmd.Execute(), "error removing secret: foo")
assert.Check(t, is.DeepEqual(names, removedSecrets)) assert.Check(t, is.DeepEqual(names, removedSecrets))

View File

@ -3,7 +3,6 @@ package service
import ( import (
"context" "context"
"io" "io"
"io/ioutil"
"github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/service/progress" "github.com/docker/cli/cli/command/service/progress"
@ -21,7 +20,7 @@ func waitOnService(ctx context.Context, dockerCli command.Cli, serviceID string,
}() }()
if quiet { if quiet {
go io.Copy(ioutil.Discard, pipeReader) go io.Copy(io.Discard, pipeReader)
return <-errChan return <-errChan
} }

View File

@ -106,7 +106,6 @@ func runList(dockerCli command.Cli, opts listOptions) error {
// there may be other situations where the client uses the "default" version. // there may be other situations where the client uses the "default" version.
// To take these situations into account, we do a quick check for services // To take these situations into account, we do a quick check for services
// that don't have ServiceStatus set, and perform a lookup for those. // that don't have ServiceStatus set, and perform a lookup for those.
// nolint: gocyclo
func AppendServiceStatus(ctx context.Context, c client.APIClient, services []swarm.Service) ([]swarm.Service, error) { func AppendServiceStatus(ctx context.Context, c client.APIClient, services []swarm.Service) ([]swarm.Service, error) {
status := map[string]*swarm.ServiceStatus{} status := map[string]*swarm.ServiceStatus{}
taskFilter := filters.NewArgs() taskFilter := filters.NewArgs()

View File

@ -466,9 +466,13 @@ func (opts *healthCheckOptions) toHealthConfig() (*container.HealthConfig, error
} }
// convertExtraHostsToSwarmHosts converts an array of extra hosts in cli // convertExtraHostsToSwarmHosts converts an array of extra hosts in cli
// <host>:<ip> //
// <host>:<ip>
//
// into a swarmkit host format: // into a swarmkit host format:
// IP_address canonical_hostname [aliases...] //
// IP_address canonical_hostname [aliases...]
//
// This assumes input value (<host>:<ip>) has already been validated // This assumes input value (<host>:<ip>) has already been validated
func convertExtraHostsToSwarmHosts(extraHosts []string) []string { func convertExtraHostsToSwarmHosts(extraHosts []string) []string {
hosts := []string{} hosts := []string{}

View File

@ -75,7 +75,8 @@ func stateToProgress(state swarm.TaskState, rollback bool) int64 {
} }
// ServiceProgress outputs progress information for convergence of a service. // ServiceProgress outputs progress information for convergence of a service.
// nolint: gocyclo //
//nolint:gocyclo
func ServiceProgress(ctx context.Context, client client.APIClient, serviceID string, progressWriter io.WriteCloser) error { func ServiceProgress(ctx context.Context, client client.APIClient, serviceID string, progressWriter io.WriteCloser) error {
defer progressWriter.Close() defer progressWriter.Close()

View File

@ -3,7 +3,7 @@ package service
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"strings" "strings"
"testing" "testing"
@ -49,7 +49,7 @@ func TestRollback(t *testing.T) {
cmd := newRollbackCommand(cli) cmd := newRollbackCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.Flags().Set("quiet", "true") cmd.Flags().Set("quiet", "true")
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())
assert.Check(t, is.Equal(strings.TrimSpace(cli.ErrBuffer().String()), tc.expectedDockerCliErr)) assert.Check(t, is.Equal(strings.TrimSpace(cli.ErrBuffer().String()), tc.expectedDockerCliErr))
} }
@ -98,7 +98,7 @@ func TestRollbackWithErrors(t *testing.T) {
})) }))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.Flags().Set("quiet", "true") cmd.Flags().Set("quiet", "true")
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }

Some files were not shown because too many files have changed in this diff Show More