From 0a3d9c3e1486145d6fc7774f19c62c52b8f0658b Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 13:03:17 +0100 Subject: [PATCH 01/41] cli/command/checkpoint: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 8dc53344e0b85ac56d7ae03c69de6978e4bf7649) Signed-off-by: Cory Snider --- cli/command/checkpoint/create_test.go | 4 ++-- cli/command/checkpoint/list_test.go | 4 ++-- cli/command/checkpoint/remove_test.go | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cli/command/checkpoint/create_test.go b/cli/command/checkpoint/create_test.go index cdd15467d8a1..ee2485a6275d 100644 --- a/cli/command/checkpoint/create_test.go +++ b/cli/command/checkpoint/create_test.go @@ -1,7 +1,7 @@ package checkpoint import ( - "io/ioutil" + "io" "strings" "testing" @@ -41,7 +41,7 @@ func TestCheckpointCreateErrors(t *testing.T) { }) cmd := newCreateCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/checkpoint/list_test.go b/cli/command/checkpoint/list_test.go index b7947e9eee3b..b3f602e5deb5 100644 --- a/cli/command/checkpoint/list_test.go +++ b/cli/command/checkpoint/list_test.go @@ -1,7 +1,7 @@ package checkpoint import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -41,7 +41,7 @@ func TestCheckpointListErrors(t *testing.T) { }) cmd := newListCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/checkpoint/remove_test.go b/cli/command/checkpoint/remove_test.go index 1f340a8c601b..309584faa9b2 100644 --- a/cli/command/checkpoint/remove_test.go +++ b/cli/command/checkpoint/remove_test.go @@ -1,7 +1,7 @@ package checkpoint import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -40,7 +40,7 @@ func TestCheckpointRemoveErrors(t *testing.T) { }) cmd := newRemoveCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } From 54b7933016d329f36ccefd3c5e0ba6f48f0736b1 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 13:04:43 +0100 Subject: [PATCH 02/41] cli/command/config: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit bc1790c5c2fcb2c303c206ffa09888db95d408ac) Signed-off-by: Cory Snider --- cli/command/config/create.go | 3 +-- cli/command/config/create_test.go | 7 ++++--- cli/command/config/inspect_test.go | 4 ++-- cli/command/config/ls_test.go | 4 ++-- cli/command/config/remove_test.go | 6 +++--- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/cli/command/config/create.go b/cli/command/config/create.go index 863c41c1b7bc..04df13e2f6af 100644 --- a/cli/command/config/create.go +++ b/cli/command/config/create.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" @@ -61,7 +60,7 @@ func RunConfigCreate(dockerCli command.Cli, options CreateOptions) error { defer file.Close() } - configData, err := ioutil.ReadAll(in) + configData, err := io.ReadAll(in) if err != nil { return errors.Errorf("Error reading content from %q: %v", options.File, err) } diff --git a/cli/command/config/create_test.go b/cli/command/config/create_test.go index e132651bb851..e65d488ce65f 100644 --- a/cli/command/config/create_test.go +++ b/cli/command/config/create_test.go @@ -1,7 +1,8 @@ package config import ( - "io/ioutil" + "io" + "os" "path/filepath" "reflect" "strings" @@ -46,7 +47,7 @@ func TestConfigCreateErrors(t *testing.T) { }), ) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -82,7 +83,7 @@ func TestConfigCreateWithLabels(t *testing.T) { } name := "foo" - data, err := ioutil.ReadFile(filepath.Join("testdata", configDataFile)) + data, err := os.ReadFile(filepath.Join("testdata", configDataFile)) assert.NilError(t, err) expected := swarm.ConfigSpec{ diff --git a/cli/command/config/inspect_test.go b/cli/command/config/inspect_test.go index eeb6391f38bc..523eba2acdab 100644 --- a/cli/command/config/inspect_test.go +++ b/cli/command/config/inspect_test.go @@ -2,7 +2,7 @@ package config import ( "fmt" - "io/ioutil" + "io" "testing" "time" @@ -59,7 +59,7 @@ func TestConfigInspectErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/config/ls_test.go b/cli/command/config/ls_test.go index fcc5a6285164..116c41bf5c76 100644 --- a/cli/command/config/ls_test.go +++ b/cli/command/config/ls_test.go @@ -1,7 +1,7 @@ package config import ( - "io/ioutil" + "io" "testing" "time" @@ -40,7 +40,7 @@ func TestConfigListErrors(t *testing.T) { }), ) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/config/remove_test.go b/cli/command/config/remove_test.go index 19a92dc40733..bbdd0c4317e9 100644 --- a/cli/command/config/remove_test.go +++ b/cli/command/config/remove_test.go @@ -1,7 +1,7 @@ package config import ( - "io/ioutil" + "io" "strings" "testing" @@ -36,7 +36,7 @@ func TestConfigRemoveErrors(t *testing.T) { }), ) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -73,7 +73,7 @@ func TestConfigRemoveContinueAfterError(t *testing.T) { cmd := newConfigRemoveCommand(cli) cmd.SetArgs(names) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.Error(t, cmd.Execute(), "error removing config: foo") assert.Check(t, is.DeepEqual(names, removedConfigs)) } From b4d152f7adf77e77e242062d78051ef2eec4d46c Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 13:05:59 +0100 Subject: [PATCH 03/41] cli/command/container: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit e946bf08043c6d1aa6f67124909a5cdeaefec06a) Signed-off-by: Cory Snider --- cli/command/container/attach_test.go | 4 ++-- cli/command/container/cp_test.go | 5 ++--- cli/command/container/create_test.go | 11 +++++------ cli/command/container/exec_test.go | 4 ++-- cli/command/container/export_test.go | 9 ++++----- cli/command/container/list.go | 4 ++-- cli/command/container/list_test.go | 4 ++-- cli/command/container/logs_test.go | 3 +-- cli/command/container/opts.go | 4 ++-- cli/command/container/opts_test.go | 4 ++-- cli/command/container/rm_test.go | 4 ++-- cli/command/container/run_test.go | 4 ++-- 12 files changed, 28 insertions(+), 32 deletions(-) diff --git a/cli/command/container/attach_test.go b/cli/command/container/attach_test.go index 7790f351c9c7..d0b45a6827d5 100644 --- a/cli/command/container/attach_test.go +++ b/cli/command/container/attach_test.go @@ -2,7 +2,7 @@ package container import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/cli" @@ -71,7 +71,7 @@ func TestNewAttachCommandErrors(t *testing.T) { } for _, tc := range testCases { cmd := NewAttachCommand(test.NewFakeCli(&fakeClient{inspectFunc: tc.containerInspectFunc})) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } diff --git a/cli/command/container/cp_test.go b/cli/command/container/cp_test.go index f599049d05cc..65ab038e7899 100644 --- a/cli/command/container/cp_test.go +++ b/cli/command/container/cp_test.go @@ -2,7 +2,6 @@ package container import ( "io" - "io/ioutil" "os" "runtime" "strings" @@ -54,7 +53,7 @@ func TestRunCopyFromContainerToStdout(t *testing.T) { fakeClient := &fakeClient{ containerCopyFromFunc: func(container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) { 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: "-"} @@ -84,7 +83,7 @@ func TestRunCopyFromContainerToFilesystem(t *testing.T) { assert.Check(t, is.Equal("", cli.OutBuffer().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.Check(t, is.Equal("content\n", string(content))) } diff --git a/cli/command/container/create_test.go b/cli/command/container/create_test.go index 19c3de366a91..a17898c717e3 100644 --- a/cli/command/container/create_test.go +++ b/cli/command/container/create_test.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "runtime" "sort" @@ -67,7 +66,7 @@ func TestCIDFileCloseWithWrite(t *testing.T) { content := "id" assert.NilError(t, file.Write(content)) - actual, err := ioutil.ReadFile(path) + actual, err := os.ReadFile(path) assert.NilError(t, err) 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) { defer func() { pullCounter++ }() - return ioutil.NopCloser(strings.NewReader("")), nil + return io.NopCloser(strings.NewReader("")), nil }, infoFunc: func() (types.Info, error) { return types.Info{IndexServerAddress: "https://indexserver.example.com"}, nil @@ -194,7 +193,7 @@ func TestNewCreateCommandWithContentTrustErrors(t *testing.T) { }, test.EnableContentTrust) cli.SetNotaryClient(tc.notaryFunc) cmd := NewCreateCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() assert.ErrorContains(t, err, tc.expectedError) @@ -254,7 +253,7 @@ func TestNewCreateCommandWithWarnings(t *testing.T) { }, }) cmd := NewCreateCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() assert.NilError(t, err) @@ -303,7 +302,7 @@ func TestCreateContainerWithProxyConfig(t *testing.T) { }, }) cmd := NewCreateCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs([]string{"image:tag"}) err := cmd.Execute() assert.NilError(t, err) diff --git a/cli/command/container/exec_test.go b/cli/command/container/exec_test.go index 0a83a5f159b0..998a02a4c446 100644 --- a/cli/command/container/exec_test.go +++ b/cli/command/container/exec_test.go @@ -2,7 +2,7 @@ package container import ( "context" - "io/ioutil" + "io" "os" "testing" @@ -267,7 +267,7 @@ func TestNewExecCommandErrors(t *testing.T) { for _, tc := range testCases { cli := test.NewFakeCli(&fakeClient{inspectFunc: tc.containerInspectFunc}) cmd := NewExecCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } diff --git a/cli/command/container/export_test.go b/cli/command/container/export_test.go index 30e80730bf0d..891317fff3df 100644 --- a/cli/command/container/export_test.go +++ b/cli/command/container/export_test.go @@ -2,7 +2,6 @@ package container import ( "io" - "io/ioutil" "strings" "testing" @@ -17,11 +16,11 @@ func TestContainerExportOutputToFile(t *testing.T) { cli := test.NewFakeCli(&fakeClient{ 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.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs([]string{"-o", dir.Join("foo"), "container"}) assert.NilError(t, cmd.Execute()) @@ -35,11 +34,11 @@ func TestContainerExportOutputToFile(t *testing.T) { func TestContainerExportOutputToIrregularFile(t *testing.T) { cli := test.NewFakeCli(&fakeClient{ 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.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs([]string{"-o", "/dev/random", "container"}) err := cmd.Execute() diff --git a/cli/command/container/list.go b/cli/command/container/list.go index 0689cee9e3fc..b9146506c64d 100644 --- a/cli/command/container/list.go +++ b/cli/command/container/list.go @@ -2,7 +2,7 @@ package container import ( "context" - "io/ioutil" + "io" "github.com/docker/cli/cli" "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 // 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") } diff --git a/cli/command/container/list_test.go b/cli/command/container/list_test.go index 0c33d048b89a..3c5720d60e34 100644 --- a/cli/command/container/list_test.go +++ b/cli/command/container/list_test.go @@ -2,7 +2,7 @@ package container import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/cli/config/configfile" @@ -161,7 +161,7 @@ func TestContainerListErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/container/logs_test.go b/cli/command/container/logs_test.go index 23d8973a9150..711e7bf7b6ee 100644 --- a/cli/command/container/logs_test.go +++ b/cli/command/container/logs_test.go @@ -2,7 +2,6 @@ package container import ( "io" - "io/ioutil" "strings" "testing" @@ -15,7 +14,7 @@ import ( var logFn = func(expectedOut string) func(string, 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 } } diff --git a/cli/command/container/opts.go b/cli/command/container/opts.go index f53ae5960de4..c97799ce10ca 100644 --- a/cli/command/container/opts.go +++ b/cli/command/container/opts.go @@ -4,7 +4,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "os" "path" "reflect" "regexp" @@ -848,7 +848,7 @@ func parseSecurityOpts(securityOpts []string) ([]string, error) { } } if con[0] == "seccomp" && con[1] != "unconfined" { - f, err := ioutil.ReadFile(con[1]) + f, err := os.ReadFile(con[1]) if err != nil { return securityOpts, errors.Errorf("opening seccomp profile (%s) failed: %v", con[1], err) } diff --git a/cli/command/container/opts_test.go b/cli/command/container/opts_test.go index 3fe5a2d62594..56b0f07f9de0 100644 --- a/cli/command/container/opts_test.go +++ b/cli/command/container/opts_test.go @@ -2,7 +2,7 @@ package container import ( "fmt" - "io/ioutil" + "io" "os" "runtime" "strings" @@ -58,7 +58,7 @@ func parseRun(args []string) (*container.Config, *container.HostConfig, *network func setupRunFlags() (*pflag.FlagSet, *containerOptions) { flags := pflag.NewFlagSet("run", pflag.ContinueOnError) - flags.SetOutput(ioutil.Discard) + flags.SetOutput(io.Discard) flags.Usage = nil copts := addFlags(flags) return flags, copts diff --git a/cli/command/container/rm_test.go b/cli/command/container/rm_test.go index 674035e2ab05..7ab83dd2c907 100644 --- a/cli/command/container/rm_test.go +++ b/cli/command/container/rm_test.go @@ -3,7 +3,7 @@ package container import ( "context" "fmt" - "io/ioutil" + "io" "sort" "sync" "testing" @@ -44,7 +44,7 @@ func TestRemoveForce(t *testing.T) { Version: "1.36", }) cmd := NewRmCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() diff --git a/cli/command/container/run_test.go b/cli/command/container/run_test.go index 5821d66e66fd..1b81eb4dadb1 100644 --- a/cli/command/container/run_test.go +++ b/cli/command/container/run_test.go @@ -2,7 +2,7 @@ package container import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -68,7 +68,7 @@ func TestRunCommandWithContentTrustErrors(t *testing.T) { cli.SetNotaryClient(tc.notaryFunc) cmd := NewRunCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) err := cmd.Execute() assert.Assert(t, err != nil) assert.Assert(t, is.Contains(cli.ErrBuffer().String(), tc.expectedError)) From 8d0c8ef081b052a51b8fad2cc1c131e1115878d4 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 13:07:16 +0100 Subject: [PATCH 04/41] cli/command/context: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 76b47359cb305fd825143c0e292418f6d25810a0) Signed-off-by: Cory Snider --- cli/command/context/create_test.go | 31 +++++++------------- cli/command/context/export-import_test.go | 35 +++++++---------------- cli/command/context/inspect_test.go | 3 +- cli/command/context/list_test.go | 6 ++-- cli/command/context/remove_test.go | 21 ++++---------- cli/command/context/update_test.go | 15 ++++------ cli/command/context/use_test.go | 14 +++------ 7 files changed, 39 insertions(+), 86 deletions(-) diff --git a/cli/command/context/create_test.go b/cli/command/context/create_test.go index afdd8bef3f23..b38d31fac0fc 100644 --- a/cli/command/context/create_test.go +++ b/cli/command/context/create_test.go @@ -2,8 +2,6 @@ package context import ( "fmt" - "io/ioutil" - "os" "testing" "github.com/docker/cli/cli/command" @@ -16,9 +14,9 @@ import ( "gotest.tools/v3/env" ) -func makeFakeCli(t *testing.T, opts ...func(*test.FakeCli)) (*test.FakeCli, func()) { - dir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) +func makeFakeCli(t *testing.T, opts ...func(*test.FakeCli)) *test.FakeCli { + t.Helper() + dir := t.TempDir() storeConfig := store.NewConfig( func() interface{} { return &command.DockerContext{} }, 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 }, } - cleanup := func() { - os.RemoveAll(dir) - } result := test.NewFakeCli(nil, opts...) for _, o := range opts { o(result) } result.SetContextStore(store) - return result, cleanup + return result } 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) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) assert.NilError(t, cli.ContextStore().CreateOrUpdate(store.Metadata{Name: "existing-context"})) tests := []struct { options CreateOptions @@ -138,8 +132,7 @@ func assertContextCreateLogging(t *testing.T, cli *test.FakeCli, n string) { } func TestCreateOrchestratorSwarm(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) err := RunCreate(cli, &CreateOptions{ Name: "test", @@ -151,8 +144,7 @@ func TestCreateOrchestratorSwarm(t *testing.T) { } func TestCreateOrchestratorEmpty(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) err := RunCreate(cli, &CreateOptions{ Name: "test", @@ -192,8 +184,7 @@ func createTestContextWithKube(t *testing.T, cli command.Cli) { } func TestCreateOrchestratorAllKubernetesEndpointFromCurrent(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) createTestContextWithKube(t, cli) assertContextCreateLogging(t, cli, "test") validateTestKubeEndpoint(t, cli.ContextStore(), "test") @@ -228,8 +219,7 @@ func TestCreateFromContext(t *testing.T) { }, } - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) revert := env.Patch(t, "KUBECONFIG", "./testdata/test-kubeconfig") defer revert() cli.ResetOutputBuffers() @@ -319,8 +309,7 @@ func TestCreateFromCurrent(t *testing.T) { }, } - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) revert := env.Patch(t, "KUBECONFIG", "./testdata/test-kubeconfig") defer revert() cli.ResetOutputBuffers() diff --git a/cli/command/context/export-import_test.go b/cli/command/context/export-import_test.go index bf0cd8852755..74f82ed6017d 100644 --- a/cli/command/context/export-import_test.go +++ b/cli/command/context/export-import_test.go @@ -3,7 +3,7 @@ package context import ( "bytes" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "testing" @@ -13,12 +13,8 @@ import ( ) func TestExportImportWithFile(t *testing.T) { - contextDir, err := ioutil.TempDir("", t.Name()+"context") - assert.NilError(t, err) - defer os.RemoveAll(contextDir) - contextFile := filepath.Join(contextDir, "exported") - cli, cleanup := makeFakeCli(t) - defer cleanup() + contextFile := filepath.Join(t.TempDir(), "exported") + cli := makeFakeCli(t) createTestContextWithKube(t, cli) cli.ErrBuffer().Reset() assert.NilError(t, RunExport(cli, &ExportOptions{ @@ -43,8 +39,7 @@ func TestExportImportWithFile(t *testing.T) { } func TestExportImportPipe(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) createTestContextWithKube(t, cli) cli.ErrBuffer().Reset() cli.OutBuffer().Reset() @@ -53,7 +48,7 @@ func TestExportImportPipe(t *testing.T) { Dest: "-", })) 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.ErrBuffer().Reset() assert.NilError(t, RunImport(cli, "test2", "-")) @@ -71,12 +66,8 @@ func TestExportImportPipe(t *testing.T) { } func TestExportKubeconfig(t *testing.T) { - contextDir, err := ioutil.TempDir("", t.Name()+"context") - assert.NilError(t, err) - defer os.RemoveAll(contextDir) - contextFile := filepath.Join(contextDir, "exported") - cli, cleanup := makeFakeCli(t) - defer cleanup() + contextFile := filepath.Join(t.TempDir(), "exported") + cli := makeFakeCli(t) createTestContextWithKube(t, cli) cli.ErrBuffer().Reset() assert.NilError(t, RunExport(cli, &ExportOptions{ @@ -96,15 +87,11 @@ func TestExportKubeconfig(t *testing.T) { } func TestExportExistingFile(t *testing.T) { - contextDir, err := ioutil.TempDir("", t.Name()+"context") - assert.NilError(t, err) - defer os.RemoveAll(contextDir) - contextFile := filepath.Join(contextDir, "exported") - cli, cleanup := makeFakeCli(t) - defer cleanup() + contextFile := filepath.Join(t.TempDir(), "exported") + cli := makeFakeCli(t) createTestContextWithKube(t, cli) cli.ErrBuffer().Reset() - assert.NilError(t, ioutil.WriteFile(contextFile, []byte{}, 0644)) - err = RunExport(cli, &ExportOptions{ContextName: "test", Dest: contextFile}) + assert.NilError(t, os.WriteFile(contextFile, []byte{}, 0644)) + err := RunExport(cli, &ExportOptions{ContextName: "test", Dest: contextFile}) assert.Assert(t, os.IsExist(err)) } diff --git a/cli/command/context/inspect_test.go b/cli/command/context/inspect_test.go index 5e26c47fcbbb..2ad4b39dd5fa 100644 --- a/cli/command/context/inspect_test.go +++ b/cli/command/context/inspect_test.go @@ -9,8 +9,7 @@ import ( ) func TestInspect(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) createTestContextWithKubeAndSwarm(t, cli, "current", "all") cli.OutBuffer().Reset() assert.NilError(t, runInspect(cli, inspectOptions{ diff --git a/cli/command/context/list_test.go b/cli/command/context/list_test.go index b71a78b5a98c..a62313fe487f 100644 --- a/cli/command/context/list_test.go +++ b/cli/command/context/list_test.go @@ -24,8 +24,7 @@ func createTestContextWithKubeAndSwarm(t *testing.T, cli command.Cli, name strin } func TestList(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all") createTestContextWithKubeAndSwarm(t, cli, "unset", "unset") @@ -36,8 +35,7 @@ func TestList(t *testing.T) { } func TestListQuiet(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all") cli.SetCurrentContext("current") diff --git a/cli/command/context/remove_test.go b/cli/command/context/remove_test.go index bf67c2f5cc09..94d8c5ea67d8 100644 --- a/cli/command/context/remove_test.go +++ b/cli/command/context/remove_test.go @@ -1,8 +1,6 @@ package context import ( - "io/ioutil" - "os" "path/filepath" "testing" @@ -13,8 +11,7 @@ import ( ) func TestRemove(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all") assert.NilError(t, RunRemove(cli, RemoveOptions{}, []string{"other"})) @@ -25,8 +22,7 @@ func TestRemove(t *testing.T) { } func TestRemoveNotAContext(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all") err := RunRemove(cli, RemoveOptions{}, []string{"not-a-context"}) @@ -34,8 +30,7 @@ func TestRemoveNotAContext(t *testing.T) { } func TestRemoveCurrent(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all") cli.SetCurrentContext("current") @@ -44,16 +39,13 @@ func TestRemoveCurrent(t *testing.T) { } func TestRemoveCurrentForce(t *testing.T) { - configDir, err := ioutil.TempDir("", t.Name()+"config") - assert.NilError(t, err) - defer os.RemoveAll(configDir) + configDir := t.TempDir() configFilePath := filepath.Join(configDir, "config.json") testCfg := configfile.New(configFilePath) testCfg.CurrentContext = "current" assert.NilError(t, testCfg.Save()) - cli, cleanup := makeFakeCli(t, withCliConfig(testCfg)) - defer cleanup() + cli := makeFakeCli(t, withCliConfig(testCfg)) createTestContextWithKubeAndSwarm(t, cli, "current", "all") createTestContextWithKubeAndSwarm(t, cli, "other", "all") cli.SetCurrentContext("current") @@ -64,8 +56,7 @@ func TestRemoveCurrentForce(t *testing.T) { } func TestRemoveDefault(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) createTestContextWithKubeAndSwarm(t, cli, "other", "all") cli.SetCurrentContext("current") err := RunRemove(cli, RemoveOptions{}, []string{"default"}) diff --git a/cli/command/context/update_test.go b/cli/command/context/update_test.go index 34ceff66be75..44469103b467 100644 --- a/cli/command/context/update_test.go +++ b/cli/command/context/update_test.go @@ -11,8 +11,7 @@ import ( ) func TestUpdateDescriptionOnly(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) err := RunCreate(cli, &CreateOptions{ Name: "test", DefaultStackOrchestrator: "swarm", @@ -37,8 +36,7 @@ func TestUpdateDescriptionOnly(t *testing.T) { } func TestUpdateDockerOnly(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) createTestContextWithKubeAndSwarm(t, cli, "test", "swarm") assert.NilError(t, RunUpdate(cli, &UpdateOptions{ Name: "test", @@ -58,8 +56,7 @@ func TestUpdateDockerOnly(t *testing.T) { } func TestUpdateStackOrchestratorStrategy(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) err := RunCreate(cli, &CreateOptions{ Name: "test", DefaultStackOrchestrator: "swarm", @@ -74,8 +71,7 @@ func TestUpdateStackOrchestratorStrategy(t *testing.T) { } func TestUpdateStackOrchestratorStrategyRemoveKubeEndpoint(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) createTestContextWithKubeAndSwarm(t, cli, "test", "kubernetes") err := RunUpdate(cli, &UpdateOptions{ Name: "test", @@ -85,8 +81,7 @@ func TestUpdateStackOrchestratorStrategyRemoveKubeEndpoint(t *testing.T) { } func TestUpdateInvalidDockerHost(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) err := RunCreate(cli, &CreateOptions{ Name: "test", Docker: map[string]string{}, diff --git a/cli/command/context/use_test.go b/cli/command/context/use_test.go index 26936a4bccfc..a0563daa9837 100644 --- a/cli/command/context/use_test.go +++ b/cli/command/context/use_test.go @@ -1,8 +1,6 @@ package context import ( - "io/ioutil" - "os" "path/filepath" "testing" @@ -13,14 +11,11 @@ import ( ) func TestUse(t *testing.T) { - configDir, err := ioutil.TempDir("", t.Name()+"config") - assert.NilError(t, err) - defer os.RemoveAll(configDir) + configDir := t.TempDir() configFilePath := filepath.Join(configDir, "config.json") testCfg := configfile.New(configFilePath) - cli, cleanup := makeFakeCli(t, withCliConfig(testCfg)) - defer cleanup() - err = RunCreate(cli, &CreateOptions{ + cli := makeFakeCli(t, withCliConfig(testCfg)) + err := RunCreate(cli, &CreateOptions{ Name: "test", Docker: map[string]string{}, }) @@ -42,8 +37,7 @@ func TestUse(t *testing.T) { } func TestUseNoExist(t *testing.T) { - cli, cleanup := makeFakeCli(t) - defer cleanup() + cli := makeFakeCli(t) err := newUseCommand(cli).RunE(nil, []string{"test"}) assert.Check(t, store.IsErrContextDoesNotExist(err)) } From 5c97f5c918bb58a9c03d2bc607ec85d77b008064 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 13:10:34 +0100 Subject: [PATCH 05/41] cli/command/image: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit d14b5bff80bce8dacacb58d8241fcfc15474379f) Signed-off-by: Cory Snider --- cli/command/image/build.go | 5 +- cli/command/image/build/context.go | 9 ++- cli/command/image/build/context_test.go | 86 ++++++++++--------------- cli/command/image/build_buildkit.go | 9 ++- cli/command/image/build_session.go | 5 +- cli/command/image/build_test.go | 18 ++---- cli/command/image/client_test.go | 11 ++-- cli/command/image/history_test.go | 6 +- cli/command/image/import_test.go | 15 ++--- cli/command/image/inspect_test.go | 6 +- cli/command/image/list_test.go | 6 +- cli/command/image/load_test.go | 13 ++-- cli/command/image/prune_test.go | 6 +- cli/command/image/pull_test.go | 11 ++-- cli/command/image/push.go | 4 +- cli/command/image/push_test.go | 7 +- cli/command/image/remove_test.go | 6 +- cli/command/image/save_test.go | 13 ++-- cli/command/image/tag_test.go | 6 +- cli/command/image/trust.go | 3 +- cli/command/image/trust_test.go | 8 +-- 21 files changed, 108 insertions(+), 145 deletions(-) diff --git a/cli/command/image/build.go b/cli/command/image/build.go index 2d6144442e5e..6d614b0fafa5 100644 --- a/cli/command/image/build.go +++ b/cli/command/image/build.go @@ -9,7 +9,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "path/filepath" "regexp" @@ -340,7 +339,7 @@ func runBuild(dockerCli command.Cli, options buildOptions) error { if err != nil { 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 == "" { 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 } } diff --git a/cli/command/image/build/context.go b/cli/command/image/build/context.go index 2509f66de4a4..1b9f975d9b3f 100644 --- a/cli/command/image/build/context.go +++ b/cli/command/image/build/context.go @@ -6,7 +6,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "net/http" "os" "path/filepath" @@ -117,13 +116,13 @@ func DetectArchiveReader(input io.ReadCloser) (rc io.ReadCloser, isArchive bool, // temporary directory containing the Dockerfile. func WriteTempDockerfile(rc io.ReadCloser) (dockerfileDir string, err error) { // 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 { return "", errors.Errorf("unable to create temporary context directory: %v", err) } defer func() { if err != nil { - os.RemoveAll(dockerfileDir) + _ = os.RemoveAll(dockerfileDir) } }() @@ -240,7 +239,7 @@ func getWithStatusError(url string) (resp *http.Response, err error) { return resp, nil } 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() if err != nil { 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 // the relative path to the dockerfile in the context. func AddDockerfileToBuildContext(dockerfileCtx io.ReadCloser, buildCtx io.ReadCloser) (io.ReadCloser, string, error) { - file, err := ioutil.ReadAll(dockerfileCtx) + file, err := io.ReadAll(dockerfileCtx) dockerfileCtx.Close() if err != nil { return nil, "", err diff --git a/cli/command/image/build/context_test.go b/cli/command/image/build/context_test.go index f2169781e0ed..c55ffef34b5e 100644 --- a/cli/command/image/build/context_test.go +++ b/cli/command/image/build/context_test.go @@ -4,7 +4,6 @@ import ( "archive/tar" "bytes" "io" - "io/ioutil" "os" "path/filepath" "runtime" @@ -19,40 +18,34 @@ import ( const dockerfileContents = "FROM busybox" -var prepareEmpty = func(t *testing.T) (string, func()) { - return "", func() {} +func prepareEmpty(t *testing.T) string { + return "" } -var prepareNoFiles = func(t *testing.T) (string, func()) { - return createTestTempDir(t, "builder-context-test") +func prepareNoFiles(t *testing.T) string { + return createTestTempDir(t) } -var prepareOneFile = func(t *testing.T) (string, func()) { - contextDir, cleanup := createTestTempDir(t, "builder-context-test") +func prepareOneFile(t *testing.T) string { + contextDir := createTestTempDir(t) createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents) - return contextDir, cleanup + return contextDir } -func testValidateContextDirectory(t *testing.T, prepare func(t *testing.T) (string, func()), excludes []string) { - contextDir, cleanup := prepare(t) - defer cleanup() - +func testValidateContextDirectory(t *testing.T, prepare func(t *testing.T) string, excludes []string) { + contextDir := prepare(t) err := ValidateContextDirectory(contextDir, excludes) assert.NilError(t, err) } func TestGetContextFromLocalDirNoDockerfile(t *testing.T) { - contextDir, cleanup := createTestTempDir(t, "builder-context-test") - defer cleanup() - + contextDir := createTestTempDir(t) _, _, err := GetContextFromLocalDir(contextDir, "") assert.ErrorContains(t, err, "Dockerfile") } func TestGetContextFromLocalDirNotExistingDir(t *testing.T) { - contextDir, cleanup := createTestTempDir(t, "builder-context-test") - defer cleanup() - + contextDir := createTestTempDir(t) fakePath := filepath.Join(contextDir, "fake") _, _, err := GetContextFromLocalDir(fakePath, "") @@ -60,9 +53,7 @@ func TestGetContextFromLocalDirNotExistingDir(t *testing.T) { } func TestGetContextFromLocalDirNotExistingDockerfile(t *testing.T) { - contextDir, cleanup := createTestTempDir(t, "builder-context-test") - defer cleanup() - + contextDir := createTestTempDir(t) fakePath := filepath.Join(contextDir, "fake") _, _, err := GetContextFromLocalDir(contextDir, fakePath) @@ -70,13 +61,10 @@ func TestGetContextFromLocalDirNotExistingDockerfile(t *testing.T) { } func TestGetContextFromLocalDirWithNoDirectory(t *testing.T) { - contextDir, dirCleanup := createTestTempDir(t, "builder-context-test") - defer dirCleanup() - + contextDir := createTestTempDir(t) createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents) - chdirCleanup := chdir(t, contextDir) - defer chdirCleanup() + chdir(t, contextDir) absContextDir, relDockerfile, err := GetContextFromLocalDir(contextDir, "") assert.NilError(t, err) @@ -86,9 +74,7 @@ func TestGetContextFromLocalDirWithNoDirectory(t *testing.T) { } func TestGetContextFromLocalDirWithDockerfile(t *testing.T) { - contextDir, cleanup := createTestTempDir(t, "builder-context-test") - defer cleanup() - + contextDir := createTestTempDir(t) createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents) absContextDir, relDockerfile, err := GetContextFromLocalDir(contextDir, "") @@ -99,9 +85,7 @@ func TestGetContextFromLocalDirWithDockerfile(t *testing.T) { } func TestGetContextFromLocalDirLocalFile(t *testing.T) { - contextDir, cleanup := createTestTempDir(t, "builder-context-test") - defer cleanup() - + contextDir := createTestTempDir(t) createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents) testFilename := createTestTempFile(t, contextDir, "tmpTest", "test") @@ -121,11 +105,8 @@ func TestGetContextFromLocalDirLocalFile(t *testing.T) { } func TestGetContextFromLocalDirWithCustomDockerfile(t *testing.T) { - contextDir, cleanup := createTestTempDir(t, "builder-context-test") - defer cleanup() - - chdirCleanup := chdir(t, contextDir) - defer chdirCleanup() + contextDir := createTestTempDir(t) + chdir(t, contextDir) createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents) @@ -137,7 +118,7 @@ func TestGetContextFromLocalDirWithCustomDockerfile(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 { t.Fatalf("Error when executing GetContextFromReader: %s", err) @@ -173,9 +154,7 @@ func TestGetContextFromReaderString(t *testing.T) { } func TestGetContextFromReaderTar(t *testing.T) { - contextDir, cleanup := createTestTempDir(t, "builder-context-test") - defer cleanup() - + contextDir := createTestTempDir(t) createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents) tarStream, err := archive.Tar(contextDir, archive.Uncompressed) @@ -238,21 +217,24 @@ func TestValidateContextDirectoryWithOneFileExcludes(t *testing.T) { testValidateContextDirectory(t, prepareOneFile, []string{DefaultDockerfileName}) } -// createTestTempDir creates a temporary directory for testing. -// It returns the created path and a cleanup function which is meant to be used as deferred call. -// When an error occurs, it terminates the test. -//nolint: unparam -func createTestTempDir(t *testing.T, prefix string) (string, func()) { - path, err := ioutil.TempDir("", prefix) +// createTestTempDir creates a temporary directory for testing. It returns the +// created path. When an error occurs, it terminates the test. +func createTestTempDir(t *testing.T) string { + t.Helper() + path := t.TempDir() + + // Eval Symlinks is needed to account for macOS TMP using symlinks + path, err := filepath.EvalSymlinks(path) 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. // When an error occurs, it terminates the test func createTestTempFile(t *testing.T, dir, filename, contents string) string { + t.Helper() filePath := filepath.Join(dir, filename) - err := ioutil.WriteFile(filePath, []byte(contents), 0777) + err := os.WriteFile(filePath, []byte(contents), 0777) assert.NilError(t, err) 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. // This function is meant to be executed as a deferred call. // 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() assert.NilError(t, err) 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) { diff --git a/cli/command/image/build_buildkit.go b/cli/command/image/build_buildkit.go index b40d53cdbd21..5c83d7f9f6e3 100644 --- a/cli/command/image/build_buildkit.go +++ b/cli/command/image/build_buildkit.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "os" "path/filepath" @@ -43,7 +42,7 @@ const uploadRequestRemote = "upload-request" 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 { ctx := appcontext.Context() @@ -92,7 +91,7 @@ func runBuildBuildKit(dockerCli command.Cli, options buildOptions) error { dockerfileReader = rc remote = clientSessionRemote // TODO: make fssync handle empty contextdir - contextDir, _ = ioutil.TempDir("", "empty-dir") + contextDir, _ = os.MkdirTemp("", "empty-dir") defer os.RemoveAll(contextDir) } case isLocalDir(options.context): @@ -249,7 +248,7 @@ func runBuildBuildKit(dockerCli command.Cli, options buildOptions) error { 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) { response, err := dockerCli.Client().ImageBuild(context.Background(), nil, buildOptions) 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) } 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") } } diff --git a/cli/command/image/build_session.go b/cli/command/image/build_session.go index 0f15f51fb456..c513f19d2504 100644 --- a/cli/command/image/build_session.go +++ b/cli/command/image/build_session.go @@ -6,7 +6,6 @@ import ( "crypto/sha256" "encoding/hex" "fmt" - "io/ioutil" "os" "path/filepath" @@ -54,13 +53,13 @@ func tryNodeIdentifier() string { if _, err := rand.Read(b); err != nil { 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 } } } - dt, err := ioutil.ReadFile(sessionFile) + dt, err := os.ReadFile(sessionFile) if err == nil { return string(dt) } diff --git a/cli/command/image/build_test.go b/cli/command/image/build_test.go index 4317a74941fa..d05e4e1c6c50 100644 --- a/cli/command/image/build_test.go +++ b/cli/command/image/build_test.go @@ -7,7 +7,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -41,7 +40,7 @@ func TestRunBuildDockerfileFromStdinWithCompress(t *testing.T) { FROM alpine:3.6 COPY foo / `) - cli.SetIn(streams.NewIn(ioutil.NopCloser(dockerfile))) + cli.SetIn(streams.NewIn(io.NopCloser(dockerfile))) dir := fs.NewDir(t, t.Name(), fs.WithFile("foo", "some content")) @@ -130,7 +129,7 @@ func TestRunBuildFromGitHubSpecialCase(t *testing.T) { cmd := NewBuildCommand(test.NewFakeCli(&fakeClient{})) // Clone a small repo that exists so git doesn't prompt for credentials cmd.SetArgs([]string{"github.com/docker/for-win"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) err := cmd.Execute() assert.ErrorContains(t, err, "unable to prepare context") assert.ErrorContains(t, err, "docker-build-git") @@ -141,20 +140,17 @@ func TestRunBuildFromGitHubSpecialCase(t *testing.T) { // case. func TestRunBuildFromLocalGitHubDir(t *testing.T) { 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") - err = os.MkdirAll(buildDir, 0777) + buildDir := filepath.Join(t.TempDir(), "github.com", "docker", "no-such-repository") + err := os.MkdirAll(buildDir, 0777) 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) client := test.NewFakeCli(&fakeClient{}) cmd := NewBuildCommand(client) cmd.SetArgs([]string{buildDir}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) err = cmd.Execute() 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.options = options 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 { diff --git a/cli/command/image/client_test.go b/cli/command/image/client_test.go index 50e46f4ec126..a1b8cb08a287 100644 --- a/cli/command/image/client_test.go +++ b/cli/command/image/client_test.go @@ -3,7 +3,6 @@ package image import ( "context" "io" - "io/ioutil" "strings" "time" @@ -41,7 +40,7 @@ func (cli *fakeClient) ImageSave(_ context.Context, images []string) (io.ReadClo if cli.imageSaveFunc != nil { return cli.imageSaveFunc(images) } - return ioutil.NopCloser(strings.NewReader("")), nil + return io.NopCloser(strings.NewReader("")), nil } 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 { 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) { @@ -70,7 +69,7 @@ func (cli *fakeClient) ImagePull(_ context.Context, ref string, options types.Im if cli.imagePullFunc != nil { 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) { @@ -106,7 +105,7 @@ func (cli *fakeClient) ImageImport(_ context.Context, source types.ImageImportSo if cli.imageImportFunc != nil { 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) { @@ -120,5 +119,5 @@ func (cli *fakeClient) ImageBuild(ctx context.Context, context io.Reader, option if cli.imageBuildFunc != nil { return cli.imageBuildFunc(ctx, context, options) } - return types.ImageBuildResponse{Body: ioutil.NopCloser(strings.NewReader(""))}, nil + return types.ImageBuildResponse{Body: io.NopCloser(strings.NewReader(""))}, nil } diff --git a/cli/command/image/history_test.go b/cli/command/image/history_test.go index 7916f895e664..6641b74772c7 100644 --- a/cli/command/image/history_test.go +++ b/cli/command/image/history_test.go @@ -2,7 +2,7 @@ package image import ( "fmt" - "io/ioutil" + "io" "testing" "time" @@ -37,7 +37,7 @@ func TestNewHistoryCommandErrors(t *testing.T) { } for _, tc := range testCases { cmd := NewHistoryCommand(test.NewFakeCli(&fakeClient{imageHistoryFunc: tc.imageHistoryFunc})) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } @@ -95,7 +95,7 @@ func TestNewHistoryCommandSuccess(t *testing.T) { for _, tc := range testCases { cli := test.NewFakeCli(&fakeClient{imageHistoryFunc: tc.imageHistoryFunc}) cmd := NewHistoryCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() assert.NilError(t, err) diff --git a/cli/command/image/import_test.go b/cli/command/image/import_test.go index f2664f1275b9..4196f4fbbe56 100644 --- a/cli/command/image/import_test.go +++ b/cli/command/image/import_test.go @@ -2,7 +2,6 @@ package image import ( "io" - "io/ioutil" "strings" "testing" @@ -36,7 +35,7 @@ func TestNewImportCommandErrors(t *testing.T) { } for _, tc := range testCases { cmd := NewImportCommand(test.NewFakeCli(&fakeClient{imageImportFunc: tc.imageImportFunc})) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } @@ -44,7 +43,7 @@ func TestNewImportCommandErrors(t *testing.T) { func TestNewImportCommandInvalidFile(t *testing.T) { cmd := NewImportCommand(test.NewFakeCli(&fakeClient{})) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs([]string{"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"}, imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { 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", "-"}, imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { 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", "-"}, imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { 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", "-"}, imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { 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 { cmd := NewImportCommand(test.NewFakeCli(&fakeClient{imageImportFunc: tc.imageImportFunc})) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.NilError(t, cmd.Execute()) } diff --git a/cli/command/image/inspect_test.go b/cli/command/image/inspect_test.go index fac74c7e0317..730ec9efd08b 100644 --- a/cli/command/image/inspect_test.go +++ b/cli/command/image/inspect_test.go @@ -2,7 +2,7 @@ package image import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -26,7 +26,7 @@ func TestNewInspectCommandErrors(t *testing.T) { } for _, tc := range testCases { cmd := newInspectCommand(test.NewFakeCli(&fakeClient{})) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } @@ -78,7 +78,7 @@ func TestNewInspectCommandSuccess(t *testing.T) { imageInspectInvocationCount = 0 cli := test.NewFakeCli(&fakeClient{imageInspectFunc: tc.imageInspectFunc}) cmd := newInspectCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() assert.NilError(t, err) diff --git a/cli/command/image/list_test.go b/cli/command/image/list_test.go index 4ada77552723..67d87a2d3571 100644 --- a/cli/command/image/list_test.go +++ b/cli/command/image/list_test.go @@ -2,7 +2,7 @@ package image import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/cli/config/configfile" @@ -36,7 +36,7 @@ func TestNewImagesCommandErrors(t *testing.T) { } for _, tc := range testCases { cmd := NewImagesCommand(test.NewFakeCli(&fakeClient{imageListFunc: tc.imageListFunc})) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } @@ -82,7 +82,7 @@ func TestNewImagesCommandSuccess(t *testing.T) { cli := test.NewFakeCli(&fakeClient{imageListFunc: tc.imageListFunc}) cli.SetConfigFile(&configfile.ConfigFile{ImagesFormat: tc.imageFormat}) cmd := NewImagesCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() assert.NilError(t, err) diff --git a/cli/command/image/load_test.go b/cli/command/image/load_test.go index d1afb461399d..8b648b2ec8ee 100644 --- a/cli/command/image/load_test.go +++ b/cli/command/image/load_test.go @@ -3,7 +3,6 @@ package image import ( "fmt" "io" - "io/ioutil" "strings" "testing" @@ -44,7 +43,7 @@ func TestNewLoadCommandErrors(t *testing.T) { cli := test.NewFakeCli(&fakeClient{imageLoadFunc: tc.imageLoadFunc}) cli.In().SetIsTerminal(tc.isTerminalIn) cmd := NewLoadCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } @@ -53,7 +52,7 @@ func TestNewLoadCommandErrors(t *testing.T) { func TestNewLoadCommandInvalidInput(t *testing.T) { expectedError := "open *" cmd := NewLoadCommand(test.NewFakeCli(&fakeClient{})) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs([]string{"--input", "*"}) err := cmd.Execute() assert.ErrorContains(t, err, expectedError) @@ -68,7 +67,7 @@ func TestNewLoadCommandSuccess(t *testing.T) { { name: "simple", 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) { json := "{\"ID\": \"1\"}" return types.ImageLoadResponse{ - Body: ioutil.NopCloser(strings.NewReader(json)), + Body: io.NopCloser(strings.NewReader(json)), JSON: true, }, nil }, @@ -85,14 +84,14 @@ func TestNewLoadCommandSuccess(t *testing.T) { name: "input-file", args: []string{"--input", "testdata/load-command-success.input.txt"}, 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 { cli := test.NewFakeCli(&fakeClient{imageLoadFunc: tc.imageLoadFunc}) cmd := NewLoadCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() assert.NilError(t, err) diff --git a/cli/command/image/prune_test.go b/cli/command/image/prune_test.go index cbfb1b5bab57..8f501ac317d1 100644 --- a/cli/command/image/prune_test.go +++ b/cli/command/image/prune_test.go @@ -2,7 +2,7 @@ package image import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -39,7 +39,7 @@ func TestNewPruneCommandErrors(t *testing.T) { cmd := NewPruneCommand(test.NewFakeCli(&fakeClient{ imagesPruneFunc: tc.imagesPruneFunc, })) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } @@ -93,7 +93,7 @@ func TestNewPruneCommandSuccess(t *testing.T) { for _, tc := range testCases { cli := test.NewFakeCli(&fakeClient{imagesPruneFunc: tc.imagesPruneFunc}) cmd := NewPruneCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() assert.NilError(t, err) diff --git a/cli/command/image/pull_test.go b/cli/command/image/pull_test.go index b9d49701b6ec..3e6c55a5b45b 100644 --- a/cli/command/image/pull_test.go +++ b/cli/command/image/pull_test.go @@ -3,7 +3,6 @@ package image import ( "fmt" "io" - "io/ioutil" "strings" "testing" @@ -40,7 +39,7 @@ func TestNewPullCommandErrors(t *testing.T) { for _, tc := range testCases { cli := test.NewFakeCli(&fakeClient{}) cmd := NewPullCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } @@ -72,11 +71,11 @@ func TestNewPullCommandSuccess(t *testing.T) { cli := test.NewFakeCli(&fakeClient{ imagePullFunc: func(ref string, options types.ImagePullOptions) (io.ReadCloser, error) { 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.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() assert.NilError(t, err) @@ -113,12 +112,12 @@ func TestNewPullCommandWithContentTrustErrors(t *testing.T) { for _, tc := range testCases { cli := test.NewFakeCli(&fakeClient{ 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) cli.SetNotaryClient(tc.notaryFunc) cmd := NewPullCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() assert.ErrorContains(t, err, tc.expectedError) diff --git a/cli/command/image/push.go b/cli/command/image/push.go index 62cad07f1160..45d560cabf64 100644 --- a/cli/command/image/push.go +++ b/cli/command/image/push.go @@ -3,7 +3,7 @@ package image import ( "context" "fmt" - "io/ioutil" + "io" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" @@ -93,7 +93,7 @@ func RunPush(dockerCli command.Cli, opts pushOptions) error { } if opts.quiet { - err = jsonmessage.DisplayJSONMessagesToStream(responseBody, streams.NewOut(ioutil.Discard), nil) + err = jsonmessage.DisplayJSONMessagesToStream(responseBody, streams.NewOut(io.Discard), nil) if err == nil { fmt.Fprintln(dockerCli.Out(), ref.String()) } diff --git a/cli/command/image/push_test.go b/cli/command/image/push_test.go index 963636980bf2..30acd9b37355 100644 --- a/cli/command/image/push_test.go +++ b/cli/command/image/push_test.go @@ -2,7 +2,6 @@ package image import ( "io" - "io/ioutil" "strings" "testing" @@ -34,14 +33,14 @@ func TestNewPushCommandErrors(t *testing.T) { args: []string{"image:repo"}, expectedError: "Failed to push", 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 { cli := test.NewFakeCli(&fakeClient{imagePushFunc: tc.imagePushFunc}) cmd := NewPushCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } @@ -69,7 +68,7 @@ func TestNewPushCommandSuccess(t *testing.T) { t.Run(tc.name, func(t *testing.T) { cli := test.NewFakeCli(&fakeClient{ 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) diff --git a/cli/command/image/remove_test.go b/cli/command/image/remove_test.go index 0dc1944477a0..55de3eb6a62e 100644 --- a/cli/command/image/remove_test.go +++ b/cli/command/image/remove_test.go @@ -2,7 +2,7 @@ package image import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -68,7 +68,7 @@ func TestNewRemoveCommandErrors(t *testing.T) { cmd := NewRemoveCommand(test.NewFakeCli(&fakeClient{ imageRemoveFunc: tc.imageRemoveFunc, })) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) }) @@ -124,7 +124,7 @@ func TestNewRemoveCommandSuccess(t *testing.T) { t.Run(tc.name, func(t *testing.T) { cli := test.NewFakeCli(&fakeClient{imageRemoveFunc: tc.imageRemoveFunc}) cmd := NewRemoveCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.NilError(t, cmd.Execute()) assert.Check(t, is.Equal(tc.expectedStderr, cli.ErrBuffer().String())) diff --git a/cli/command/image/save_test.go b/cli/command/image/save_test.go index eb0fbc3bdd38..22434c736fd3 100644 --- a/cli/command/image/save_test.go +++ b/cli/command/image/save_test.go @@ -2,7 +2,6 @@ package image import ( "io" - "io/ioutil" "os" "strings" "testing" @@ -38,7 +37,7 @@ func TestNewSaveCommandErrors(t *testing.T) { isTerminal: false, expectedError: "error saving image", 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.Out().SetIsTerminal(tc.isTerminal) cmd := NewSaveCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(tc.args) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } @@ -75,7 +74,7 @@ func TestNewSaveCommandSuccess(t *testing.T) { imageSaveFunc: func(images []string) (io.ReadCloser, error) { assert.Assert(t, is.Len(images, 1)) assert.Check(t, is.Equal("arg1", images[0])) - return ioutil.NopCloser(strings.NewReader("")), nil + return io.NopCloser(strings.NewReader("")), nil }, deferredFunc: func() { os.Remove("save_tmp_file") @@ -88,17 +87,17 @@ func TestNewSaveCommandSuccess(t *testing.T) { assert.Assert(t, is.Len(images, 2)) assert.Check(t, is.Equal("arg1", images[0])) assert.Check(t, is.Equal("arg2", images[1])) - return ioutil.NopCloser(strings.NewReader("")), nil + return io.NopCloser(strings.NewReader("")), nil }, }, } for _, tc := range testCases { cmd := NewSaveCommand(test.NewFakeCli(&fakeClient{ 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) assert.NilError(t, cmd.Execute()) if tc.deferredFunc != nil { diff --git a/cli/command/image/tag_test.go b/cli/command/image/tag_test.go index b044ae22cb67..87e7aeb1e585 100644 --- a/cli/command/image/tag_test.go +++ b/cli/command/image/tag_test.go @@ -1,7 +1,7 @@ package image import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -19,7 +19,7 @@ func TestCliNewTagCommandErrors(t *testing.T) { for _, args := range testCases { cmd := NewTagCommand(test.NewFakeCli(&fakeClient{})) cmd.SetArgs(args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), expectedError) } } @@ -34,7 +34,7 @@ func TestCliNewTagCommand(t *testing.T) { }, })) cmd.SetArgs([]string{"image1", "image2"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.NilError(t, cmd.Execute()) value, _ := cmd.Flags().GetBool("interspersed") assert.Check(t, !value) diff --git a/cli/command/image/trust.go b/cli/command/image/trust.go index f54318cceb83..ac48ca364ed1 100644 --- a/cli/command/image/trust.go +++ b/cli/command/image/trust.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "sort" "github.com/docker/cli/cli/command" @@ -283,7 +282,7 @@ func imagePullPrivileged(ctx context.Context, cli command.Cli, imgRefAndAuth tru out := cli.Out() if opts.quiet { - out = streams.NewOut(ioutil.Discard) + out = streams.NewOut(io.Discard) } return jsonmessage.DisplayJSONMessagesToStream(responseBody, out, nil) } diff --git a/cli/command/image/trust_test.go b/cli/command/image/trust_test.go index b7279dc330b7..3fcf77c52c8c 100644 --- a/cli/command/image/trust_test.go +++ b/cli/command/image/trust_test.go @@ -1,8 +1,6 @@ package image import ( - "io/ioutil" - "os" "testing" "github.com/docker/cli/cli/trust" @@ -51,11 +49,7 @@ func TestNonOfficialTrustServer(t *testing.T) { } func TestAddTargetToAllSignableRolesError(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - - notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{}) + notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{}) assert.NilError(t, err) target := client.Target{} err = AddTargetToAllSignableRoles(notaryRepo, &target) From 5237d943a8ac3753d78af484a71c7b6ad37a662e Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 13:11:27 +0100 Subject: [PATCH 06/41] cli/command/manifest: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 43795ec8f7281c17dfe58f11b6188785eb4769df) Signed-off-by: Cory Snider --- cli/command/manifest/annotate_test.go | 10 +++++----- cli/command/manifest/create_test.go | 20 +++++++++---------- cli/command/manifest/inspect_test.go | 28 ++++++++------------------- cli/command/manifest/push_test.go | 8 ++++---- cli/command/manifest/rm_test.go | 13 ++++++------- 5 files changed, 32 insertions(+), 47 deletions(-) diff --git a/cli/command/manifest/annotate_test.go b/cli/command/manifest/annotate_test.go index ce6e9101affa..1c6a4ace3d08 100644 --- a/cli/command/manifest/annotate_test.go +++ b/cli/command/manifest/annotate_test.go @@ -1,9 +1,10 @@ package manifest import ( - "io/ioutil" + "io" "testing" + "github.com/docker/cli/cli/manifest/store" "github.com/docker/cli/internal/test" "gotest.tools/v3/assert" is "gotest.tools/v3/assert/cmp" @@ -33,14 +34,13 @@ func TestManifestAnnotateError(t *testing.T) { cli := test.NewFakeCli(nil) cmd := newAnnotateCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } func TestManifestAnnotate(t *testing.T) { - store, cleanup := newTempManifestStore(t) - defer cleanup() + store := store.NewStore(t.TempDir()) cli := test.NewFakeCli(nil) cli.SetManifestStore(store) @@ -51,7 +51,7 @@ func TestManifestAnnotate(t *testing.T) { cmd := newAnnotateCommand(cli) 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" assert.ErrorContains(t, cmd.Execute(), expectedError) diff --git a/cli/command/manifest/create_test.go b/cli/command/manifest/create_test.go index b6014f8bef25..e1092ee3d71e 100644 --- a/cli/command/manifest/create_test.go +++ b/cli/command/manifest/create_test.go @@ -2,9 +2,10 @@ package manifest import ( "context" - "io/ioutil" + "io" "testing" + "github.com/docker/cli/cli/manifest/store" manifesttypes "github.com/docker/cli/cli/manifest/types" "github.com/docker/cli/internal/test" "github.com/docker/distribution/reference" @@ -33,15 +34,14 @@ func TestManifestCreateErrors(t *testing.T) { cli := test.NewFakeCli(nil) cmd := newCreateListCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) 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 func TestManifestCreateAmend(t *testing.T) { - store, cleanup := newTempManifestStore(t) - defer cleanup() + store := store.NewStore(t.TempDir()) cli := test.NewFakeCli(nil) cli.SetManifestStore(store) @@ -58,7 +58,7 @@ func TestManifestCreateAmend(t *testing.T) { cmd := newCreateListCommand(cli) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.1"}) cmd.Flags().Set("amend", "true") - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) err = cmd.Execute() assert.NilError(t, err) @@ -75,8 +75,7 @@ func TestManifestCreateAmend(t *testing.T) { // attempt to overwrite a saved manifest and get refused func TestManifestCreateRefuseAmend(t *testing.T) { - store, cleanup := newTempManifestStore(t) - defer cleanup() + store := store.NewStore(t.TempDir()) cli := test.NewFakeCli(nil) cli.SetManifestStore(store) @@ -87,15 +86,14 @@ func TestManifestCreateRefuseAmend(t *testing.T) { cmd := newCreateListCommand(cli) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) err = cmd.Execute() assert.Error(t, err, "refusing to amend an existing manifest list with no --amend flag") } // attempt to make a manifest list without valid images func TestManifestCreateNoManifest(t *testing.T) { - store, cleanup := newTempManifestStore(t) - defer cleanup() + store := store.NewStore(t.TempDir()) cli := test.NewFakeCli(nil) cli.SetManifestStore(store) @@ -110,7 +108,7 @@ func TestManifestCreateNoManifest(t *testing.T) { cmd := newCreateListCommand(cli) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) err := cmd.Execute() assert.Error(t, err, "No such image: example.com/alpine:3.0") } diff --git a/cli/command/manifest/inspect_test.go b/cli/command/manifest/inspect_test.go index f58c00c86584..92bfd2e27a72 100644 --- a/cli/command/manifest/inspect_test.go +++ b/cli/command/manifest/inspect_test.go @@ -2,8 +2,7 @@ package manifest import ( "context" - "io/ioutil" - "os" + "io" "testing" "github.com/docker/cli/cli/manifest/store" @@ -21,13 +20,6 @@ import ( "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 { named, err := reference.ParseNamed("example.com/" + name) assert.NilError(t, err) @@ -70,22 +62,20 @@ func fullImageManifest(t *testing.T, ref reference.Named) types.ImageManifest { } func TestInspectCommandLocalManifestNotFound(t *testing.T) { - store, cleanup := newTempManifestStore(t) - defer cleanup() + store := store.NewStore(t.TempDir()) cli := test.NewFakeCli(nil) cli.SetManifestStore(store) cmd := newInspectCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"}) err := cmd.Execute() assert.Error(t, err, "No such manifest: example.com/alpine:3.0") } func TestInspectCommandNotFound(t *testing.T) { - store, cleanup := newTempManifestStore(t) - defer cleanup() + store := store.NewStore(t.TempDir()) cli := test.NewFakeCli(nil) cli.SetManifestStore(store) @@ -99,15 +89,14 @@ func TestInspectCommandNotFound(t *testing.T) { }) cmd := newInspectCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs([]string{"example.com/alpine:3.0"}) err := cmd.Execute() assert.Error(t, err, "No such manifest: example.com/alpine:3.0") } func TestInspectCommandLocalManifest(t *testing.T) { - store, cleanup := newTempManifestStore(t) - defer cleanup() + store := store.NewStore(t.TempDir()) cli := test.NewFakeCli(nil) cli.SetManifestStore(store) @@ -125,8 +114,7 @@ func TestInspectCommandLocalManifest(t *testing.T) { } func TestInspectcommandRemoteManifest(t *testing.T) { - store, cleanup := newTempManifestStore(t) - defer cleanup() + store := store.NewStore(t.TempDir()) cli := test.NewFakeCli(nil) cli.SetManifestStore(store) @@ -137,7 +125,7 @@ func TestInspectcommandRemoteManifest(t *testing.T) { }) cmd := newInspectCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs([]string{"example.com/alpine:3.0"}) assert.NilError(t, cmd.Execute()) actual := cli.OutBuffer() diff --git a/cli/command/manifest/push_test.go b/cli/command/manifest/push_test.go index 5146c85b5c75..a39fa66c5f74 100644 --- a/cli/command/manifest/push_test.go +++ b/cli/command/manifest/push_test.go @@ -2,9 +2,10 @@ package manifest import ( "context" - "io/ioutil" + "io" "testing" + "github.com/docker/cli/cli/manifest/store" manifesttypes "github.com/docker/cli/cli/manifest/types" "github.com/docker/cli/internal/test" "github.com/docker/distribution/reference" @@ -42,14 +43,13 @@ func TestManifestPushErrors(t *testing.T) { cli := test.NewFakeCli(nil) cmd := newPushListCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } func TestManifestPush(t *testing.T) { - store, sCleanup := newTempManifestStore(t) - defer sCleanup() + store := store.NewStore(t.TempDir()) registry := newFakeRegistryClient() diff --git a/cli/command/manifest/rm_test.go b/cli/command/manifest/rm_test.go index 1e1829e40ba0..d76f85a507f7 100644 --- a/cli/command/manifest/rm_test.go +++ b/cli/command/manifest/rm_test.go @@ -1,17 +1,17 @@ package manifest import ( - "io/ioutil" + "io" "testing" + "github.com/docker/cli/cli/manifest/store" "github.com/docker/cli/internal/test" "gotest.tools/v3/assert" ) // create two manifest lists and remove them both func TestRmSeveralManifests(t *testing.T) { - store, cleanup := newTempManifestStore(t) - defer cleanup() + store := store.NewStore(t.TempDir()) cli := test.NewFakeCli(nil) cli.SetManifestStore(store) @@ -31,7 +31,7 @@ func TestRmSeveralManifests(t *testing.T) { cmd := newRmManifestListCommand(cli) cmd.SetArgs([]string{"example.com/first:1", "example.com/second:2"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) err = cmd.Execute() assert.NilError(t, err) @@ -43,8 +43,7 @@ func TestRmSeveralManifests(t *testing.T) { // attempt to remove a manifest list which was never created func TestRmManifestNotCreated(t *testing.T) { - store, cleanup := newTempManifestStore(t) - defer cleanup() + store := store.NewStore(t.TempDir()) cli := test.NewFakeCli(nil) cli.SetManifestStore(store) @@ -56,7 +55,7 @@ func TestRmManifestNotCreated(t *testing.T) { cmd := newRmManifestListCommand(cli) cmd.SetArgs([]string{"example.com/first:1", "example.com/second:2"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) err = cmd.Execute() assert.Error(t, err, "No such manifest: example.com/first:1") From 4f3c38a7d91ec5aacd1782f73eb816b464b9b547 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 13:12:19 +0100 Subject: [PATCH 07/41] cli/command/context: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit f28c063e2f7320200a68eeea35e42e983f601978) Signed-off-by: Cory Snider --- cli/command/network/connect_test.go | 4 ++-- cli/command/network/create_test.go | 4 ++-- cli/command/network/disconnect_test.go | 4 ++-- cli/command/network/list_test.go | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cli/command/network/connect_test.go b/cli/command/network/connect_test.go index bc1432b625f4..c245a785433d 100644 --- a/cli/command/network/connect_test.go +++ b/cli/command/network/connect_test.go @@ -2,7 +2,7 @@ package network import ( "context" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -37,7 +37,7 @@ func TestNetworkConnectErrors(t *testing.T) { }), ) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } diff --git a/cli/command/network/create_test.go b/cli/command/network/create_test.go index 307b5a14875c..ec96c5874907 100644 --- a/cli/command/network/create_test.go +++ b/cli/command/network/create_test.go @@ -2,7 +2,7 @@ package network import ( "context" - "io/ioutil" + "io" "strings" "testing" @@ -137,7 +137,7 @@ func TestNetworkCreateErrors(t *testing.T) { for key, value := range tc.flags { assert.NilError(t, cmd.Flags().Set(key, value)) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } diff --git a/cli/command/network/disconnect_test.go b/cli/command/network/disconnect_test.go index 4413b95e51f2..e60ecd6ac089 100644 --- a/cli/command/network/disconnect_test.go +++ b/cli/command/network/disconnect_test.go @@ -2,7 +2,7 @@ package network import ( "context" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -35,7 +35,7 @@ func TestNetworkDisconnectErrors(t *testing.T) { }), ) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/network/list_test.go b/cli/command/network/list_test.go index 0cb3b0497526..99bd8508b9b7 100644 --- a/cli/command/network/list_test.go +++ b/cli/command/network/list_test.go @@ -2,7 +2,7 @@ package network import ( "context" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -35,7 +35,7 @@ func TestNetworkListErrors(t *testing.T) { networkListFunc: tc.networkListFunc, }), ) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } From 22300128caaee3b4524323dc4121bbc2fd18a725 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 13:20:55 +0100 Subject: [PATCH 08/41] cli/command/node: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 9bdeb09ae92e8bf40c7ca5ff00fb28484f5da1b2) Signed-off-by: Cory Snider --- cli/command/node/demote_test.go | 4 ++-- cli/command/node/inspect_test.go | 4 ++-- cli/command/node/list_test.go | 4 ++-- cli/command/node/promote_test.go | 4 ++-- cli/command/node/ps_test.go | 4 ++-- cli/command/node/remove_test.go | 4 ++-- cli/command/node/update_test.go | 4 ++-- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/cli/command/node/demote_test.go b/cli/command/node/demote_test.go index c4d6c267697d..8c226a9f9fe9 100644 --- a/cli/command/node/demote_test.go +++ b/cli/command/node/demote_test.go @@ -1,7 +1,7 @@ package node import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -43,7 +43,7 @@ func TestNodeDemoteErrors(t *testing.T) { nodeUpdateFunc: tc.nodeUpdateFunc, })) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/node/inspect_test.go b/cli/command/node/inspect_test.go index 975db14b7c0f..2c2e33bedf2b 100644 --- a/cli/command/node/inspect_test.go +++ b/cli/command/node/inspect_test.go @@ -2,7 +2,7 @@ package node import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -73,7 +73,7 @@ func TestNodeInspectErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/node/list_test.go b/cli/command/node/list_test.go index 309bd3798a08..6c176795fc77 100644 --- a/cli/command/node/list_test.go +++ b/cli/command/node/list_test.go @@ -1,7 +1,7 @@ package node import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/cli/config/configfile" @@ -47,7 +47,7 @@ func TestNodeListErrorOnAPIFailure(t *testing.T) { infoFunc: tc.infoFunc, }) cmd := newListCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.Error(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/node/promote_test.go b/cli/command/node/promote_test.go index 68299d298378..ebb2890ec2ad 100644 --- a/cli/command/node/promote_test.go +++ b/cli/command/node/promote_test.go @@ -1,7 +1,7 @@ package node import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -43,7 +43,7 @@ func TestNodePromoteErrors(t *testing.T) { nodeUpdateFunc: tc.nodeUpdateFunc, })) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/node/ps_test.go b/cli/command/node/ps_test.go index 2b6ab9a7a14b..870e8eb1871f 100644 --- a/cli/command/node/ps_test.go +++ b/cli/command/node/ps_test.go @@ -3,7 +3,7 @@ package node import ( "context" "fmt" - "io/ioutil" + "io" "testing" "time" @@ -59,7 +59,7 @@ func TestNodePsErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.Error(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/node/remove_test.go b/cli/command/node/remove_test.go index e4eaf9df71bb..db7bbcc7de49 100644 --- a/cli/command/node/remove_test.go +++ b/cli/command/node/remove_test.go @@ -1,7 +1,7 @@ package node import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -32,7 +32,7 @@ func TestNodeRemoveErrors(t *testing.T) { nodeRemoveFunc: tc.nodeRemoveFunc, })) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/node/update_test.go b/cli/command/node/update_test.go index 879855bfabfb..797f79f621da 100644 --- a/cli/command/node/update_test.go +++ b/cli/command/node/update_test.go @@ -1,7 +1,7 @@ package node import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -63,7 +63,7 @@ func TestNodeUpdateErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } From d06eafc516387fc2bd4a3bda6ada6c0455e05e7a Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:29:10 +0100 Subject: [PATCH 09/41] cli/command/plugin: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit f61aab59f75f250a1c9b1846217c0bc8fffc5cfa) Signed-off-by: Cory Snider --- cli/command/plugin/create_test.go | 11 +++++------ cli/command/plugin/disable_test.go | 4 ++-- cli/command/plugin/enable_test.go | 4 ++-- cli/command/plugin/inspect_test.go | 4 ++-- cli/command/plugin/install_test.go | 9 ++++----- cli/command/plugin/list_test.go | 4 ++-- cli/command/plugin/remove_test.go | 4 ++-- 7 files changed, 19 insertions(+), 21 deletions(-) diff --git a/cli/command/plugin/create_test.go b/cli/command/plugin/create_test.go index 923f931beb9b..37ce5e22c4bc 100644 --- a/cli/command/plugin/create_test.go +++ b/cli/command/plugin/create_test.go @@ -3,7 +3,6 @@ package plugin import ( "fmt" "io" - "io/ioutil" "runtime" "testing" @@ -41,7 +40,7 @@ func TestCreateErrors(t *testing.T) { cli := test.NewFakeCli(&fakeClient{}) cmd := newCreateCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -53,7 +52,7 @@ func TestCreateErrorOnFileAsContextDir(t *testing.T) { cli := test.NewFakeCli(&fakeClient{}) cmd := newCreateCommand(cli) 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") } @@ -64,7 +63,7 @@ func TestCreateErrorOnContextDirWithoutConfig(t *testing.T) { cli := test.NewFakeCli(&fakeClient{}) cmd := newCreateCommand(cli) cmd.SetArgs([]string{"plugin-foo", tmpDir.Path()}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) expectedErr := "config.json: no such file or directory" if runtime.GOOS == "windows" { @@ -82,7 +81,7 @@ func TestCreateErrorOnInvalidConfig(t *testing.T) { cli := test.NewFakeCli(&fakeClient{}) cmd := newCreateCommand(cli) cmd.SetArgs([]string{"plugin-foo", tmpDir.Path()}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), "invalid") } @@ -100,7 +99,7 @@ func TestCreateErrorFromDaemon(t *testing.T) { cmd := newCreateCommand(cli) cmd.SetArgs([]string{"plugin-foo", tmpDir.Path()}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), "Error creating plugin") } diff --git a/cli/command/plugin/disable_test.go b/cli/command/plugin/disable_test.go index bd1f812339a9..ca2e0d2cbbbe 100644 --- a/cli/command/plugin/disable_test.go +++ b/cli/command/plugin/disable_test.go @@ -2,7 +2,7 @@ package plugin import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -40,7 +40,7 @@ func TestPluginDisableErrors(t *testing.T) { pluginDisableFunc: tc.pluginDisableFunc, })) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/plugin/enable_test.go b/cli/command/plugin/enable_test.go index 5652543b706f..1d8840e77c16 100644 --- a/cli/command/plugin/enable_test.go +++ b/cli/command/plugin/enable_test.go @@ -2,7 +2,7 @@ package plugin import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -51,7 +51,7 @@ func TestPluginEnableErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/plugin/inspect_test.go b/cli/command/plugin/inspect_test.go index 66454b462fa4..4d3127660a68 100644 --- a/cli/command/plugin/inspect_test.go +++ b/cli/command/plugin/inspect_test.go @@ -2,7 +2,7 @@ package plugin import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -73,7 +73,7 @@ func TestInspectErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) }) } diff --git a/cli/command/plugin/install_test.go b/cli/command/plugin/install_test.go index 1e6486a0131e..f1a4ff975b63 100644 --- a/cli/command/plugin/install_test.go +++ b/cli/command/plugin/install_test.go @@ -3,7 +3,6 @@ package plugin import ( "fmt" "io" - "io/ioutil" "strings" "testing" @@ -58,7 +57,7 @@ func TestInstallErrors(t *testing.T) { cli := test.NewFakeCli(&fakeClient{pluginInstallFunc: tc.installFunc}) cmd := newInstallCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -100,7 +99,7 @@ func TestInstallContentTrustErrors(t *testing.T) { cli.SetNotaryClient(tc.notaryFunc) cmd := newInstallCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -117,7 +116,7 @@ func TestInstall(t *testing.T) { args: []string{"foo"}, expectedOutput: "Installed plugin foo\n", 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", installFunc: func(name string, options types.PluginInstallOptions) (io.ReadCloser, error) { assert.Check(t, options.Disabled) - return ioutil.NopCloser(strings.NewReader("")), nil + return io.NopCloser(strings.NewReader("")), nil }, }, } diff --git a/cli/command/plugin/list_test.go b/cli/command/plugin/list_test.go index b51565969b5f..ed30eb1c596f 100644 --- a/cli/command/plugin/list_test.go +++ b/cli/command/plugin/list_test.go @@ -2,7 +2,7 @@ package plugin import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -52,7 +52,7 @@ func TestListErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/plugin/remove_test.go b/cli/command/plugin/remove_test.go index f436c5accd3b..1b811f0c709b 100644 --- a/cli/command/plugin/remove_test.go +++ b/cli/command/plugin/remove_test.go @@ -2,7 +2,7 @@ package plugin import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -37,7 +37,7 @@ func TestRemoveErrors(t *testing.T) { }) cmd := newRemoveCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } From 0dfc5567bc0fdfe4e274fb55388b9aa96fdeb6df Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:29:48 +0100 Subject: [PATCH 10/41] cli/command/registry: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 3b3a0b898f19f69c73af0d36444bbd6a95ebfeea) Signed-off-by: Cory Snider --- cli/command/registry/login.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cli/command/registry/login.go b/cli/command/registry/login.go index 3820c414b124..b73c0792b243 100644 --- a/cli/command/registry/login.go +++ b/cli/command/registry/login.go @@ -3,7 +3,7 @@ package registry import ( "context" "fmt" - "io/ioutil" + "io" "strings" "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") } - contents, err := ioutil.ReadAll(dockerCli.In()) + contents, err := io.ReadAll(dockerCli.In()) if err != nil { return err } From 65893236e0efe15fc04eb33cbbed817e3f3ae978 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:30:27 +0100 Subject: [PATCH 11/41] cli/command/secret: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit c558df7cedb536c142c1ea8165b4ab6443c69048) Signed-off-by: Cory Snider --- cli/command/secret/create.go | 3 +-- cli/command/secret/create_test.go | 7 ++++--- cli/command/secret/inspect_test.go | 4 ++-- cli/command/secret/ls_test.go | 4 ++-- cli/command/secret/remove_test.go | 6 +++--- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/cli/command/secret/create.go b/cli/command/secret/create.go index 79456fdf30bd..b6ae84b46f45 100644 --- a/cli/command/secret/create.go +++ b/cli/command/secret/create.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" @@ -101,7 +100,7 @@ func readSecretData(in io.ReadCloser, file string) ([]byte, error) { } defer in.Close() } - data, err := ioutil.ReadAll(in) + data, err := io.ReadAll(in) if err != nil { return nil, err } diff --git a/cli/command/secret/create_test.go b/cli/command/secret/create_test.go index 5d12b84c71d4..5ca892877aa9 100644 --- a/cli/command/secret/create_test.go +++ b/cli/command/secret/create_test.go @@ -1,7 +1,8 @@ package secret import ( - "io/ioutil" + "io" + "os" "path/filepath" "reflect" "strings" @@ -44,14 +45,14 @@ func TestSecretCreateErrors(t *testing.T) { }), ) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } func TestSecretCreateWithName(t *testing.T) { name := "foo" - data, err := ioutil.ReadFile(filepath.Join("testdata", secretDataFile)) + data, err := os.ReadFile(filepath.Join("testdata", secretDataFile)) assert.NilError(t, err) expected := swarm.SecretSpec{ diff --git a/cli/command/secret/inspect_test.go b/cli/command/secret/inspect_test.go index 170adf4c862d..e05311f2af6b 100644 --- a/cli/command/secret/inspect_test.go +++ b/cli/command/secret/inspect_test.go @@ -2,7 +2,7 @@ package secret import ( "fmt" - "io/ioutil" + "io" "testing" "time" @@ -59,7 +59,7 @@ func TestSecretInspectErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/secret/ls_test.go b/cli/command/secret/ls_test.go index bfc1f3c4ff79..4c8b635fd11f 100644 --- a/cli/command/secret/ls_test.go +++ b/cli/command/secret/ls_test.go @@ -1,7 +1,7 @@ package secret import ( - "io/ioutil" + "io" "testing" "time" @@ -40,7 +40,7 @@ func TestSecretListErrors(t *testing.T) { }), ) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/secret/remove_test.go b/cli/command/secret/remove_test.go index a52e5d1f746e..c9f24dc22bc1 100644 --- a/cli/command/secret/remove_test.go +++ b/cli/command/secret/remove_test.go @@ -1,7 +1,7 @@ package secret import ( - "io/ioutil" + "io" "strings" "testing" @@ -36,7 +36,7 @@ func TestSecretRemoveErrors(t *testing.T) { }), ) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -72,7 +72,7 @@ func TestSecretRemoveContinueAfterError(t *testing.T) { }) cmd := newSecretRemoveCommand(cli) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs(names) assert.Error(t, cmd.Execute(), "error removing secret: foo") assert.Check(t, is.DeepEqual(names, removedSecrets)) From b061531f8c96592fc9d5589b96db6deda08b8ee0 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:30:56 +0100 Subject: [PATCH 12/41] cli/command/service: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit d1f26de646dda74035258d61d204b338ef91c6db) Signed-off-by: Cory Snider --- cli/command/service/helpers.go | 3 +-- cli/command/service/rollback_test.go | 6 +++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/cli/command/service/helpers.go b/cli/command/service/helpers.go index eb508e85fbfe..a104f19fd3e7 100644 --- a/cli/command/service/helpers.go +++ b/cli/command/service/helpers.go @@ -3,7 +3,6 @@ package service import ( "context" "io" - "io/ioutil" "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command/service/progress" @@ -21,7 +20,7 @@ func waitOnService(ctx context.Context, dockerCli command.Cli, serviceID string, }() if quiet { - go io.Copy(ioutil.Discard, pipeReader) + go io.Copy(io.Discard, pipeReader) return <-errChan } diff --git a/cli/command/service/rollback_test.go b/cli/command/service/rollback_test.go index a4da2b54fdf7..e589946b0699 100644 --- a/cli/command/service/rollback_test.go +++ b/cli/command/service/rollback_test.go @@ -3,7 +3,7 @@ package service import ( "context" "fmt" - "io/ioutil" + "io" "strings" "testing" @@ -49,7 +49,7 @@ func TestRollback(t *testing.T) { cmd := newRollbackCommand(cli) cmd.SetArgs(tc.args) cmd.Flags().Set("quiet", "true") - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.NilError(t, cmd.Execute()) 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.Flags().Set("quiet", "true") - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } From 7c6baba23bd8fb4172e6b601f86e6c72856df95e Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:31:31 +0100 Subject: [PATCH 13/41] cli/command/stack: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit d59330f40d0dd95dff6f6c64f12824089c01065d) Signed-off-by: Cory Snider --- cli/command/stack/deploy_test.go | 4 ++-- cli/command/stack/kubernetes/convert.go | 3 +-- cli/command/stack/kubernetes/convert_test.go | 13 +++++++------ cli/command/stack/kubernetes/list.go | 4 ++-- cli/command/stack/kubernetes/stack.go | 6 +++--- cli/command/stack/kubernetes/stackclient_test.go | 6 +++--- cli/command/stack/list_test.go | 4 ++-- cli/command/stack/loader/loader.go | 5 ++--- cli/command/stack/ps_test.go | 6 +++--- cli/command/stack/remove_test.go | 6 +++--- cli/command/stack/services_test.go | 6 +++--- 11 files changed, 31 insertions(+), 32 deletions(-) diff --git a/cli/command/stack/deploy_test.go b/cli/command/stack/deploy_test.go index cc27e12f6842..a8f88d51206f 100644 --- a/cli/command/stack/deploy_test.go +++ b/cli/command/stack/deploy_test.go @@ -1,7 +1,7 @@ package stack import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -11,7 +11,7 @@ import ( func TestDeployWithEmptyName(t *testing.T) { cmd := newDeployCommand(test.NewFakeCli(&fakeClient{}), nil) cmd.SetArgs([]string{"' '"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), `invalid stack name: "' '"`) } diff --git a/cli/command/stack/kubernetes/convert.go b/cli/command/stack/kubernetes/convert.go index 60c2c884472d..aa66e16b9bdc 100644 --- a/cli/command/stack/kubernetes/convert.go +++ b/cli/command/stack/kubernetes/convert.go @@ -2,7 +2,6 @@ package kubernetes import ( "io" - "io/ioutil" "regexp" "strconv" "strings" @@ -115,7 +114,7 @@ func stackFromV1beta1(in *v1beta1.Stack) (Stack, error) { if err != nil { return Stack{}, err } - spec, err := fromComposeConfig(ioutil.Discard, cfg, v1beta1Capabilities) + spec, err := fromComposeConfig(io.Discard, cfg, v1beta1Capabilities) if err != nil { return Stack{}, err } diff --git a/cli/command/stack/kubernetes/convert_test.go b/cli/command/stack/kubernetes/convert_test.go index aaab4eb8124d..868a919a4044 100644 --- a/cli/command/stack/kubernetes/convert_test.go +++ b/cli/command/stack/kubernetes/convert_test.go @@ -2,7 +2,8 @@ package kubernetes import ( "fmt" - "io/ioutil" + "io" + "os" "path/filepath" "testing" @@ -170,7 +171,7 @@ func TestConvertFromToV1alpha3(t *testing.T) { func loadTestStackWith(t *testing.T, with string) *composetypes.Config { t.Helper() filePath := fmt.Sprintf("testdata/compose-with-%s.yml", with) - data, err := ioutil.ReadFile(filePath) + data, err := os.ReadFile(filePath) assert.NilError(t, err) yamlData, err := loader.ParseYAML(data) assert.NilError(t, err) @@ -199,7 +200,7 @@ func TestHandlePullSecret(t *testing.T) { t.Run(c.version, func(t *testing.T) { conv, err := NewStackConverter(c.version) assert.NilError(t, err) - s, err := conv.FromCompose(ioutil.Discard, "test", testData) + s, err := conv.FromCompose(io.Discard, "test", testData) if c.err != "" { assert.Error(t, err, c.err) @@ -227,7 +228,7 @@ func TestHandlePullPolicy(t *testing.T) { t.Run(c.version, func(t *testing.T) { conv, err := NewStackConverter(c.version) assert.NilError(t, err) - s, err := conv.FromCompose(ioutil.Discard, "test", testData) + s, err := conv.FromCompose(io.Discard, "test", testData) if c.err != "" { assert.Error(t, err, c.err) @@ -299,7 +300,7 @@ func TestIgnoreExpose(t *testing.T) { for _, version := range []string{"v1beta1", "v1beta2"} { conv, err := NewStackConverter(version) assert.NilError(t, err) - s, err := conv.FromCompose(ioutil.Discard, "test", testData) + s, err := conv.FromCompose(io.Discard, "test", testData) assert.NilError(t, err) assert.Equal(t, len(s.Spec.Services[0].InternalPorts), 0) } @@ -309,7 +310,7 @@ func TestParseExpose(t *testing.T) { testData := loadTestStackWith(t, "expose") conv, err := NewStackConverter("v1alpha3") assert.NilError(t, err) - s, err := conv.FromCompose(ioutil.Discard, "test", testData) + s, err := conv.FromCompose(io.Discard, "test", testData) assert.NilError(t, err) expected := []v1alpha3.InternalPort{ { diff --git a/cli/command/stack/kubernetes/list.go b/cli/command/stack/kubernetes/list.go index facd401bb999..ea176019e0c0 100644 --- a/cli/command/stack/kubernetes/list.go +++ b/cli/command/stack/kubernetes/list.go @@ -3,7 +3,7 @@ package kubernetes import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" @@ -87,7 +87,7 @@ func getUserVisibleNamespaces(dockerCli command.Cli) ([]string, error) { return nil, err } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, errors.Wrapf(err, "received %d status and unable to read response", resp.StatusCode) } diff --git a/cli/command/stack/kubernetes/stack.go b/cli/command/stack/kubernetes/stack.go index e368d718de9e..8c304d65b5c0 100644 --- a/cli/command/stack/kubernetes/stack.go +++ b/cli/command/stack/kubernetes/stack.go @@ -1,7 +1,7 @@ package kubernetes import ( - "io/ioutil" + "os" "path/filepath" "sort" @@ -59,7 +59,7 @@ func (s *Stack) createFileBasedConfigMaps(configMaps corev1.ConfigMapInterface) } fileName := filepath.Base(config.File) - content, err := ioutil.ReadFile(config.File) + content, err := os.ReadFile(config.File) if err != nil { return resources, err } @@ -116,7 +116,7 @@ func (s *Stack) createFileBasedSecrets(secrets corev1.SecretInterface) ([]childR } fileName := filepath.Base(secret.File) - content, err := ioutil.ReadFile(secret.File) + content, err := os.ReadFile(secret.File) if err != nil { return resources, err } diff --git a/cli/command/stack/kubernetes/stackclient_test.go b/cli/command/stack/kubernetes/stackclient_test.go index 354d8c389775..18c27b576017 100644 --- a/cli/command/stack/kubernetes/stackclient_test.go +++ b/cli/command/stack/kubernetes/stackclient_test.go @@ -1,7 +1,7 @@ package kubernetes import ( - "io/ioutil" + "io" "testing" composetypes "github.com/docker/cli/cli/compose/types" @@ -10,7 +10,7 @@ import ( func TestFromCompose(t *testing.T) { stackClient := &stackV1Beta1{} - s, err := stackClient.FromCompose(ioutil.Discard, "foo", &composetypes.Config{ + s, err := stackClient.FromCompose(io.Discard, "foo", &composetypes.Config{ Version: "3.1", Filename: "banana", Services: []composetypes.ServiceConfig{ @@ -37,7 +37,7 @@ services: func TestFromComposeUnsupportedVersion(t *testing.T) { stackClient := &stackV1Beta1{} - _, err := stackClient.FromCompose(ioutil.Discard, "foo", &composetypes.Config{ + _, err := stackClient.FromCompose(io.Discard, "foo", &composetypes.Config{ Version: "3.6", Filename: "banana", Services: []composetypes.ServiceConfig{ diff --git a/cli/command/stack/list_test.go b/cli/command/stack/list_test.go index e9c653329af8..c2bcee8e1ff5 100644 --- a/cli/command/stack/list_test.go +++ b/cli/command/stack/list_test.go @@ -1,7 +1,7 @@ package stack import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/cli/command" @@ -54,7 +54,7 @@ func TestListErrors(t *testing.T) { serviceListFunc: tc.serviceListFunc, }), &orchestrator) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) for key, value := range tc.flags { cmd.Flags().Set(key, value) } diff --git a/cli/command/stack/loader/loader.go b/cli/command/stack/loader/loader.go index 0874d6bf6b84..a61efc7bd740 100644 --- a/cli/command/stack/loader/loader.go +++ b/cli/command/stack/loader/loader.go @@ -3,7 +3,6 @@ package loader import ( "fmt" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -133,9 +132,9 @@ func loadConfigFile(filename string, stdin io.Reader) (*composetypes.ConfigFile, var err error if filename == "-" { - bytes, err = ioutil.ReadAll(stdin) + bytes, err = io.ReadAll(stdin) } else { - bytes, err = ioutil.ReadFile(filename) + bytes, err = os.ReadFile(filename) } if err != nil { return nil, err diff --git a/cli/command/stack/ps_test.go b/cli/command/stack/ps_test.go index 58a651252b16..d93ebc19d9cf 100644 --- a/cli/command/stack/ps_test.go +++ b/cli/command/stack/ps_test.go @@ -1,7 +1,7 @@ package stack import ( - "io/ioutil" + "io" "testing" "time" @@ -45,7 +45,7 @@ func TestStackPsErrors(t *testing.T) { taskListFunc: tc.taskListFunc, }), &orchestrator) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -169,7 +169,7 @@ func TestStackPs(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) if tc.expectedErr != "" { assert.Error(t, cmd.Execute(), tc.expectedErr) diff --git a/cli/command/stack/remove_test.go b/cli/command/stack/remove_test.go index 0f10c55b2441..f533a94339b0 100644 --- a/cli/command/stack/remove_test.go +++ b/cli/command/stack/remove_test.go @@ -2,7 +2,7 @@ package stack import ( "errors" - "io/ioutil" + "io" "strings" "testing" @@ -44,7 +44,7 @@ func fakeClientForRemoveStackTest(version string) *fakeClient { func TestRemoveWithEmptyName(t *testing.T) { cmd := newRemoveCommand(test.NewFakeCli(&fakeClient{}), &orchestrator) cmd.SetArgs([]string{"good", "' '", "alsogood"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), `invalid stack name: "' '"`) } @@ -155,7 +155,7 @@ func TestRemoveContinueAfterError(t *testing.T) { }, } cmd := newRemoveCommand(test.NewFakeCli(cli), &orchestrator) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.SetArgs([]string{"foo", "bar"}) assert.Error(t, cmd.Execute(), "Failed to remove some resources from stack: foo") diff --git a/cli/command/stack/services_test.go b/cli/command/stack/services_test.go index 1962dd245f24..42fcb3c7c437 100644 --- a/cli/command/stack/services_test.go +++ b/cli/command/stack/services_test.go @@ -1,7 +1,7 @@ package stack import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/cli/config/configfile" @@ -79,7 +79,7 @@ func TestStackServicesErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) }) } @@ -88,7 +88,7 @@ func TestStackServicesErrors(t *testing.T) { func TestRunServicesWithEmptyName(t *testing.T) { cmd := newServicesCommand(test.NewFakeCli(&fakeClient{}), &orchestrator) cmd.SetArgs([]string{"' '"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), `invalid stack name: "' '"`) } From b5cd20f67a9f370843f5dfd86f9d109d44b1bd54 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:32:11 +0100 Subject: [PATCH 14/41] cli/command/swarm: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 78cb61c61c073592c45f30f4e827841be341935a) Signed-off-by: Cory Snider --- cli/command/swarm/ca.go | 3 +-- cli/command/swarm/ca_test.go | 11 +++++------ cli/command/swarm/init_test.go | 4 ++-- cli/command/swarm/join_test.go | 4 ++-- cli/command/swarm/join_token_test.go | 4 ++-- cli/command/swarm/leave_test.go | 4 ++-- cli/command/swarm/opts.go | 6 +++--- cli/command/swarm/unlock_key_test.go | 4 ++-- cli/command/swarm/unlock_test.go | 6 +++--- cli/command/swarm/update_test.go | 4 ++-- 10 files changed, 24 insertions(+), 26 deletions(-) diff --git a/cli/command/swarm/ca.go b/cli/command/swarm/ca.go index 961e7e89441b..1c01f68460b1 100644 --- a/cli/command/swarm/ca.go +++ b/cli/command/swarm/ca.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "strings" "github.com/docker/cli/cli" @@ -113,7 +112,7 @@ func attach(ctx context.Context, dockerCli command.Cli, opts caOptions) error { }() if opts.quiet { - go io.Copy(ioutil.Discard, pipeReader) + go io.Copy(io.Discard, pipeReader) return <-errChan } diff --git a/cli/command/swarm/ca_test.go b/cli/command/swarm/ca_test.go index 1f65647c5880..2758bfb12150 100644 --- a/cli/command/swarm/ca_test.go +++ b/cli/command/swarm/ca_test.go @@ -2,7 +2,7 @@ package swarm import ( "bytes" - "io/ioutil" + "io" "os" "testing" "time" @@ -65,7 +65,7 @@ type invalidCATestCases struct { } func writeFile(data string) (string, error) { - tmpfile, err := ioutil.TempFile("", "testfile") + tmpfile, err := os.CreateTemp("", "testfile") if err != nil { return "", err } @@ -73,15 +73,14 @@ func writeFile(data string) (string, error) { if err != nil { return "", err } - tmpfile.Close() - return tmpfile.Name(), nil + return tmpfile.Name(), tmpfile.Close() } func TestDisplayTrustRootInvalidFlags(t *testing.T) { // we need an actual PEMfile to test tmpfile, err := writeFile(cert) assert.NilError(t, err) - defer os.Remove(tmpfile) + t.Cleanup(func() { _ = os.Remove(tmpfile) }) errorTestCases := []invalidCATestCases{ { @@ -145,7 +144,7 @@ func TestDisplayTrustRootInvalidFlags(t *testing.T) { }, })) assert.Check(t, cmd.Flags().Parse(testCase.args)) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), testCase.errorMsg) } } diff --git a/cli/command/swarm/init_test.go b/cli/command/swarm/init_test.go index 261417726963..e2153040e998 100644 --- a/cli/command/swarm/init_test.go +++ b/cli/command/swarm/init_test.go @@ -2,7 +2,7 @@ package swarm import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -73,7 +73,7 @@ func TestSwarmInitErrorOnAPIFailure(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.Error(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/swarm/join_test.go b/cli/command/swarm/join_test.go index 7fba3bc4d70d..e8204f391335 100644 --- a/cli/command/swarm/join_test.go +++ b/cli/command/swarm/join_test.go @@ -1,7 +1,7 @@ package swarm import ( - "io/ioutil" + "io" "strings" "testing" @@ -54,7 +54,7 @@ func TestSwarmJoinErrors(t *testing.T) { infoFunc: tc.infoFunc, })) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/swarm/join_token_test.go b/cli/command/swarm/join_token_test.go index 3d79ae90ba76..082b54852a2e 100644 --- a/cli/command/swarm/join_token_test.go +++ b/cli/command/swarm/join_token_test.go @@ -2,7 +2,7 @@ package swarm import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -98,7 +98,7 @@ func TestSwarmJoinTokenErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/swarm/leave_test.go b/cli/command/swarm/leave_test.go index 969bdbbfb473..e1005828d067 100644 --- a/cli/command/swarm/leave_test.go +++ b/cli/command/swarm/leave_test.go @@ -1,7 +1,7 @@ package swarm import ( - "io/ioutil" + "io" "strings" "testing" @@ -37,7 +37,7 @@ func TestSwarmLeaveErrors(t *testing.T) { swarmLeaveFunc: tc.swarmLeaveFunc, })) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/swarm/opts.go b/cli/command/swarm/opts.go index ea66bf398769..4db2e303b18c 100644 --- a/cli/command/swarm/opts.go +++ b/cli/command/swarm/opts.go @@ -4,7 +4,7 @@ import ( "encoding/csv" "encoding/pem" "fmt" - "io/ioutil" + "os" "strings" "time" @@ -140,7 +140,7 @@ func (p *PEMFile) String() string { // Set parses a root rotation option func (p *PEMFile) Set(value string) error { - contents, err := ioutil.ReadFile(value) + contents, err := os.ReadFile(value) if err != nil { return err } @@ -195,7 +195,7 @@ func parseExternalCA(caSpec string) (*swarm.ExternalCA, error) { hasURL = true externalCA.URL = value case "cacert": - cacontents, err := ioutil.ReadFile(value) + cacontents, err := os.ReadFile(value) if err != nil { return nil, errors.Wrap(err, "unable to read CA cert for external CA") } diff --git a/cli/command/swarm/unlock_key_test.go b/cli/command/swarm/unlock_key_test.go index e51bd726ef76..24ca164aa6cb 100644 --- a/cli/command/swarm/unlock_key_test.go +++ b/cli/command/swarm/unlock_key_test.go @@ -2,7 +2,7 @@ package swarm import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -90,7 +90,7 @@ func TestSwarmUnlockKeyErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/swarm/unlock_test.go b/cli/command/swarm/unlock_test.go index 6d40613619d9..c7e463a32a42 100644 --- a/cli/command/swarm/unlock_test.go +++ b/cli/command/swarm/unlock_test.go @@ -1,7 +1,7 @@ package swarm import ( - "io/ioutil" + "io" "strings" "testing" @@ -70,7 +70,7 @@ func TestSwarmUnlockErrors(t *testing.T) { swarmUnlockFunc: tc.swarmUnlockFunc, })) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -92,7 +92,7 @@ func TestSwarmUnlock(t *testing.T) { return nil }, }) - dockerCli.SetIn(streams.NewIn(ioutil.NopCloser(strings.NewReader(input)))) + dockerCli.SetIn(streams.NewIn(io.NopCloser(strings.NewReader(input)))) cmd := newUnlockCommand(dockerCli) assert.NilError(t, cmd.Execute()) } diff --git a/cli/command/swarm/update_test.go b/cli/command/swarm/update_test.go index ea695f25883c..14605c033a6c 100644 --- a/cli/command/swarm/update_test.go +++ b/cli/command/swarm/update_test.go @@ -2,7 +2,7 @@ package swarm import ( "fmt" - "io/ioutil" + "io" "testing" "time" @@ -75,7 +75,7 @@ func TestSwarmUpdateErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } From 3d4a0c16127be8d3b3a4a5c2d9f55ca3ca2895e4 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:32:43 +0100 Subject: [PATCH 15/41] cli/command/system: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit e0299ff86296393f89594863b13ed9bb5797b36b) Signed-off-by: Cory Snider --- cli/command/system/events.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cli/command/system/events.go b/cli/command/system/events.go index 37de9722eac7..643cde070b30 100644 --- a/cli/command/system/events.go +++ b/cli/command/system/events.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "sort" "strings" "text/template" @@ -100,7 +99,7 @@ func makeTemplate(format string) (*template.Template, error) { } // we execute the template for an empty message, so as to validate // a bad template like "{{.badFieldString}}" - return tmpl, tmpl.Execute(ioutil.Discard, &eventtypes.Message{}) + return tmpl, tmpl.Execute(io.Discard, &eventtypes.Message{}) } // rfc3339NanoFixed is similar to time.RFC3339Nano, except it pads nanoseconds From 65e4b0e2b3873eb0106a05b9d271ea46d8efb3f4 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:33:57 +0100 Subject: [PATCH 16/41] cli/command/trust: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit b5dce3c9e6b7e4bbea922660ff2cd3f53ac93157) Signed-off-by: Cory Snider --- cli/command/trust/helpers_test.go | 8 +--- cli/command/trust/inspect_pretty_test.go | 15 +++---- cli/command/trust/inspect_test.go | 6 +-- cli/command/trust/key_generate.go | 3 +- cli/command/trust/key_generate_test.go | 32 +++++--------- cli/command/trust/key_load.go | 4 +- cli/command/trust/key_load_test.go | 56 ++++++++---------------- cli/command/trust/revoke_test.go | 13 ++---- cli/command/trust/sign_test.go | 51 ++++++--------------- cli/command/trust/signer_add.go | 3 +- cli/command/trust/signer_add_test.go | 42 +++++++----------- cli/command/trust/signer_remove_test.go | 6 +-- 12 files changed, 80 insertions(+), 159 deletions(-) diff --git a/cli/command/trust/helpers_test.go b/cli/command/trust/helpers_test.go index 32c247b6fee5..9ce19259d11e 100644 --- a/cli/command/trust/helpers_test.go +++ b/cli/command/trust/helpers_test.go @@ -1,8 +1,6 @@ package trust import ( - "io/ioutil" - "os" "testing" "github.com/theupdateframework/notary/client" @@ -12,11 +10,7 @@ import ( ) func TestGetOrGenerateNotaryKeyAndInitRepo(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - - notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) + notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) assert.NilError(t, err) err = getOrGenerateRootKeyAndInitRepo(notaryRepo) diff --git a/cli/command/trust/inspect_pretty_test.go b/cli/command/trust/inspect_pretty_test.go index e350ddada804..2d6e456e8ab2 100644 --- a/cli/command/trust/inspect_pretty_test.go +++ b/cli/command/trust/inspect_pretty_test.go @@ -5,7 +5,6 @@ import ( "context" "encoding/hex" "io" - "io/ioutil" "testing" "github.com/docker/cli/cli/trust" @@ -65,7 +64,7 @@ func TestTrustInspectPrettyCommandErrors(t *testing.T) { cmd := newInspectCommand( test.NewFakeCli(&fakeClient{})) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.Flags().Set("pretty", "true") assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } @@ -77,7 +76,7 @@ func TestTrustInspectPrettyCommandOfflineErrors(t *testing.T) { cmd := newInspectCommand(cli) cmd.Flags().Set("pretty", "true") cmd.SetArgs([]string{"nonexistent-reg-name.io/image"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access nonexistent-reg-name.io/image") cli = test.NewFakeCli(&fakeClient{}) @@ -85,7 +84,7 @@ func TestTrustInspectPrettyCommandOfflineErrors(t *testing.T) { cmd = newInspectCommand(cli) cmd.Flags().Set("pretty", "true") cmd.SetArgs([]string{"nonexistent-reg-name.io/image:tag"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access nonexistent-reg-name.io/image") } @@ -95,7 +94,7 @@ func TestTrustInspectPrettyCommandUninitializedErrors(t *testing.T) { cmd := newInspectCommand(cli) cmd.Flags().Set("pretty", "true") cmd.SetArgs([]string{"reg/unsigned-img"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access reg/unsigned-img") cli = test.NewFakeCli(&fakeClient{}) @@ -103,7 +102,7 @@ func TestTrustInspectPrettyCommandUninitializedErrors(t *testing.T) { cmd = newInspectCommand(cli) cmd.Flags().Set("pretty", "true") cmd.SetArgs([]string{"reg/unsigned-img:tag"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access reg/unsigned-img:tag") } @@ -113,7 +112,7 @@ func TestTrustInspectPrettyCommandEmptyNotaryRepoErrors(t *testing.T) { cmd := newInspectCommand(cli) cmd.Flags().Set("pretty", "true") cmd.SetArgs([]string{"reg/img:unsigned-tag"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.NilError(t, cmd.Execute()) assert.Check(t, is.Contains(cli.OutBuffer().String(), "No signatures for reg/img:unsigned-tag")) assert.Check(t, is.Contains(cli.OutBuffer().String(), "Administrative keys for reg/img")) @@ -123,7 +122,7 @@ func TestTrustInspectPrettyCommandEmptyNotaryRepoErrors(t *testing.T) { cmd = newInspectCommand(cli) cmd.Flags().Set("pretty", "true") cmd.SetArgs([]string{"reg/img"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.NilError(t, cmd.Execute()) assert.Check(t, is.Contains(cli.OutBuffer().String(), "No signatures for reg/img")) assert.Check(t, is.Contains(cli.OutBuffer().String(), "Administrative keys for reg/img")) diff --git a/cli/command/trust/inspect_test.go b/cli/command/trust/inspect_test.go index e3c79364cadb..af76731eddc3 100644 --- a/cli/command/trust/inspect_test.go +++ b/cli/command/trust/inspect_test.go @@ -1,7 +1,7 @@ package trust import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/cli/trust" @@ -38,7 +38,7 @@ func TestTrustInspectCommandErrors(t *testing.T) { test.NewFakeCli(&fakeClient{})) cmd.Flags().Set("pretty", "true") cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -85,7 +85,7 @@ func TestTrustInspectCommandRepositoryErrors(t *testing.T) { cli.SetNotaryClient(tc.notaryRepository) cmd := newInspectCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.err) if tc.golden != "" { golden.Assert(t, cli.OutBuffer().String(), tc.golden) diff --git a/cli/command/trust/key_generate.go b/cli/command/trust/key_generate.go index bca6c45d7df7..39eb0cb1b998 100644 --- a/cli/command/trust/key_generate.go +++ b/cli/command/trust/key_generate.go @@ -3,7 +3,6 @@ package trust import ( "encoding/pem" "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -126,7 +125,7 @@ func writePubKeyPEMToDir(pubPEM pem.Block, keyName, workingDir string) (string, // Output the public key to a file in the CWD or specified dir pubFileName := strings.Join([]string{keyName, "pub"}, ".") pubFilePath := filepath.Join(workingDir, pubFileName) - if err := ioutil.WriteFile(pubFilePath, pem.EncodeToMemory(&pubPEM), notary.PrivNoExecPerms); err != nil { + if err := os.WriteFile(pubFilePath, pem.EncodeToMemory(&pubPEM), notary.PrivNoExecPerms); err != nil { return "", errors.Wrapf(err, "failed to write public key to %s", pubFilePath) } return pubFilePath, nil diff --git a/cli/command/trust/key_generate_test.go b/cli/command/trust/key_generate_test.go index 4e3083e1af89..4645c9ae3334 100644 --- a/cli/command/trust/key_generate_test.go +++ b/cli/command/trust/key_generate_test.go @@ -3,7 +3,7 @@ package trust import ( "encoding/pem" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "testing" @@ -35,28 +35,20 @@ func TestTrustKeyGenerateErrors(t *testing.T) { }, } - tmpDir, err := ioutil.TempDir("", "docker-key-generate-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - config.SetDir(tmpDir) + config.SetDir(t.TempDir()) for _, tc := range testCases { cli := test.NewFakeCli(&fakeClient{}) cmd := newKeyGenerateCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } func TestGenerateKeySuccess(t *testing.T) { - pubKeyCWD, err := ioutil.TempDir("", "pub-keys-") - assert.NilError(t, err) - defer os.RemoveAll(pubKeyCWD) - - privKeyStorageDir, err := ioutil.TempDir("", "priv-keys-") - assert.NilError(t, err) - defer os.RemoveAll(privKeyStorageDir) + pubKeyCWD := t.TempDir() + privKeyStorageDir := t.TempDir() passwd := "password" cannedPasswordRetriever := passphrase.ConstantRetriever(passwd) @@ -79,7 +71,7 @@ func TestGenerateKeySuccess(t *testing.T) { _, err = os.Stat(expectedPrivKeyDir) assert.NilError(t, err) - keyFiles, err := ioutil.ReadDir(expectedPrivKeyDir) + keyFiles, err := os.ReadDir(expectedPrivKeyDir) assert.NilError(t, err) assert.Check(t, is.Len(keyFiles, 1)) privKeyFilePath := filepath.Join(expectedPrivKeyDir, keyFiles[0].Name()) @@ -87,7 +79,7 @@ func TestGenerateKeySuccess(t *testing.T) { // verify the key content privFrom, _ := os.OpenFile(privKeyFilePath, os.O_RDONLY, notary.PrivExecPerms) defer privFrom.Close() - fromBytes, _ := ioutil.ReadAll(privFrom) + fromBytes, _ := io.ReadAll(privFrom) privKeyPEM, _ := pem.Decode(fromBytes) assert.Check(t, is.Equal(keyName, privKeyPEM.Headers["role"])) // the default GUN is empty @@ -106,17 +98,15 @@ func TestGenerateKeySuccess(t *testing.T) { _, err = os.Stat(expectedPubKeyPath) assert.NilError(t, err) // check that the public key is the only file output in CWD - cwdKeyFiles, err := ioutil.ReadDir(pubKeyCWD) + cwdKeyFiles, err := os.ReadDir(pubKeyCWD) assert.NilError(t, err) assert.Check(t, is.Len(cwdKeyFiles, 1)) } func TestValidateKeyArgs(t *testing.T) { - pubKeyCWD, err := ioutil.TempDir("", "pub-keys-") - assert.NilError(t, err) - defer os.RemoveAll(pubKeyCWD) + pubKeyCWD := t.TempDir() - err = validateKeyArgs("a", pubKeyCWD) + err := validateKeyArgs("a", pubKeyCWD) assert.NilError(t, err) err = validateKeyArgs("a/b", pubKeyCWD) @@ -125,7 +115,7 @@ func TestValidateKeyArgs(t *testing.T) { err = validateKeyArgs("-", pubKeyCWD) assert.Error(t, err, "key name \"-\" must start with lowercase alphanumeric characters and can include \"-\" or \"_\" after the first character") - assert.NilError(t, ioutil.WriteFile(filepath.Join(pubKeyCWD, "a.pub"), []byte("abc"), notary.PrivExecPerms)) + assert.NilError(t, os.WriteFile(filepath.Join(pubKeyCWD, "a.pub"), []byte("abc"), notary.PrivExecPerms)) err = validateKeyArgs("a", pubKeyCWD) assert.Error(t, err, fmt.Sprintf("public key file already exists: \"%s\"", filepath.Join(pubKeyCWD, "a.pub"))) diff --git a/cli/command/trust/key_load.go b/cli/command/trust/key_load.go index 3b2c04bac9e9..6fce409d774a 100644 --- a/cli/command/trust/key_load.go +++ b/cli/command/trust/key_load.go @@ -4,7 +4,7 @@ import ( "bytes" "encoding/pem" "fmt" - "io/ioutil" + "io" "os" "runtime" @@ -86,7 +86,7 @@ func getPrivKeyBytesFromPath(keyPath string) ([]byte, error) { } defer from.Close() - return ioutil.ReadAll(from) + return io.ReadAll(from) } func loadPrivKeyBytesToStore(privKeyBytes []byte, privKeyImporters []trustmanager.Importer, keyPath, keyName string, passRet notary.PassRetriever) error { diff --git a/cli/command/trust/key_load_test.go b/cli/command/trust/key_load_test.go index 89386a319bf5..4cc0fc252d57 100644 --- a/cli/command/trust/key_load_test.go +++ b/cli/command/trust/key_load_test.go @@ -3,7 +3,7 @@ package trust import ( "encoding/pem" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "runtime" @@ -56,16 +56,13 @@ func TestTrustKeyLoadErrors(t *testing.T) { expectedOutput: "", }, } - tmpDir, err := ioutil.TempDir("", "docker-key-load-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - config.SetDir(tmpDir) + config.SetDir(t.TempDir()) for _, tc := range testCases { cli := test.NewFakeCli(&fakeClient{}) cmd := newKeyLoadCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.Check(t, is.Contains(cli.OutBuffer().String(), tc.expectedOutput)) } @@ -125,17 +122,12 @@ func TestLoadKeyFromPath(t *testing.T) { } func testLoadKeyFromPath(t *testing.T, privKeyID string, privKeyFixture []byte) { - privKeyDir, err := ioutil.TempDir("", "key-load-test-") - assert.NilError(t, err) - defer os.RemoveAll(privKeyDir) - privKeyFilepath := filepath.Join(privKeyDir, "privkey.pem") - assert.NilError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, notary.PrivNoExecPerms)) + privKeyFilepath := filepath.Join(t.TempDir(), "privkey.pem") + assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, notary.PrivNoExecPerms)) - keyStorageDir, err := ioutil.TempDir("", "loaded-keys-") - assert.NilError(t, err) - defer os.RemoveAll(keyStorageDir) + keyStorageDir := t.TempDir() - passwd := "password" + const passwd = "password" cannedPasswordRetriever := passphrase.ConstantRetriever(passwd) keyFileStore, err := storage.NewPrivateKeyFileStorage(keyStorageDir, notary.KeyExtension) assert.NilError(t, err) @@ -156,7 +148,7 @@ func testLoadKeyFromPath(t *testing.T, privKeyID string, privKeyFixture []byte) // verify the key content from, _ := os.OpenFile(expectedImportKeyPath, os.O_RDONLY, notary.PrivExecPerms) defer from.Close() - fromBytes, _ := ioutil.ReadAll(from) + fromBytes, _ := io.ReadAll(from) keyPEM, _ := pem.Decode(fromBytes) assert.Check(t, is.Equal("signer-name", keyPEM.Headers["role"])) // the default GUN is empty @@ -181,43 +173,37 @@ func TestLoadKeyTooPermissive(t *testing.T) { } func testLoadKeyTooPermissive(t *testing.T, privKeyFixture []byte) { - privKeyDir, err := ioutil.TempDir("", "key-load-test-") - assert.NilError(t, err) - defer os.RemoveAll(privKeyDir) + privKeyDir := t.TempDir() privKeyFilepath := filepath.Join(privKeyDir, "privkey477.pem") - assert.NilError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0477)) - - keyStorageDir, err := ioutil.TempDir("", "loaded-keys-") - assert.NilError(t, err) - defer os.RemoveAll(keyStorageDir) + assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0477)) // import the key to our keyStorageDir - _, err = getPrivKeyBytesFromPath(privKeyFilepath) + _, err := getPrivKeyBytesFromPath(privKeyFilepath) expected := fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath) assert.Error(t, err, expected) privKeyFilepath = filepath.Join(privKeyDir, "privkey667.pem") - assert.NilError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0677)) + assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0677)) _, err = getPrivKeyBytesFromPath(privKeyFilepath) expected = fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath) assert.Error(t, err, expected) privKeyFilepath = filepath.Join(privKeyDir, "privkey777.pem") - assert.NilError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0777)) + assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0777)) _, err = getPrivKeyBytesFromPath(privKeyFilepath) expected = fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath) assert.Error(t, err, expected) privKeyFilepath = filepath.Join(privKeyDir, "privkey400.pem") - assert.NilError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0400)) + assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0400)) _, err = getPrivKeyBytesFromPath(privKeyFilepath) assert.NilError(t, err) privKeyFilepath = filepath.Join(privKeyDir, "privkey600.pem") - assert.NilError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0600)) + assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0600)) _, err = getPrivKeyBytesFromPath(privKeyFilepath) assert.NilError(t, err) @@ -230,16 +216,12 @@ H3nzy2O6Q/ct4BjOBKa+WCdRtPo78bA+C/7t81ADQO8Jqaj59W50rwoqDQ== func TestLoadPubKeyFailure(t *testing.T) { skip.If(t, runtime.GOOS == "windows") - pubKeyDir, err := ioutil.TempDir("", "key-load-test-pubkey-") - assert.NilError(t, err) - defer os.RemoveAll(pubKeyDir) + pubKeyDir := t.TempDir() pubKeyFilepath := filepath.Join(pubKeyDir, "pubkey.pem") - assert.NilError(t, ioutil.WriteFile(pubKeyFilepath, pubKeyFixture, notary.PrivNoExecPerms)) - keyStorageDir, err := ioutil.TempDir("", "loaded-keys-") - assert.NilError(t, err) - defer os.RemoveAll(keyStorageDir) + assert.NilError(t, os.WriteFile(pubKeyFilepath, pubKeyFixture, notary.PrivNoExecPerms)) + keyStorageDir := t.TempDir() - passwd := "password" + const passwd = "password" cannedPasswordRetriever := passphrase.ConstantRetriever(passwd) keyFileStore, err := storage.NewPrivateKeyFileStorage(keyStorageDir, notary.KeyExtension) assert.NilError(t, err) diff --git a/cli/command/trust/revoke_test.go b/cli/command/trust/revoke_test.go index bd550a7d2708..6fd83a8ba952 100644 --- a/cli/command/trust/revoke_test.go +++ b/cli/command/trust/revoke_test.go @@ -1,8 +1,7 @@ package trust import ( - "io/ioutil" - "os" + "io" "testing" "github.com/docker/cli/cli/trust" @@ -50,7 +49,7 @@ func TestTrustRevokeCommandErrors(t *testing.T) { cmd := newRevokeCommand( test.NewFakeCli(&fakeClient{})) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -131,7 +130,7 @@ func TestTrustRevokeCommand(t *testing.T) { cli.SetNotaryClient(tc.notaryRepository) cmd := newRevokeCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) if tc.expectedErr != "" { assert.ErrorContains(t, cmd.Execute(), tc.expectedErr) return @@ -144,11 +143,7 @@ func TestTrustRevokeCommand(t *testing.T) { } func TestGetSignableRolesForTargetAndRemoveError(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - - notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{}) + notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{}) assert.NilError(t, err) target := client.Target{} err = getSignableRolesForTargetAndRemove(target, notaryRepo) diff --git a/cli/command/trust/sign_test.go b/cli/command/trust/sign_test.go index 25704140865b..f318d955180c 100644 --- a/cli/command/trust/sign_test.go +++ b/cli/command/trust/sign_test.go @@ -3,8 +3,7 @@ package trust import ( "bytes" "encoding/json" - "io/ioutil" - "os" + "io" "runtime" "testing" @@ -62,15 +61,12 @@ func TestTrustSignCommandErrors(t *testing.T) { }, } // change to a tmpdir - tmpDir, err := ioutil.TempDir("", "docker-sign-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - config.SetDir(tmpDir) + config.SetDir(t.TempDir()) for _, tc := range testCases { cmd := newSignCommand( test.NewFakeCli(&fakeClient{})) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -80,16 +76,12 @@ func TestTrustSignCommandOfflineErrors(t *testing.T) { cli.SetNotaryClient(notaryfake.GetOfflineNotaryRepository) cmd := newSignCommand(cli) cmd.SetArgs([]string{"reg-name.io/image:tag"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), "client is offline") } func TestGetOrGenerateNotaryKey(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - - notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) + notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) assert.NilError(t, err) // repo is empty, try making a root key @@ -131,11 +123,8 @@ func TestGetOrGenerateNotaryKey(t *testing.T) { func TestAddStageSigners(t *testing.T) { skip.If(t, runtime.GOOS == "windows", "FIXME: not supported currently") - tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) + notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) assert.NilError(t, err) // stage targets/user @@ -216,11 +205,7 @@ func TestAddStageSigners(t *testing.T) { } func TestGetSignedManifestHashAndSize(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - - notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) + notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) assert.NilError(t, err) target := &client.Target{} target.Hashes, target.Length, err = getSignedManifestHashAndSize(notaryRepo, "test") @@ -244,11 +229,7 @@ func TestGetReleasedTargetHashAndSize(t *testing.T) { } func TestCreateTarget(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - - notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) + notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) assert.NilError(t, err) _, err = createTarget(notaryRepo, "") assert.Error(t, err, "No tag specified") @@ -257,11 +238,7 @@ func TestCreateTarget(t *testing.T) { } func TestGetExistingSignatureInfoForReleasedTag(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - - notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) + notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) assert.NilError(t, err) _, err = getExistingSignatureInfoForReleasedTag(notaryRepo, "test") assert.Error(t, err, "client is offline") @@ -277,18 +254,16 @@ func TestPrettyPrintExistingSignatureInfo(t *testing.T) { } func TestSignCommandChangeListIsCleanedOnError(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "docker-sign-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() config.SetDir(tmpDir) cli := test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(notaryfake.GetLoadedNotaryRepository) cmd := newSignCommand(cli) cmd.SetArgs([]string{"ubuntu:latest"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) - err = cmd.Execute() + err := cmd.Execute() assert.Assert(t, err != nil) notaryRepo, err := client.NewFileCachedRepository(tmpDir, "docker.io/library/ubuntu", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) @@ -303,7 +278,7 @@ func TestSignCommandLocalFlag(t *testing.T) { cli.SetNotaryClient(notaryfake.GetEmptyTargetsNotaryRepository) cmd := newSignCommand(cli) cmd.SetArgs([]string{"--local", "reg-name.io/image:red"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), "error contacting notary server: dial tcp: lookup reg-name.io") } diff --git a/cli/command/trust/signer_add.go b/cli/command/trust/signer_add.go index 304aeec92f68..307d864deafb 100644 --- a/cli/command/trust/signer_add.go +++ b/cli/command/trust/signer_add.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "path" "regexp" @@ -125,7 +124,7 @@ func ingestPublicKeys(pubKeyPaths []string) ([]data.PublicKey, error) { defer pubKeyFile.Close() // limit to l := io.LimitReader(pubKeyFile, 1<<20) - pubKeyBytes, err := ioutil.ReadAll(l) + pubKeyBytes, err := io.ReadAll(l) if err != nil { return nil, errors.Wrap(err, "unable to read public key from file") } diff --git a/cli/command/trust/signer_add_test.go b/cli/command/trust/signer_add_test.go index d487883d3593..50165283bb1a 100644 --- a/cli/command/trust/signer_add_test.go +++ b/cli/command/trust/signer_add_test.go @@ -2,7 +2,7 @@ package trust import ( "fmt" - "io/ioutil" + "io" "os" "path/filepath" "runtime" @@ -52,29 +52,24 @@ func TestTrustSignerAddErrors(t *testing.T) { expectedError: "signer name \"_alice\" must start with lowercase alphanumeric characters and can include \"-\" or \"_\" after the first character", }, } - tmpDir, err := ioutil.TempDir("", "docker-sign-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - config.SetDir(tmpDir) + config.SetDir(t.TempDir()) for _, tc := range testCases { cli := test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(notaryfake.GetOfflineNotaryRepository) cmd := newSignerAddCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } func TestSignerAddCommandNoTargetsKey(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "docker-sign-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - config.SetDir(tmpDir) + config.SetDir(t.TempDir()) - tmpfile, err := ioutil.TempFile("", "pemfile") + tmpfile, err := os.CreateTemp("", "pemfile") assert.NilError(t, err) + tmpfile.Close() defer os.Remove(tmpfile.Name()) cli := test.NewFakeCli(&fakeClient{}) @@ -82,22 +77,19 @@ func TestSignerAddCommandNoTargetsKey(t *testing.T) { cmd := newSignerAddCommand(cli) cmd.SetArgs([]string{"--key", tmpfile.Name(), "alice", "alpine", "linuxkit/alpine"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.Error(t, cmd.Execute(), fmt.Sprintf("could not parse public key from file: %s: no valid public key found", tmpfile.Name())) } func TestSignerAddCommandBadKeyPath(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "docker-sign-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - config.SetDir(tmpDir) + config.SetDir(t.TempDir()) cli := test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(notaryfake.GetEmptyTargetsNotaryRepository) cmd := newSignerAddCommand(cli) cmd.SetArgs([]string{"--key", "/path/to/key.pem", "alice", "alpine"}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) expectedError := "unable to read public key from file: open /path/to/key.pem: no such file or directory" if runtime.GOOS == "windows" { expectedError = "unable to read public key from file: open /path/to/key.pem: The system cannot find the path specified." @@ -106,16 +98,11 @@ func TestSignerAddCommandBadKeyPath(t *testing.T) { } func TestSignerAddCommandInvalidRepoName(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "docker-sign-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - config.SetDir(tmpDir) + config.SetDir(t.TempDir()) - pubKeyDir, err := ioutil.TempDir("", "key-load-test-pubkey-") - assert.NilError(t, err) - defer os.RemoveAll(pubKeyDir) + pubKeyDir := t.TempDir() pubKeyFilepath := filepath.Join(pubKeyDir, "pubkey.pem") - assert.NilError(t, ioutil.WriteFile(pubKeyFilepath, pubKeyFixture, notary.PrivNoExecPerms)) + assert.NilError(t, os.WriteFile(pubKeyFilepath, pubKeyFixture, notary.PrivNoExecPerms)) cli := test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(notaryfake.GetUninitializedNotaryRepository) @@ -123,7 +110,7 @@ func TestSignerAddCommandInvalidRepoName(t *testing.T) { imageName := "870d292919d01a0af7e7f056271dc78792c05f55f49b9b9012b6d89725bd9abd" cmd.SetArgs([]string{"--key", pubKeyFilepath, "alice", imageName}) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.Error(t, cmd.Execute(), "Failed to add signer to: 870d292919d01a0af7e7f056271dc78792c05f55f49b9b9012b6d89725bd9abd") expectedErr := fmt.Sprintf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings\n\n", imageName) @@ -139,8 +126,9 @@ func TestIngestPublicKeys(t *testing.T) { } assert.Error(t, err, expectedError) // Call with real file path - tmpfile, err := ioutil.TempFile("", "pemfile") + tmpfile, err := os.CreateTemp("", "pemfile") assert.NilError(t, err) + tmpfile.Close() defer os.Remove(tmpfile.Name()) _, err = ingestPublicKeys([]string{tmpfile.Name()}) assert.Error(t, err, fmt.Sprintf("could not parse public key from file: %s: no valid public key found", tmpfile.Name())) diff --git a/cli/command/trust/signer_remove_test.go b/cli/command/trust/signer_remove_test.go index 44fddce0e5be..c268fc82a54f 100644 --- a/cli/command/trust/signer_remove_test.go +++ b/cli/command/trust/signer_remove_test.go @@ -1,7 +1,7 @@ package trust import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -32,7 +32,7 @@ func TestTrustSignerRemoveErrors(t *testing.T) { cmd := newSignerRemoveCommand( test.NewFakeCli(&fakeClient{})) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } testCasesWithOutput := []struct { @@ -61,7 +61,7 @@ func TestTrustSignerRemoveErrors(t *testing.T) { cli.SetNotaryClient(notaryfake.GetOfflineNotaryRepository) cmd := newSignerRemoveCommand(cli) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) cmd.Execute() assert.Check(t, is.Contains(cli.ErrBuffer().String(), tc.expectedError)) } From 03d93a93c3e8c44c08894d8e27cab9f335b25f2c Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:34:38 +0100 Subject: [PATCH 17/41] cli/command/volume: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit cca73bff41382c25bcf5d695120a520ce72f23c1) Signed-off-by: Cory Snider --- cli/command/volume/create_test.go | 4 ++-- cli/command/volume/inspect_test.go | 4 ++-- cli/command/volume/list_test.go | 4 ++-- cli/command/volume/prune_test.go | 8 ++++---- cli/command/volume/remove_test.go | 4 ++-- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/cli/command/volume/create_test.go b/cli/command/volume/create_test.go index e9eaa58179d1..875253b5c87d 100644 --- a/cli/command/volume/create_test.go +++ b/cli/command/volume/create_test.go @@ -1,7 +1,7 @@ package volume import ( - "io/ioutil" + "io" "reflect" "strings" "testing" @@ -49,7 +49,7 @@ func TestVolumeCreateErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/volume/inspect_test.go b/cli/command/volume/inspect_test.go index 49907202bce6..40ab82c50b17 100644 --- a/cli/command/volume/inspect_test.go +++ b/cli/command/volume/inspect_test.go @@ -2,7 +2,7 @@ package volume import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -60,7 +60,7 @@ func TestVolumeInspectErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/volume/list_test.go b/cli/command/volume/list_test.go index 2c1501e5c7f0..77f63d52199e 100644 --- a/cli/command/volume/list_test.go +++ b/cli/command/volume/list_test.go @@ -1,7 +1,7 @@ package volume import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/cli/config/configfile" @@ -43,7 +43,7 @@ func TestVolumeListErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } diff --git a/cli/command/volume/prune_test.go b/cli/command/volume/prune_test.go index 8e668c57f68c..7cfbad66b312 100644 --- a/cli/command/volume/prune_test.go +++ b/cli/command/volume/prune_test.go @@ -2,7 +2,7 @@ package volume import ( "fmt" - "io/ioutil" + "io" "runtime" "strings" "testing" @@ -48,7 +48,7 @@ func TestVolumePruneErrors(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -86,7 +86,7 @@ func TestVolumePrunePromptYes(t *testing.T) { volumePruneFunc: simplePruneFunc, }) - cli.SetIn(streams.NewIn(ioutil.NopCloser(strings.NewReader(input)))) + cli.SetIn(streams.NewIn(io.NopCloser(strings.NewReader(input)))) cmd := NewPruneCommand(cli) assert.NilError(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "volume-prune-yes.golden") @@ -102,7 +102,7 @@ func TestVolumePrunePromptNo(t *testing.T) { volumePruneFunc: simplePruneFunc, }) - cli.SetIn(streams.NewIn(ioutil.NopCloser(strings.NewReader(input)))) + cli.SetIn(streams.NewIn(io.NopCloser(strings.NewReader(input)))) cmd := NewPruneCommand(cli) assert.NilError(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "volume-prune-no.golden") diff --git a/cli/command/volume/remove_test.go b/cli/command/volume/remove_test.go index 19bc467d7079..6f617f9ce027 100644 --- a/cli/command/volume/remove_test.go +++ b/cli/command/volume/remove_test.go @@ -1,7 +1,7 @@ package volume import ( - "io/ioutil" + "io" "testing" "github.com/docker/cli/internal/test" @@ -32,7 +32,7 @@ func TestVolumeRemoveErrors(t *testing.T) { volumeRemoveFunc: tc.volumeRemoveFunc, })) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } From 8efbfcce25f566abbac16fb3185f1c1479427466 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:35:28 +0100 Subject: [PATCH 18/41] cli/command: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 3f7e7bf9d2ff009c8b716d84b9d656c172e211bd) Signed-off-by: Cory Snider --- cli/command/cli.go | 3 +-- cli/command/cli_test.go | 10 +++---- cli/command/defaultcontextstore_test.go | 35 ++++++++----------------- cli/command/orchestrator_test.go | 4 +-- cli/command/utils_test.go | 9 +++---- 5 files changed, 22 insertions(+), 39 deletions(-) diff --git a/cli/command/cli.go b/cli/command/cli.go index fe6444f42f8d..4e27a1457e05 100644 --- a/cli/command/cli.go +++ b/cli/command/cli.go @@ -3,7 +3,6 @@ package command import ( "context" "io" - "io/ioutil" "os" "path/filepath" "runtime" @@ -279,7 +278,7 @@ func NewAPIClientFromFlags(opts *cliflags.CommonOptions, configFile *configfile. store := &ContextStoreWithDefault{ Store: store.New(cliconfig.ContextStoreDir(), storeConfig), Resolver: func() (*DefaultContext, error) { - return ResolveDefaultContext(opts, configFile, storeConfig, ioutil.Discard) + return ResolveDefaultContext(opts, configFile, storeConfig, io.Discard) }, } contextName, err := resolveContextName(opts, configFile, store) diff --git a/cli/command/cli_test.go b/cli/command/cli_test.go index 370ecec803b9..a497b8fd650c 100644 --- a/cli/command/cli_test.go +++ b/cli/command/cli_test.go @@ -5,7 +5,7 @@ import ( "context" "crypto/x509" "fmt" - "io/ioutil" + "io" "os" "runtime" "testing" @@ -275,23 +275,23 @@ func TestNewDockerCliAndOperators(t *testing.T) { outbuf := bytes.NewBuffer(nil) errbuf := bytes.NewBuffer(nil) err = cli.Apply( - WithInputStream(ioutil.NopCloser(inbuf)), + WithInputStream(io.NopCloser(inbuf)), WithOutputStream(outbuf), WithErrorStream(errbuf), ) assert.NilError(t, err) // Check input stream - inputStream, err := ioutil.ReadAll(cli.In()) + inputStream, err := io.ReadAll(cli.In()) assert.NilError(t, err) assert.Equal(t, string(inputStream), "input") // Check output stream fmt.Fprintf(cli.Out(), "output") - outputStream, err := ioutil.ReadAll(outbuf) + outputStream, err := io.ReadAll(outbuf) assert.NilError(t, err) assert.Equal(t, string(outputStream), "output") // Check error stream fmt.Fprintf(cli.Err(), "error") - errStream, err := ioutil.ReadAll(errbuf) + errStream, err := io.ReadAll(errbuf) assert.NilError(t, err) assert.Equal(t, string(errStream), "error") } diff --git a/cli/command/defaultcontextstore_test.go b/cli/command/defaultcontextstore_test.go index 3c36dc0dcb97..2f0371968f30 100644 --- a/cli/command/defaultcontextstore_test.go +++ b/cli/command/defaultcontextstore_test.go @@ -2,8 +2,6 @@ package command import ( "crypto/rand" - "io/ioutil" - "os" "testing" "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()) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - s := &ContextStoreWithDefault{ - Store: store.New(testDir, testCfg), +func testStore(t *testing.T, meta store.Metadata, tls store.ContextTLSData) store.Store { + t.Helper() + return &ContextStoreWithDefault{ + Store: store.New(t.TempDir(), testCfg), Resolver: func() (*DefaultContext, error) { return &DefaultContext{ Meta: meta, @@ -51,9 +48,6 @@ func testStore(t *testing.T, meta store.Metadata, tls store.ContextTLSData) (sto }, nil }, } - return s, func() { - _ = os.RemoveAll(testDir) - } } func TestDefaultContextInitializer(t *testing.T) { @@ -81,7 +75,7 @@ func TestExportDefaultImport(t *testing.T) { rand.Read(file1) file2 := make([]byte, 3700) rand.Read(file2) - s, cleanup := testStore(t, testDefaultMetadata(), store.ContextTLSData{ + s := testStore(t, testDefaultMetadata(), store.ContextTLSData{ Endpoints: map[string]store.EndpointTLSData{ "ep2": { Files: map[string][]byte{ @@ -91,7 +85,6 @@ func TestExportDefaultImport(t *testing.T) { }, }, }) - defer cleanup() r := store.Export("default", s) defer r.Close() err := store.Import("dest", s, r) @@ -130,8 +123,7 @@ func TestExportDefaultImport(t *testing.T) { func TestListDefaultContext(t *testing.T) { meta := testDefaultMetadata() - s, cleanup := testStore(t, meta, store.ContextTLSData{}) - defer cleanup() + s := testStore(t, meta, store.ContextTLSData{}) result, err := s.List() assert.NilError(t, err) assert.Equal(t, 1, len(result)) @@ -139,8 +131,7 @@ func TestListDefaultContext(t *testing.T) { } func TestGetDefaultContextStorageInfo(t *testing.T) { - s, cleanup := testStore(t, testDefaultMetadata(), store.ContextTLSData{}) - defer cleanup() + s := testStore(t, testDefaultMetadata(), store.ContextTLSData{}) result := s.GetStorageInfo(DefaultContextName) assert.Equal(t, "", result.MetadataPath) assert.Equal(t, "", result.TLSPath) @@ -148,8 +139,7 @@ func TestGetDefaultContextStorageInfo(t *testing.T) { func TestGetDefaultContextMetadata(t *testing.T) { meta := testDefaultMetadata() - s, cleanup := testStore(t, meta, store.ContextTLSData{}) - defer cleanup() + s := testStore(t, meta, store.ContextTLSData{}) result, err := s.GetMetadata(DefaultContextName) assert.NilError(t, err) assert.Equal(t, DefaultContextName, result.Name) @@ -159,8 +149,7 @@ func TestGetDefaultContextMetadata(t *testing.T) { func TestErrCreateDefault(t *testing.T) { meta := testDefaultMetadata() - s, cleanup := testStore(t, meta, store.ContextTLSData{}) - defer cleanup() + s := testStore(t, meta, store.ContextTLSData{}) err := s.CreateOrUpdate(store.Metadata{ Endpoints: map[string]interface{}{ "ep1": endpoint{Foo: "bar"}, @@ -173,16 +162,14 @@ func TestErrCreateDefault(t *testing.T) { func TestErrRemoveDefault(t *testing.T) { meta := testDefaultMetadata() - s, cleanup := testStore(t, meta, store.ContextTLSData{}) - defer cleanup() + s := testStore(t, meta, store.ContextTLSData{}) err := s.Remove("default") assert.Error(t, err, "default context cannot be removed") } func TestErrTLSDataError(t *testing.T) { meta := testDefaultMetadata() - s, cleanup := testStore(t, meta, store.ContextTLSData{}) - defer cleanup() + s := testStore(t, meta, store.ContextTLSData{}) _, err := s.GetTLSData("default", "noop", "noop") assert.Check(t, store.IsErrTLSDataDoesNotExist(err)) } diff --git a/cli/command/orchestrator_test.go b/cli/command/orchestrator_test.go index fbd9018effd0..b2e7ebb7ac4d 100644 --- a/cli/command/orchestrator_test.go +++ b/cli/command/orchestrator_test.go @@ -1,7 +1,7 @@ package command import ( - "io/ioutil" + "io" "testing" "gotest.tools/v3/assert" @@ -91,7 +91,7 @@ func TestOrchestratorSwitch(t *testing.T) { if 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.Check(t, is.Equal(testcase.expectedKubernetes, orchestrator.HasKubernetes())) assert.Check(t, is.Equal(testcase.expectedSwarm, orchestrator.HasSwarm())) diff --git a/cli/command/utils_test.go b/cli/command/utils_test.go index 566b93284157..2af232d2e9b7 100644 --- a/cli/command/utils_test.go +++ b/cli/command/utils_test.go @@ -1,7 +1,6 @@ package command import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -37,15 +36,13 @@ func TestStringSliceReplaceAt(t *testing.T) { } func TestValidateOutputPath(t *testing.T) { - basedir, err := ioutil.TempDir("", "TestValidateOutputPath") - assert.NilError(t, err) - defer os.RemoveAll(basedir) + basedir := t.TempDir() dir := filepath.Join(basedir, "dir") notexist := filepath.Join(basedir, "notexist") - err = os.MkdirAll(dir, 0755) + err := os.MkdirAll(dir, 0755) assert.NilError(t, err) file := filepath.Join(dir, "file") - err = ioutil.WriteFile(file, []byte("hi"), 0644) + err = os.WriteFile(file, []byte("hi"), 0644) assert.NilError(t, err) var testcases = []struct { path string From 38e86531d6c9b88ff8f9c1db6a2b21c72e5cdd5a Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:36:05 +0100 Subject: [PATCH 19/41] cli/compose: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit b9f0340b68d50491e6dd5f7f49af4c1c1aa8de54) Signed-off-by: Cory Snider --- cli/compose/convert/compose.go | 4 ++-- cli/compose/loader/loader_test.go | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/cli/compose/convert/compose.go b/cli/compose/convert/compose.go index 189a909622a3..98cd92989b8f 100644 --- a/cli/compose/convert/compose.go +++ b/cli/compose/convert/compose.go @@ -1,7 +1,7 @@ package convert import ( - "io/ioutil" + "os" "strings" composetypes "github.com/docker/cli/cli/compose/types" @@ -178,7 +178,7 @@ func driverObjectConfig(namespace Namespace, name string, obj composetypes.FileO } func fileObjectConfig(namespace Namespace, name string, obj composetypes.FileObjectConfig) (swarmFileObject, error) { - data, err := ioutil.ReadFile(obj.File) + data, err := os.ReadFile(obj.File) if err != nil { return swarmFileObject{}, err } diff --git a/cli/compose/loader/loader_test.go b/cli/compose/loader/loader_test.go index db57dba24a2d..4b2fc9cbb69b 100644 --- a/cli/compose/loader/loader_test.go +++ b/cli/compose/loader/loader_test.go @@ -2,7 +2,6 @@ package loader import ( "bytes" - "io/ioutil" "os" "reflect" "sort" @@ -946,7 +945,7 @@ func uint32Ptr(value uint32) *uint32 { } func TestFullExample(t *testing.T) { - bytes, err := ioutil.ReadFile("full-example.yml") + bytes, err := os.ReadFile("full-example.yml") assert.NilError(t, err) homeDir := "/home/foo" From fc37f52414cdefba12f69a0660b0c1ee3a4a51e5 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:36:33 +0100 Subject: [PATCH 20/41] cli/config: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 71575ab3b52eae93f667902fe32f91fc89612bff) Signed-off-by: Cory Snider --- cli/config/config_test.go | 114 +++++++------------- cli/config/configfile/file.go | 5 +- cli/config/configfile/file_test.go | 15 ++- cli/config/credentials/native_store_test.go | 3 +- 4 files changed, 48 insertions(+), 89 deletions(-) diff --git a/cli/config/config_test.go b/cli/config/config_test.go index 26197454e6ee..c6858e9ffd35 100644 --- a/cli/config/config_test.go +++ b/cli/config/config_test.go @@ -3,7 +3,6 @@ package config import ( "bytes" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -27,21 +26,18 @@ func init() { } } -func setupConfigDir(t *testing.T) (string, func()) { - tmpdir, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) +func setupConfigDir(t *testing.T) string { + tmpdir := t.TempDir() oldDir := Dir() SetDir(tmpdir) - - return tmpdir, func() { + t.Cleanup(func() { SetDir(oldDir) - os.RemoveAll(tmpdir) - } + }) + return tmpdir } func TestEmptyConfigDir(t *testing.T) { - tmpHome, cleanup := setupConfigDir(t) - defer cleanup() + tmpHome := setupConfigDir(t) config, err := Load("") assert.NilError(t, err) @@ -54,9 +50,7 @@ func TestEmptyConfigDir(t *testing.T) { } func TestMissingFile(t *testing.T) { - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() config, err := Load(tmpHome) assert.NilError(t, err) @@ -66,9 +60,7 @@ func TestMissingFile(t *testing.T) { } func TestSaveFileToDirs(t *testing.T) { - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() tmpHome += "/.docker" @@ -80,12 +72,10 @@ func TestSaveFileToDirs(t *testing.T) { } func TestEmptyFile(t *testing.T) { - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() fn := filepath.Join(tmpHome, ConfigFileName) - err = ioutil.WriteFile(fn, []byte(""), 0600) + err := os.WriteFile(fn, []byte(""), 0600) assert.NilError(t, err) _, err = Load(tmpHome) @@ -93,12 +83,10 @@ func TestEmptyFile(t *testing.T) { } func TestEmptyJSON(t *testing.T) { - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() fn := filepath.Join(tmpHome, ConfigFileName) - err = ioutil.WriteFile(fn, []byte("{}"), 0600) + err := os.WriteFile(fn, []byte("{}"), 0600) assert.NilError(t, err) config, err := Load(tmpHome) @@ -118,14 +106,12 @@ email`: "Invalid auth configuration file", } resetHomeDir() - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() defer env.Patch(t, homeKey, tmpHome)() for content, expectedError := range invalids { fn := filepath.Join(tmpHome, oldConfigfile) - err := ioutil.WriteFile(fn, []byte(content), 0600) + err := os.WriteFile(fn, []byte(content), 0600) assert.NilError(t, err) _, err = Load(tmpHome) @@ -135,15 +121,13 @@ email`: "Invalid auth configuration file", func TestOldValidAuth(t *testing.T) { resetHomeDir() - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() defer env.Patch(t, homeKey, tmpHome)() fn := filepath.Join(tmpHome, oldConfigfile) js := `username = am9lam9lOmhlbGxv email = user@example.com` - err = ioutil.WriteFile(fn, []byte(js), 0600) + err := os.WriteFile(fn, []byte(js), 0600) assert.NilError(t, err) config, err := Load(tmpHome) @@ -170,14 +154,12 @@ func TestOldValidAuth(t *testing.T) { func TestOldJSONInvalid(t *testing.T) { resetHomeDir() - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() defer env.Patch(t, homeKey, tmpHome)() fn := filepath.Join(tmpHome, oldConfigfile) js := `{"https://index.docker.io/v1/":{"auth":"test","email":"user@example.com"}}` - if err := ioutil.WriteFile(fn, []byte(js), 0600); err != nil { + if err := os.WriteFile(fn, []byte(js), 0600); err != nil { t.Fatal(err) } @@ -190,14 +172,12 @@ func TestOldJSONInvalid(t *testing.T) { func TestOldJSON(t *testing.T) { resetHomeDir() - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() defer env.Patch(t, homeKey, tmpHome)() fn := filepath.Join(tmpHome, oldConfigfile) js := `{"https://index.docker.io/v1/":{"auth":"am9lam9lOmhlbGxv","email":"user@example.com"}}` - if err := ioutil.WriteFile(fn, []byte(js), 0600); err != nil { + if err := os.WriteFile(fn, []byte(js), 0600); err != nil { t.Fatal(err) } @@ -251,13 +231,11 @@ func TestOldJSONFallbackDeprecationWarning(t *testing.T) { } func TestNewJSON(t *testing.T) { - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() fn := filepath.Join(tmpHome, ConfigFileName) js := ` { "auths": { "https://index.docker.io/v1/": { "auth": "am9lam9lOmhlbGxv" } } }` - if err := ioutil.WriteFile(fn, []byte(js), 0600); err != nil { + if err := os.WriteFile(fn, []byte(js), 0600); err != nil { t.Fatal(err) } @@ -285,13 +263,11 @@ func TestNewJSON(t *testing.T) { } func TestNewJSONNoEmail(t *testing.T) { - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() fn := filepath.Join(tmpHome, ConfigFileName) js := ` { "auths": { "https://index.docker.io/v1/": { "auth": "am9lam9lOmhlbGxv" } } }` - if err := ioutil.WriteFile(fn, []byte(js), 0600); err != nil { + if err := os.WriteFile(fn, []byte(js), 0600); err != nil { t.Fatal(err) } @@ -319,16 +295,14 @@ func TestNewJSONNoEmail(t *testing.T) { } func TestJSONWithPsFormat(t *testing.T) { - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() fn := filepath.Join(tmpHome, ConfigFileName) js := `{ "auths": { "https://index.docker.io/v1/": { "auth": "am9lam9lOmhlbGxv", "email": "user@example.com" } }, "psFormat": "table {{.ID}}\\t{{.Label \"com.docker.label.cpu\"}}" }` - if err := ioutil.WriteFile(fn, []byte(js), 0600); err != nil { + if err := os.WriteFile(fn, []byte(js), 0600); err != nil { t.Fatal(err) } @@ -348,16 +322,14 @@ func TestJSONWithPsFormat(t *testing.T) { } func TestJSONWithCredentialStore(t *testing.T) { - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() fn := filepath.Join(tmpHome, ConfigFileName) js := `{ "auths": { "https://index.docker.io/v1/": { "auth": "am9lam9lOmhlbGxv", "email": "user@example.com" } }, "credsStore": "crazy-secure-storage" }` - if err := ioutil.WriteFile(fn, []byte(js), 0600); err != nil { + if err := os.WriteFile(fn, []byte(js), 0600); err != nil { t.Fatal(err) } @@ -377,16 +349,14 @@ func TestJSONWithCredentialStore(t *testing.T) { } func TestJSONWithCredentialHelpers(t *testing.T) { - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() fn := filepath.Join(tmpHome, ConfigFileName) js := `{ "auths": { "https://index.docker.io/v1/": { "auth": "am9lam9lOmhlbGxv", "email": "user@example.com" } }, "credHelpers": { "images.io": "images-io", "containers.com": "crazy-secure-storage" } }` - if err := ioutil.WriteFile(fn, []byte(js), 0600); err != nil { + if err := os.WriteFile(fn, []byte(js), 0600); err != nil { t.Fatal(err) } @@ -416,16 +386,14 @@ func saveConfigAndValidateNewFormat(t *testing.T, config *configfile.ConfigFile, t.Helper() assert.NilError(t, config.Save()) - buf, err := ioutil.ReadFile(filepath.Join(configDir, ConfigFileName)) + buf, err := os.ReadFile(filepath.Join(configDir, ConfigFileName)) assert.NilError(t, err) assert.Check(t, is.Contains(string(buf), `"auths":`)) return string(buf) } func TestConfigDir(t *testing.T) { - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() if Dir() == tmpHome { t.Fatalf("Expected ConfigDir to be different than %s by default, but was the same", tmpHome) @@ -484,16 +452,14 @@ func TestJSONSaveWithNoFile(t *testing.T) { err = config.Save() assert.ErrorContains(t, err, "with empty filename") - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) + tmpHome := t.TempDir() fn := filepath.Join(tmpHome, ConfigFileName) f, _ := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) defer f.Close() assert.NilError(t, config.SaveToWriter(f)) - buf, err := ioutil.ReadFile(filepath.Join(tmpHome, ConfigFileName)) + buf, err := os.ReadFile(filepath.Join(tmpHome, ConfigFileName)) assert.NilError(t, err) expConfStr := `{ "auths": { @@ -515,16 +481,13 @@ func TestLegacyJSONSaveWithNoFile(t *testing.T) { err = config.Save() assert.ErrorContains(t, err, "with empty filename") - tmpHome, err := ioutil.TempDir("", "config-test") - assert.NilError(t, err) - defer os.RemoveAll(tmpHome) - + tmpHome := t.TempDir() fn := filepath.Join(tmpHome, ConfigFileName) f, _ := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) defer f.Close() assert.NilError(t, config.SaveToWriter(f)) - buf, err := ioutil.ReadFile(filepath.Join(tmpHome, ConfigFileName)) + buf, err := os.ReadFile(filepath.Join(tmpHome, ConfigFileName)) assert.NilError(t, err) expConfStr := `{ @@ -542,13 +505,12 @@ func TestLegacyJSONSaveWithNoFile(t *testing.T) { } func TestLoadDefaultConfigFile(t *testing.T) { - dir, cleanup := setupConfigDir(t) - defer cleanup() + dir := setupConfigDir(t) buffer := new(bytes.Buffer) filename := filepath.Join(dir, ConfigFileName) content := []byte(`{"PsFormat": "format"}`) - err := ioutil.WriteFile(filename, content, 0644) + err := os.WriteFile(filename, content, 0644) assert.NilError(t, err) configFile := LoadDefaultConfigFile(buffer) diff --git a/cli/config/configfile/file.go b/cli/config/configfile/file.go index d6f710817ab2..52f8e3875df3 100644 --- a/cli/config/configfile/file.go +++ b/cli/config/configfile/file.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -81,7 +80,7 @@ func New(fn string) *ConfigFile { // LegacyLoadFromReader reads the non-nested configuration data given and sets up the // auth config information with given directory and populates the receiver object func (configFile *ConfigFile) LegacyLoadFromReader(configData io.Reader) error { - b, err := ioutil.ReadAll(configData) + b, err := io.ReadAll(configData) if err != nil { return err } @@ -194,7 +193,7 @@ func (configFile *ConfigFile) Save() (retErr error) { if err := os.MkdirAll(dir, 0700); err != nil { return err } - temp, err := ioutil.TempFile(dir, filepath.Base(configFile.Filename)) + temp, err := os.CreateTemp(dir, filepath.Base(configFile.Filename)) if err != nil { return err } diff --git a/cli/config/configfile/file_test.go b/cli/config/configfile/file_test.go index fbab2930f776..68cdd8711079 100644 --- a/cli/config/configfile/file_test.go +++ b/cli/config/configfile/file_test.go @@ -3,7 +3,6 @@ package configfile import ( "bytes" "encoding/json" - "io/ioutil" "os" "testing" @@ -479,7 +478,7 @@ func TestSave(t *testing.T) { defer os.Remove("test-save") err := configFile.Save() assert.NilError(t, err) - cfg, err := ioutil.ReadFile("test-save") + cfg, err := os.ReadFile("test-save") assert.NilError(t, err) assert.Equal(t, string(cfg), `{ "auths": {} @@ -494,7 +493,7 @@ func TestSaveCustomHTTPHeaders(t *testing.T) { configFile.HTTPHeaders["user-agent"] = "user-agent 2" err := configFile.Save() assert.NilError(t, err) - cfg, err := ioutil.ReadFile(t.Name()) + cfg, err := os.ReadFile(t.Name()) assert.NilError(t, err) assert.Equal(t, string(cfg), `{ "auths": {}, @@ -522,11 +521,11 @@ func TestSaveWithSymlink(t *testing.T) { assert.NilError(t, err) assert.Assert(t, fi.Mode()&os.ModeSymlink != 0, "expected %s to be a symlink", symLink) - cfg, err := ioutil.ReadFile(symLink) + cfg, err := os.ReadFile(symLink) assert.NilError(t, err) assert.Check(t, is.Equal(string(cfg), "{\n \"auths\": {}\n}")) - cfg, err = ioutil.ReadFile(realFile) + cfg, err = os.ReadFile(realFile) assert.NilError(t, err) assert.Check(t, is.Equal(string(cfg), "{\n \"auths\": {}\n}")) } @@ -545,7 +544,7 @@ func TestPluginConfig(t *testing.T) { assert.NilError(t, err) // Read it back and check it has the expected content - cfg, err := ioutil.ReadFile("test-plugin") + cfg, err := os.ReadFile("test-plugin") assert.NilError(t, err) golden.Assert(t, string(cfg), "plugin-config.golden") @@ -556,7 +555,7 @@ func TestPluginConfig(t *testing.T) { assert.NilError(t, configFile.LoadFromReader(bytes.NewReader(cfg))) err = configFile.Save() assert.NilError(t, err) - cfg, err = ioutil.ReadFile("test-plugin2") + cfg, err = os.ReadFile("test-plugin2") assert.NilError(t, err) golden.Assert(t, string(cfg), "plugin-config.golden") @@ -591,7 +590,7 @@ func TestPluginConfig(t *testing.T) { assert.NilError(t, err) // Read it back and check it has the expected content again - cfg, err = ioutil.ReadFile("test-plugin2") + cfg, err = os.ReadFile("test-plugin2") assert.NilError(t, err) golden.Assert(t, string(cfg), "plugin-config-2.golden") } diff --git a/cli/config/credentials/native_store_test.go b/cli/config/credentials/native_store_test.go index 7c54a967beba..2c6f230f681d 100644 --- a/cli/config/credentials/native_store_test.go +++ b/cli/config/credentials/native_store_test.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "strings" "testing" @@ -36,7 +35,7 @@ type mockCommand struct { // Output returns responses from the remote credentials helper. // It mocks those responses based in the input in the mock. func (m *mockCommand) Output() ([]byte, error) { - in, err := ioutil.ReadAll(m.input) + in, err := io.ReadAll(m.input) if err != nil { return nil, err } From cec1b29b81404bc0e89fc527d99af3032b27188c Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 14:37:07 +0100 Subject: [PATCH 21/41] cli/context: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit cca80cdddd58d34304fc0c92fde43d9a833283e2) Signed-off-by: Cory Snider --- cli/context/kubernetes/endpoint_test.go | 24 +++---------- cli/context/kubernetes/save.go | 4 +-- cli/context/store/io_utils_test.go | 8 ++--- cli/context/store/metadata_test.go | 44 ++++++++--------------- cli/context/store/metadatastore.go | 7 ++-- cli/context/store/store.go | 11 +++--- cli/context/store/store_test.go | 46 +++++-------------------- cli/context/store/tlsstore.go | 9 +++-- cli/context/store/tlsstore_test.go | 16 +++------ cli/context/tlsdata.go | 8 ++--- 10 files changed, 54 insertions(+), 123 deletions(-) diff --git a/cli/context/kubernetes/endpoint_test.go b/cli/context/kubernetes/endpoint_test.go index 89eeb9d61c5d..3eb01cbf57e5 100644 --- a/cli/context/kubernetes/endpoint_test.go +++ b/cli/context/kubernetes/endpoint_test.go @@ -1,7 +1,6 @@ package kubernetes import ( - "io/ioutil" "os" "testing" @@ -41,17 +40,13 @@ var testStoreCfg = store.NewConfig( ) func TestSaveLoadContexts(t *testing.T) { - storeDir, err := ioutil.TempDir("", "test-load-save-k8-context") - assert.NilError(t, err) - defer os.RemoveAll(storeDir) - store := store.New(storeDir, testStoreCfg) + store := store.New(t.TempDir(), testStoreCfg) assert.NilError(t, save(store, testEndpoint("https://test", "test", nil, nil, nil, false), "raw-notls")) assert.NilError(t, save(store, testEndpoint("https://test", "test", nil, nil, nil, true), "raw-notls-skip")) assert.NilError(t, save(store, testEndpoint("https://test", "test", []byte("ca"), []byte("cert"), []byte("key"), true), "raw-tls")) - kcFile, err := ioutil.TempFile(os.TempDir(), "test-load-save-k8-context") + kcFile, err := os.CreateTemp(t.TempDir(), "test-load-save-k8-context") assert.NilError(t, err) - defer os.Remove(kcFile.Name()) defer kcFile.Close() cfg := clientcmdapi.NewConfig() cfg.AuthInfos["user"] = clientcmdapi.NewAuthInfo() @@ -146,10 +141,7 @@ func save(s store.Writer, ep Endpoint, name string) error { } func TestSaveLoadGKEConfig(t *testing.T) { - storeDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(storeDir) - store := store.New(storeDir, testStoreCfg) + store := store.New(t.TempDir(), testStoreCfg) cfg, err := clientcmd.LoadFromFile("testdata/gke-kubeconfig") assert.NilError(t, err) clientCfg := clientcmd.NewDefaultClientConfig(*cfg, &clientcmd.ConfigOverrides{}) @@ -171,10 +163,7 @@ func TestSaveLoadGKEConfig(t *testing.T) { } func TestSaveLoadEKSConfig(t *testing.T) { - storeDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(storeDir) - store := store.New(storeDir, testStoreCfg) + store := store.New(t.TempDir(), testStoreCfg) cfg, err := clientcmd.LoadFromFile("testdata/eks-kubeconfig") assert.NilError(t, err) clientCfg := clientcmd.NewDefaultClientConfig(*cfg, &clientcmd.ConfigOverrides{}) @@ -196,10 +185,7 @@ func TestSaveLoadEKSConfig(t *testing.T) { } func TestSaveLoadK3SConfig(t *testing.T) { - storeDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(storeDir) - store := store.New(storeDir, testStoreCfg) + store := store.New(t.TempDir(), testStoreCfg) cfg, err := clientcmd.LoadFromFile("testdata/k3s-kubeconfig") assert.NilError(t, err) clientCfg := clientcmd.NewDefaultClientConfig(*cfg, &clientcmd.ConfigOverrides{}) diff --git a/cli/context/kubernetes/save.go b/cli/context/kubernetes/save.go index 032a01d46ab9..0b2639c44964 100644 --- a/cli/context/kubernetes/save.go +++ b/cli/context/kubernetes/save.go @@ -1,7 +1,7 @@ package kubernetes import ( - "io/ioutil" + "os" "github.com/docker/cli/cli/context" "k8s.io/client-go/tools/clientcmd" @@ -63,7 +63,7 @@ func FromKubeConfig(kubeconfig, kubeContext, namespaceOverride string) (Endpoint func readFileOrDefault(path string, defaultValue []byte) ([]byte, error) { if path != "" { - return ioutil.ReadFile(path) + return os.ReadFile(path) } return defaultValue, nil } diff --git a/cli/context/store/io_utils_test.go b/cli/context/store/io_utils_test.go index e7b6ecf9750f..e917f1191491 100644 --- a/cli/context/store/io_utils_test.go +++ b/cli/context/store/io_utils_test.go @@ -1,7 +1,7 @@ package store import ( - "io/ioutil" + "io" "strings" "testing" @@ -11,14 +11,14 @@ import ( func TestLimitReaderReadAll(t *testing.T) { r := strings.NewReader("Reader") - _, err := ioutil.ReadAll(r) + _, err := io.ReadAll(r) assert.NilError(t, err) r = strings.NewReader("Test") - _, err = ioutil.ReadAll(&LimitedReader{R: r, N: 4}) + _, err = io.ReadAll(&LimitedReader{R: r, N: 4}) assert.NilError(t, err) r = strings.NewReader("Test") - _, err = ioutil.ReadAll(&LimitedReader{R: r, N: 2}) + _, err = io.ReadAll(&LimitedReader{R: r, N: 2}) assert.Error(t, err, "read exceeds the defined limit") } diff --git a/cli/context/store/metadata_test.go b/cli/context/store/metadata_test.go index 3d9a5be5f119..9de17408b058 100644 --- a/cli/context/store/metadata_test.go +++ b/cli/context/store/metadata_test.go @@ -1,7 +1,6 @@ package store import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -21,18 +20,13 @@ func testMetadata(name string) Metadata { } func TestMetadataGetNotExisting(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) - testee := metadataStore{root: testDir, config: testCfg} - _, err = testee.get("noexist") + testee := metadataStore{root: t.TempDir(), config: testCfg} + _, err := testee.get("noexist") assert.Assert(t, IsErrContextDoesNotExist(err)) } func TestMetadataCreateGetRemove(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) + testDir := t.TempDir() testee := metadataStore{root: testDir, config: testCfg} expected2 := Metadata{ Endpoints: map[string]interface{}{ @@ -43,7 +37,7 @@ func TestMetadataCreateGetRemove(t *testing.T) { Name: "test-context", } testMeta := testMetadata("test-context") - err = testee.createOrUpdate(testMeta) + err := testee.createOrUpdate(testMeta) assert.NilError(t, err) // create a new instance to check it does not depend on some sort of state testee = metadataStore{root: testDir, config: testCfg} @@ -66,22 +60,17 @@ func TestMetadataCreateGetRemove(t *testing.T) { } func TestMetadataRespectJsonAnnotation(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) + testDir := t.TempDir() testee := metadataStore{root: testDir, config: testCfg} assert.NilError(t, testee.createOrUpdate(testMetadata("test"))) - bytes, err := ioutil.ReadFile(filepath.Join(testDir, string(contextdirOf("test")), "meta.json")) + bytes, err := os.ReadFile(filepath.Join(testDir, string(contextdirOf("test")), "meta.json")) assert.NilError(t, err) assert.Assert(t, cmp.Contains(string(bytes), "a_very_recognizable_field_name")) assert.Assert(t, cmp.Contains(string(bytes), "another_very_recognizable_field_name")) } func TestMetadataList(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) - testee := metadataStore{root: testDir, config: testCfg} + testee := metadataStore{root: t.TempDir(), config: testCfg} wholeData := []Metadata{ testMetadata("context1"), testMetadata("context2"), @@ -89,8 +78,7 @@ func TestMetadataList(t *testing.T) { } for _, s := range wholeData { - err = testee.createOrUpdate(s) - assert.NilError(t, err) + assert.NilError(t, testee.createOrUpdate(s)) } data, err := testee.list() @@ -99,10 +87,7 @@ func TestMetadataList(t *testing.T) { } func TestEmptyConfig(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) - testee := metadataStore{root: testDir} + testee := metadataStore{root: t.TempDir()} wholeData := []Metadata{ testMetadata("context1"), testMetadata("context2"), @@ -110,8 +95,7 @@ func TestEmptyConfig(t *testing.T) { } for _, s := range wholeData { - err = testee.createOrUpdate(s) - assert.NilError(t, err) + assert.NilError(t, testee.createOrUpdate(s)) } data, err := testee.list() @@ -127,10 +111,10 @@ type embeddedStruct struct { } func TestWithEmbedding(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) - testee := metadataStore{root: testDir, config: NewConfig(func() interface{} { return &contextWithEmbedding{} })} + testee := metadataStore{ + root: t.TempDir(), + config: NewConfig(func() interface{} { return &contextWithEmbedding{} }), + } testCtxMeta := contextWithEmbedding{ embeddedStruct: embeddedStruct{ Val: "Hello", diff --git a/cli/context/store/metadatastore.go b/cli/context/store/metadatastore.go index 0e9bc8889cbd..151852fa1bf0 100644 --- a/cli/context/store/metadatastore.go +++ b/cli/context/store/metadatastore.go @@ -3,7 +3,6 @@ package store import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -35,7 +34,7 @@ func (s *metadataStore) createOrUpdate(meta Metadata) error { if err != nil { return err } - return ioutil.WriteFile(filepath.Join(contextDir, metaFile), bytes, 0644) + return os.WriteFile(filepath.Join(contextDir, metaFile), bytes, 0644) } func parseTypedOrMap(payload []byte, getter TypeGetter) (interface{}, error) { @@ -58,7 +57,7 @@ func parseTypedOrMap(payload []byte, getter TypeGetter) (interface{}, error) { func (s *metadataStore) get(id contextdir) (Metadata, error) { contextDir := s.contextDir(id) - bytes, err := ioutil.ReadFile(filepath.Join(contextDir, metaFile)) + bytes, err := os.ReadFile(filepath.Join(contextDir, metaFile)) if err != nil { return Metadata{}, convertContextDoesNotExist(err) } @@ -117,7 +116,7 @@ func isContextDir(path string) bool { } func listRecursivelyMetadataDirs(root string) ([]string, error) { - fis, err := ioutil.ReadDir(root) + fis, err := os.ReadDir(root) if err != nil { return nil, err } diff --git a/cli/context/store/store.go b/cli/context/store/store.go index 71220e9ac0f6..ff7049e82766 100644 --- a/cli/context/store/store.go +++ b/cli/context/store/store.go @@ -9,7 +9,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "path" "path/filepath" @@ -349,7 +348,7 @@ func importTar(name string, s Writer, reader io.Reader) error { return errors.Wrap(err, hdr.Name) } if hdr.Name == metaFile { - data, err := ioutil.ReadAll(tr) + data, err := io.ReadAll(tr) if err != nil { return err } @@ -362,7 +361,7 @@ func importTar(name string, s Writer, reader io.Reader) error { } importedMetaFile = true } else if strings.HasPrefix(hdr.Name, "tls/") { - data, err := ioutil.ReadAll(tr) + data, err := io.ReadAll(tr) if err != nil { return err } @@ -378,7 +377,7 @@ func importTar(name string, s Writer, reader io.Reader) error { } func importZip(name string, s Writer, reader io.Reader) error { - body, err := ioutil.ReadAll(&LimitedReader{R: reader, N: maxAllowedFileSizeToImport}) + body, err := io.ReadAll(&LimitedReader{R: reader, N: maxAllowedFileSizeToImport}) if err != nil { return err } @@ -406,7 +405,7 @@ func importZip(name string, s Writer, reader io.Reader) error { return err } - data, err := ioutil.ReadAll(&LimitedReader{R: f, N: maxAllowedFileSizeToImport}) + data, err := io.ReadAll(&LimitedReader{R: f, N: maxAllowedFileSizeToImport}) defer f.Close() if err != nil { return err @@ -424,7 +423,7 @@ func importZip(name string, s Writer, reader io.Reader) error { if err != nil { return err } - data, err := ioutil.ReadAll(f) + data, err := io.ReadAll(f) defer f.Close() if err != nil { return err diff --git a/cli/context/store/store_test.go b/cli/context/store/store_test.go index 4b412652de01..3c9ddd6b7a06 100644 --- a/cli/context/store/store_test.go +++ b/cli/context/store/store_test.go @@ -8,7 +8,6 @@ import ( "crypto/rand" "encoding/json" "io" - "io/ioutil" "os" "path" "testing" @@ -30,11 +29,8 @@ var testCfg = NewConfig(func() interface{} { return &context{} }, ) func TestExportImport(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) - s := New(testDir, testCfg) - err = s.CreateOrUpdate( + s := New(t.TempDir(), testCfg) + err := s.CreateOrUpdate( Metadata{ Endpoints: map[string]interface{}{ "ep1": endpoint{Foo: "bar"}, @@ -87,11 +83,8 @@ func TestExportImport(t *testing.T) { } func TestRemove(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) - s := New(testDir, testCfg) - err = s.CreateOrUpdate( + s := New(t.TempDir(), testCfg) + err := s.CreateOrUpdate( Metadata{ Endpoints: map[string]interface{}{ "ep1": endpoint{Foo: "bar"}, @@ -114,30 +107,18 @@ func TestRemove(t *testing.T) { } func TestListEmptyStore(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) - store := New(testDir, testCfg) - result, err := store.List() + result, err := New(t.TempDir(), testCfg).List() assert.NilError(t, err) assert.Check(t, len(result) == 0) } func TestErrHasCorrectContext(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) - store := New(testDir, testCfg) - _, err = store.GetMetadata("no-exists") + _, err := New(t.TempDir(), testCfg).GetMetadata("no-exists") assert.ErrorContains(t, err, "no-exists") assert.Check(t, IsErrContextDoesNotExist(err)) } func TestDetectImportContentType(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) - buf := new(bytes.Buffer) r := bufio.NewReader(buf) ct, err := getImportContentType(r) @@ -146,10 +127,7 @@ func TestDetectImportContentType(t *testing.T) { } func TestImportTarInvalid(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) - + testDir := t.TempDir() tf := path.Join(testDir, "test.context") f, err := os.Create(tf) @@ -179,10 +157,7 @@ func TestImportTarInvalid(t *testing.T) { } func TestImportZip(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) - + testDir := t.TempDir() zf := path.Join(testDir, "test.zip") f, err := os.Create(zf) @@ -230,10 +205,7 @@ func TestImportZip(t *testing.T) { } func TestImportZipInvalid(t *testing.T) { - testDir, err := ioutil.TempDir("", t.Name()) - assert.NilError(t, err) - defer os.RemoveAll(testDir) - + testDir := t.TempDir() zf := path.Join(testDir, "test.zip") f, err := os.Create(zf) diff --git a/cli/context/store/tlsstore.go b/cli/context/store/tlsstore.go index 1188ce2df798..8267e879644f 100644 --- a/cli/context/store/tlsstore.go +++ b/cli/context/store/tlsstore.go @@ -1,7 +1,6 @@ package store import ( - "io/ioutil" "os" "path/filepath" ) @@ -33,11 +32,11 @@ func (s *tlsStore) createOrUpdate(contextID contextdir, endpointName, filename s if err := os.MkdirAll(epdir, 0700); err != nil { return err } - return ioutil.WriteFile(s.filePath(contextID, endpointName, filename), data, 0600) + return os.WriteFile(s.filePath(contextID, endpointName, filename), data, 0600) } func (s *tlsStore) getData(contextID contextdir, endpointName, filename string) ([]byte, error) { - data, err := ioutil.ReadFile(s.filePath(contextID, endpointName, filename)) + data, err := os.ReadFile(s.filePath(contextID, endpointName, filename)) if err != nil { return nil, convertTLSDataDoesNotExist(endpointName, filename, err) } @@ -61,7 +60,7 @@ func (s *tlsStore) removeAllContextData(contextID contextdir) error { } func (s *tlsStore) listContextData(contextID contextdir) (map[string]EndpointFiles, error) { - epFSs, err := ioutil.ReadDir(s.contextDir(contextID)) + epFSs, err := os.ReadDir(s.contextDir(contextID)) if err != nil { if os.IsNotExist(err) { return map[string]EndpointFiles{}, nil @@ -72,7 +71,7 @@ func (s *tlsStore) listContextData(contextID contextdir) (map[string]EndpointFil for _, epFS := range epFSs { if epFS.IsDir() { epDir := s.endpointDir(contextID, epFS.Name()) - fss, err := ioutil.ReadDir(epDir) + fss, err := os.ReadDir(epDir) if err != nil { return nil, err } diff --git a/cli/context/store/tlsstore_test.go b/cli/context/store/tlsstore_test.go index a8a735dcf7b1..5af9acda3b2b 100644 --- a/cli/context/store/tlsstore_test.go +++ b/cli/context/store/tlsstore_test.go @@ -1,19 +1,14 @@ package store import ( - "io/ioutil" - "os" "testing" "gotest.tools/v3/assert" ) func TestTlsCreateUpdateGetRemove(t *testing.T) { - testDir, err := ioutil.TempDir("", "TestTlsCreateUpdateGetRemove") - assert.NilError(t, err) - defer os.RemoveAll(testDir) - testee := tlsStore{root: testDir} - _, err = testee.getData("test-ctx", "test-ep", "test-data") + testee := tlsStore{root: t.TempDir()} + _, err := testee.getData("test-ctx", "test-ep", "test-data") assert.Equal(t, true, IsErrTLSDataDoesNotExist(err)) err = testee.createOrUpdate("test-ctx", "test-ep", "test-data", []byte("data")) @@ -37,10 +32,7 @@ func TestTlsCreateUpdateGetRemove(t *testing.T) { } func TestTlsListAndBatchRemove(t *testing.T) { - testDir, err := ioutil.TempDir("", "TestTlsListAndBatchRemove") - assert.NilError(t, err) - defer os.RemoveAll(testDir) - testee := tlsStore{root: testDir} + testee := tlsStore{root: t.TempDir()} all := map[string]EndpointFiles{ "ep1": {"f1", "f2", "f3"}, @@ -55,7 +47,7 @@ func TestTlsListAndBatchRemove(t *testing.T) { for name, files := range all { for _, file := range files { - err = testee.createOrUpdate("test-ctx", name, file, []byte("data")) + err := testee.createOrUpdate("test-ctx", name, file, []byte("data")) assert.NilError(t, err) } } diff --git a/cli/context/tlsdata.go b/cli/context/tlsdata.go index 124d98ba3d90..f8459fd40648 100644 --- a/cli/context/tlsdata.go +++ b/cli/context/tlsdata.go @@ -1,7 +1,7 @@ package context import ( - "io/ioutil" + "os" "github.com/docker/cli/cli/context/store" "github.com/pkg/errors" @@ -77,17 +77,17 @@ func TLSDataFromFiles(caPath, certPath, keyPath string) (*TLSData, error) { err error ) if caPath != "" { - if ca, err = ioutil.ReadFile(caPath); err != nil { + if ca, err = os.ReadFile(caPath); err != nil { return nil, err } } if certPath != "" { - if cert, err = ioutil.ReadFile(certPath); err != nil { + if cert, err = os.ReadFile(certPath); err != nil { return nil, err } } if keyPath != "" { - if key, err = ioutil.ReadFile(keyPath); err != nil { + if key, err = os.ReadFile(keyPath); err != nil { return nil, err } } From f8211f7f80d9210e4e2f88c0531d8ec3a07dd73d Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 15:29:30 +0100 Subject: [PATCH 22/41] cli/manifest: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 58cf16da45082f0b013c79bf055a3d6b3c99eab9) Signed-off-by: Cory Snider --- cli/manifest/store/store.go | 9 ++++--- cli/manifest/store/store_test.go | 41 ++++++++++---------------------- 2 files changed, 17 insertions(+), 33 deletions(-) diff --git a/cli/manifest/store/store.go b/cli/manifest/store/store.go index 1fd0207b3462..dd0c86e5262d 100644 --- a/cli/manifest/store/store.go +++ b/cli/manifest/store/store.go @@ -3,7 +3,6 @@ package store import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -47,7 +46,7 @@ func (s *fsStore) Get(listRef reference.Reference, manifest reference.Reference) } func (s *fsStore) getFromFilename(ref reference.Reference, filename string) (types.ImageManifest, error) { - bytes, err := ioutil.ReadFile(filename) + bytes, err := os.ReadFile(filename) switch { case os.IsNotExist(err): return types.ImageManifest{}, newNotFoundError(ref.String()) @@ -112,7 +111,7 @@ func (s *fsStore) GetList(listRef reference.Reference) ([]types.ImageManifest, e // listManifests stored in a transaction func (s *fsStore) listManifests(transaction string) ([]string, error) { transactionDir := filepath.Join(s.root, makeFilesafeName(transaction)) - fileInfos, err := ioutil.ReadDir(transactionDir) + fileInfos, err := os.ReadDir(transactionDir) switch { case os.IsNotExist(err): return nil, nil @@ -120,7 +119,7 @@ func (s *fsStore) listManifests(transaction string) ([]string, error) { return nil, err } - filenames := []string{} + filenames := make([]string, 0, len(fileInfos)) for _, info := range fileInfos { filenames = append(filenames, info.Name()) } @@ -137,7 +136,7 @@ func (s *fsStore) Save(listRef reference.Reference, manifest reference.Reference if err != nil { return err } - return ioutil.WriteFile(filename, bytes, 0644) + return os.WriteFile(filename, bytes, 0644) } func (s *fsStore) createManifestListDirectory(transaction string) error { diff --git a/cli/manifest/store/store_test.go b/cli/manifest/store/store_test.go index a89f3980ba8c..5fc05a6031e7 100644 --- a/cli/manifest/store/store_test.go +++ b/cli/manifest/store/store_test.go @@ -1,7 +1,6 @@ package store import ( - "io/ioutil" "os" "testing" @@ -29,41 +28,31 @@ func ref(name string) fakeRef { } func sref(t *testing.T, name string) *types.SerializableNamed { + t.Helper() named, err := reference.ParseNamed("example.com/" + name) assert.NilError(t, err) return &types.SerializableNamed{Named: named} } -func newTestStore(t *testing.T) (Store, func()) { - tmpdir, err := ioutil.TempDir("", "manifest-store-test") - assert.NilError(t, err) - - return NewStore(tmpdir), func() { os.RemoveAll(tmpdir) } -} - -func getFiles(t *testing.T, store Store) []os.FileInfo { - infos, err := ioutil.ReadDir(store.(*fsStore).root) - assert.NilError(t, err) - return infos -} - func TestStoreRemove(t *testing.T) { - store, cleanup := newTestStore(t) - defer cleanup() - + tmpDir := t.TempDir() + store := NewStore(tmpDir) listRef := ref("list") data := types.ImageManifest{Ref: sref(t, "abcdef")} assert.NilError(t, store.Save(listRef, ref("manifest"), data)) - assert.Assert(t, is.Len(getFiles(t, store), 1)) + + files, err := os.ReadDir(tmpDir) + assert.NilError(t, err) + assert.Assert(t, is.Len(files, 1)) assert.Check(t, store.Remove(listRef)) - assert.Check(t, is.Len(getFiles(t, store), 0)) + files, err = os.ReadDir(tmpDir) + assert.NilError(t, err) + assert.Check(t, is.Len(files, 0)) } func TestStoreSaveAndGet(t *testing.T) { - store, cleanup := newTestStore(t) - defer cleanup() - + store := NewStore(t.TempDir()) listRef := ref("list") data := types.ImageManifest{Ref: sref(t, "abcdef")} err := store.Save(listRef, ref("exists"), data) @@ -112,9 +101,7 @@ var cmpReferenceNamed = cmp.Transformer("namedref", func(r reference.Named) stri }) func TestStoreGetList(t *testing.T) { - store, cleanup := newTestStore(t) - defer cleanup() - + store := NewStore(t.TempDir()) listRef := ref("list") first := types.ImageManifest{Ref: sref(t, "first")} assert.NilError(t, store.Save(listRef, ref("first"), first)) @@ -127,9 +114,7 @@ func TestStoreGetList(t *testing.T) { } func TestStoreGetListDoesNotExist(t *testing.T) { - store, cleanup := newTestStore(t) - defer cleanup() - + store := NewStore(t.TempDir()) listRef := ref("list") _, err := store.GetList(listRef) assert.Error(t, err, "No such manifest: list") From dc4e6835b7abd2a94ca83e52755767658926ad2b Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 15:30:02 +0100 Subject: [PATCH 23/41] cli/trust: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 1e54bca833c093d9ae8f12e27770b197fcb0cece) Signed-off-by: Cory Snider --- cli/trust/trust_test.go | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/cli/trust/trust_test.go b/cli/trust/trust_test.go index c49f41008f89..044e2c208846 100644 --- a/cli/trust/trust_test.go +++ b/cli/trust/trust_test.go @@ -1,8 +1,6 @@ package trust import ( - "io/ioutil" - "os" "testing" "github.com/docker/distribution/reference" @@ -49,11 +47,7 @@ func TestGetDigest(t *testing.T) { } func TestGetSignableRolesError(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NilError(t, err) - defer os.RemoveAll(tmpDir) - - notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{}) + notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{}) assert.NilError(t, err) target := client.Target{} _, err = GetSignableRoles(notaryRepo, &target) From a0f0a4fe7a65342bb7ee8d3947e57b1573a6d769 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 15:30:38 +0100 Subject: [PATCH 24/41] cli: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 86db51e86e5a214b895453a8f99fc9bcea11e45f) Signed-off-by: Cory Snider --- cli/required_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cli/required_test.go b/cli/required_test.go index d83c2cb4d965..41d1ac0236ca 100644 --- a/cli/required_test.go +++ b/cli/required_test.go @@ -2,7 +2,7 @@ package cli import ( "errors" - "io/ioutil" + "io" "testing" "github.com/spf13/cobra" @@ -119,7 +119,7 @@ func runTestCases(t *testing.T, testCases []testCase) { for _, tc := range testCases { cmd := newDummyCommand(tc.validateFunc) cmd.SetArgs(tc.args) - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) err := cmd.Execute() assert.ErrorContains(t, err, tc.expectedError) From f471347d885611a1918b03d9a2ca6c6ae6349063 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 15:31:22 +0100 Subject: [PATCH 25/41] cmd/docker: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 0e3197ebd4c378762205c39121e9b2b8ff4dbeae) Signed-off-by: Cory Snider --- cmd/docker/docker_test.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cmd/docker/docker_test.go b/cmd/docker/docker_test.go index 0acca1b6b138..fc1c5829bd85 100644 --- a/cmd/docker/docker_test.go +++ b/cmd/docker/docker_test.go @@ -3,7 +3,6 @@ package main import ( "bytes" "io" - "io/ioutil" "os" "testing" @@ -30,7 +29,7 @@ func TestClientDebugEnabled(t *testing.T) { assert.Check(t, is.Equal(logrus.DebugLevel, logrus.GetLevel())) } -var discard = ioutil.NopCloser(bytes.NewBuffer(nil)) +var discard = io.NopCloser(bytes.NewBuffer(nil)) func runCliCommand(t *testing.T, r io.ReadCloser, w io.Writer, args ...string) error { t.Helper() @@ -38,7 +37,7 @@ func runCliCommand(t *testing.T, r io.ReadCloser, w io.Writer, args ...string) e r = discard } if w == nil { - w = ioutil.Discard + w = io.Discard } cli, err := command.NewDockerCli(command.WithInputStream(r), command.WithCombinedStreams(w)) assert.NilError(t, err) From 58d486bac79a2aa775d25a4d3443536086ec0141 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 15:31:47 +0100 Subject: [PATCH 26/41] docs/yaml: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 39ace680617ae003ba4d7894e086aa70dded3f1a) Signed-off-by: Cory Snider --- docs/yaml/generate.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/yaml/generate.go b/docs/yaml/generate.go index ff451c192042..f3d8d42dcb63 100644 --- a/docs/yaml/generate.go +++ b/docs/yaml/generate.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "io/ioutil" "log" "os" "path/filepath" @@ -72,7 +71,7 @@ func loadLongDescription(parentCmd *cobra.Command, path string) error { } mdFile := strings.ReplaceAll(name, " ", "_") + ".md" fullPath := filepath.Join(path, mdFile) - content, err := ioutil.ReadFile(fullPath) + content, err := os.ReadFile(fullPath) if os.IsNotExist(err) { log.Printf("WARN: %s does not exist, skipping\n", mdFile) continue From ac72d64c304c7c4f134de8d1f328cbcc90feaa1c Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 15:32:16 +0100 Subject: [PATCH 27/41] e2e: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit e89af84ffc0e7e6f96cc205d230533e9c3ed3941) Signed-off-by: Cory Snider --- e2e/context/context_test.go | 13 +++---------- e2e/image/build_test.go | 4 ++-- 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/e2e/context/context_test.go b/e2e/context/context_test.go index 6212b98dea47..57531172b771 100644 --- a/e2e/context/context_test.go +++ b/e2e/context/context_test.go @@ -1,7 +1,6 @@ package context import ( - "io/ioutil" "os" "testing" @@ -24,10 +23,7 @@ func TestContextList(t *testing.T) { } func TestContextImportNoTLS(t *testing.T) { - d, _ := ioutil.TempDir("", "") - defer func() { - os.RemoveAll(d) - }() + d := t.TempDir() cmd := icmd.Command("docker", "context", "import", "remote", "./testdata/test-dockerconfig.tar") cmd.Env = append(cmd.Env, "DOCKER_CONFIG="+d, @@ -44,10 +40,7 @@ func TestContextImportNoTLS(t *testing.T) { } func TestContextImportTLS(t *testing.T) { - d, _ := ioutil.TempDir("", "") - defer func() { - os.RemoveAll(d) - }() + d := t.TempDir() cmd := icmd.Command("docker", "context", "import", "test", "./testdata/test-dockerconfig-tls.tar") cmd.Env = append(cmd.Env, "DOCKER_CONFIG="+d, @@ -61,7 +54,7 @@ func TestContextImportTLS(t *testing.T) { result := icmd.RunCmd(cmd).Assert(t, icmd.Success) golden.Assert(t, result.Stdout(), "context-ls-tls.golden") - b, err := ioutil.ReadFile(d + "/contexts/tls/9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08/kubernetes/key.pem") + b, err := os.ReadFile(d + "/contexts/tls/9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08/kubernetes/key.pem") assert.NilError(t, err) assert.Equal(t, string(b), `-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEArQk77K5sgrQYY6HiQ1y7AC+67HrRB36oEvR+Fq60RsFcc3cZ diff --git a/e2e/image/build_test.go b/e2e/image/build_test.go index c92c0b0d8959..932de63235f3 100644 --- a/e2e/image/build_test.go +++ b/e2e/image/build_test.go @@ -2,7 +2,7 @@ package image import ( "fmt" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -129,7 +129,7 @@ func TestBuildIidFileSquash(t *testing.T) { withWorkingDir(buildDir), ) result.Assert(t, icmd.Success) - id, err := ioutil.ReadFile(iidfile) + id, err := os.ReadFile(iidfile) assert.NilError(t, err) result = icmd.RunCommand("docker", "image", "inspect", "-f", "{{.Id}}", imageTag) result.Assert(t, icmd.Success) From 8793cdd2c7d26e79429f66437f18c94ae8e0e20f Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 15:32:54 +0100 Subject: [PATCH 28/41] internal/test: remove deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 7491c5ac6584bcbd2427ee0e8ef4c4c4d0cac1d9) Signed-off-by: Cory Snider --- internal/test/cli.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/internal/test/cli.go b/internal/test/cli.go index f3844142f793..f37f93e5b316 100644 --- a/internal/test/cli.go +++ b/internal/test/cli.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "strings" "github.com/docker/cli/cli/command" @@ -52,7 +51,7 @@ func NewFakeCli(client client.APIClient, opts ...func(*FakeCli)) *FakeCli { out: streams.NewOut(outBuffer), outBuffer: outBuffer, err: errBuffer, - in: streams.NewIn(ioutil.NopCloser(strings.NewReader(""))), + in: streams.NewIn(io.NopCloser(strings.NewReader(""))), // Use an empty string for filename so that tests don't create configfiles // Set cli.ConfigFile().Filename to a tempfile to support Save. configfile: configfile.New(""), From 3f681a2f64ca9c6f35cc83f7d95f933b50ad9be4 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 15:33:19 +0100 Subject: [PATCH 29/41] man: remove deprecated io/ioutil and use t.TempDir() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 85754c9ab5c215204e94f3ec7157c8a71e6c48d8) Signed-off-by: Cory Snider --- man/generate.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/man/generate.go b/man/generate.go index d21a6467aa9f..ac58c382faa6 100644 --- a/man/generate.go +++ b/man/generate.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "io/ioutil" "log" "os" "path/filepath" @@ -74,7 +73,7 @@ func loadLongDescription(cmd *cobra.Command, path string) error { continue } - content, err := ioutil.ReadFile(fullpath) + content, err := os.ReadFile(fullpath) if err != nil { return err } @@ -85,7 +84,7 @@ func loadLongDescription(cmd *cobra.Command, path string) error { continue } - content, err = ioutil.ReadFile(fullpath) + content, err = os.ReadFile(fullpath) if err != nil { return err } From d228386fa04ecea086b69578dddd0ce610ed5d56 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 15:35:13 +0100 Subject: [PATCH 30/41] opts: remove deprecated io/ioutil and use t.Cleanup() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 38e62571fbb85acbd9097296c9b86f824f2235eb) Signed-off-by: Cory Snider --- opts/envfile_test.go | 41 ++++++++++++++++++----------------------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/opts/envfile_test.go b/opts/envfile_test.go index f875707a5eb0..de84410a05de 100644 --- a/opts/envfile_test.go +++ b/opts/envfile_test.go @@ -2,22 +2,27 @@ package opts import ( "bufio" - "fmt" - "io/ioutil" "os" "reflect" "strings" "testing" ) -func tmpFileWithContent(content string, t *testing.T) string { - tmpFile, err := ioutil.TempFile("", "envfile-test") +func tmpFileWithContent(t *testing.T, content string) string { + t.Helper() + tmpFile, err := os.CreateTemp("", "envfile-test") if err != nil { t.Fatal(err) } defer tmpFile.Close() - tmpFile.WriteString(content) + _, err = tmpFile.WriteString(content) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = os.Remove(tmpFile.Name()) + }) return tmpFile.Name() } @@ -37,8 +42,7 @@ and_underscore=working too // from lines, which becomes annoying since that's the // exact thing we need to test. content += "\n \t " - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) + tmpFile := tmpFileWithContent(t, content) lines, err := ParseEnvFile(tmpFile) if err != nil { @@ -60,8 +64,7 @@ and_underscore=working too // Test ParseEnvFile for an empty file func TestParseEnvFileEmptyFile(t *testing.T) { - tmpFile := tmpFileWithContent("", t) - defer os.Remove(tmpFile) + tmpFile := tmpFileWithContent(t, "") lines, err := ParseEnvFile(tmpFile) if err != nil { @@ -89,9 +92,7 @@ func TestParseEnvFileBadlyFormattedFile(t *testing.T) { content := `foo=bar f =quux ` - - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) + tmpFile := tmpFileWithContent(t, content) _, err := ParseEnvFile(tmpFile) if err == nil { @@ -108,11 +109,8 @@ func TestParseEnvFileBadlyFormattedFile(t *testing.T) { // Test ParseEnvFile for a file with a line exceeding bufio.MaxScanTokenSize func TestParseEnvFileLineTooLongFile(t *testing.T) { - content := strings.Repeat("a", bufio.MaxScanTokenSize+42) - content = fmt.Sprint("foo=", content) - - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) + content := "foo=" + strings.Repeat("a", bufio.MaxScanTokenSize+42) + tmpFile := tmpFileWithContent(t, content) _, err := ParseEnvFile(tmpFile) if err == nil { @@ -124,8 +122,7 @@ func TestParseEnvFileLineTooLongFile(t *testing.T) { func TestParseEnvFileRandomFile(t *testing.T) { content := `first line another invalid line` - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) + tmpFile := tmpFileWithContent(t, content) _, err := ParseEnvFile(tmpFile) if err == nil { @@ -146,8 +143,7 @@ func TestParseEnvVariableDefinitionsFile(t *testing.T) { UNDEFINED_VAR HOME ` - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) + tmpFile := tmpFileWithContent(t, content) variables, err := ParseEnvFile(tmpFile) if nil != err { @@ -168,8 +164,7 @@ func TestParseEnvVariableWithNoNameFile(t *testing.T) { content := `# comment= =blank variable names are an error case ` - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) + tmpFile := tmpFileWithContent(t, content) _, err := ParseEnvFile(tmpFile) if nil == err { From e501531b5f35ce4420d658b87f0da3fcf6d612bf Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 25 Feb 2022 16:01:20 +0100 Subject: [PATCH 31/41] cli-plugins/manager: remove uses of deprecated io/ioutil Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 6c06950cdffa5f606b764fe3bc6918186383422f) Signed-off-by: Cory Snider --- cli-plugins/manager/manager.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cli-plugins/manager/manager.go b/cli-plugins/manager/manager.go index 50f7208ea334..6b8f5826c71d 100644 --- a/cli-plugins/manager/manager.go +++ b/cli-plugins/manager/manager.go @@ -1,7 +1,6 @@ package manager import ( - "io/ioutil" "os" "path/filepath" "sort" @@ -57,12 +56,12 @@ func getPluginDirs(dockerCli command.Cli) ([]string, error) { } func addPluginCandidatesFromDir(res map[string][]string, d string) error { - dentries, err := ioutil.ReadDir(d) + dentries, err := os.ReadDir(d) if err != nil { return err } for _, dentry := range dentries { - switch dentry.Mode() & os.ModeType { + switch dentry.Type() & os.ModeType { case 0, os.ModeSymlink: // Regular file or symlink, keep going default: From 0573ec2b01dc2d306932deaa9ba397b741b08e46 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Wed, 13 Jul 2022 12:29:49 +0200 Subject: [PATCH 32/41] format (GoDoc) comments with Go 1.19 to prepare for go updates Older versions of Go do not format these comments, so we can already reformat them ahead of time to prevent gofmt linting failing once we update to Go 1.19 or up. Result of: gofmt -s -w $(find . -type f -name '*.go' | grep -v "/vendor/") With some manual adjusting. Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 82427d1a078e89d9bd10dd397e5ee7736a8086f9) Signed-off-by: Cory Snider --- cli-plugins/manager/plugin.go | 2 +- cli/command/container/cp.go | 6 +- cli/command/container/create.go | 2 +- cli/command/container/opts.go | 10 ++- cli/command/container/opts_test.go | 2 +- cli/command/container/run.go | 2 +- cli/command/container/start.go | 2 +- cli/command/container/stats.go | 3 +- cli/command/formatter/container_test.go | 2 +- cli/command/formatter/reflect_test.go | 2 +- cli/command/image/build.go | 2 +- cli/command/image/formatter_history_test.go | 6 +- cli/command/image/trust.go | 3 +- cli/command/manifest/util.go | 2 +- cli/command/network/create.go | 3 +- cli/command/registry/login.go | 2 +- cli/command/service/list.go | 3 +- cli/command/service/opts.go | 8 ++- cli/command/service/progress/progress.go | 3 +- cli/command/service/update.go | 67 +++++++++---------- cli/command/service/update_test.go | 5 +- cli/command/stack/swarm/deploy_composefile.go | 2 +- cli/command/system/info.go | 4 +- cli/compose/loader/merge.go | 4 +- cli/compose/loader/windows_path.go | 3 +- cli/connhelper/commandconn/commandconn.go | 14 ++-- cli/context/docker/load.go | 2 +- cli/context/store/doc.go | 42 +++++++----- cli/required.go | 2 +- cli/winresources/res_windows.go | 10 +-- e2e/image/push_test.go | 2 +- internal/test/builders/doc.go | 1 - internal/test/doc.go | 1 - .../client/clientset/scheme/register.go | 14 ++-- man/import.go | 1 + opts/envfile.go | 4 +- opts/gpus.go | 3 +- opts/mount.go | 3 +- opts/opts_test.go | 2 +- opts/parse.go | 4 +- opts/port.go | 3 +- 41 files changed, 144 insertions(+), 114 deletions(-) diff --git a/cli-plugins/manager/plugin.go b/cli-plugins/manager/plugin.go index 4b32a4fde641..e501af722837 100644 --- a/cli-plugins/manager/plugin.go +++ b/cli-plugins/manager/plugin.go @@ -34,7 +34,7 @@ type Plugin struct { // returned with no error. An error is only returned due to a // non-recoverable error. // -// nolint: gocyclo +//nolint:gocyclo func newPlugin(c Candidate, rootcmd *cobra.Command) (Plugin, error) { path := c.Path() if path == "" { diff --git a/cli/command/container/cp.go b/cli/command/container/cp.go index 20809bc36206..46ccfa340532 100644 --- a/cli/command/container/cp.go +++ b/cli/command/container/cp.go @@ -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 // requiring a LOCALPATH with a `:` to be made explicit with a relative or // 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: -// 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 // have a separator, e.g., "host0/cname1" if container is in a Docker cluster, diff --git a/cli/command/container/create.go b/cli/command/container/create.go index 036c03d4644c..976abb5d594e 100644 --- a/cli/command/container/create.go +++ b/cli/command/container/create.go @@ -188,7 +188,7 @@ func newCIDFile(path string) (*cidFile, error) { 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) { config := containerConfig.Config hostConfig := containerConfig.HostConfig diff --git a/cli/command/container/opts.go b/cli/command/container/opts.go index c97799ce10ca..ef09b2272d89 100644 --- a/cli/command/container/opts.go +++ b/cli/command/container/opts.go @@ -310,7 +310,8 @@ type containerConfig struct { // parse parses the args for the specified command and generates a Config, // a HostConfig and returns them with the specified command. // 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) { var ( attachStdin = copts.attach.Get("stdin") @@ -951,7 +952,8 @@ func parseWindowsDevice(device string) (container.DeviceMapping, error) { // validateDeviceCgroupRule validates a device cgroup rule string format // It will make sure 'val' is in the form: -// 'type major:minor mode' +// +// 'type major:minor mode' func validateDeviceCgroupRule(val string) (string, error) { if deviceCgroupRuleRegexp.MatchString(val) { return val, nil @@ -995,7 +997,9 @@ func validateDevice(val string, serverOS string) (string, error) { // validateLinuxPath is the implementation of validateDevice knowing that the // target server operating system is a Linux daemon. // 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. func validateLinuxPath(val string, validator func(string) bool) (string, error) { var containerPath string diff --git a/cli/command/container/opts_test.go b/cli/command/container/opts_test.go index 56b0f07f9de0..b5672a186c2a 100644 --- a/cli/command/container/opts_test.go +++ b/cli/command/container/opts_test.go @@ -182,7 +182,7 @@ func TestParseRunWithInvalidArgs(t *testing.T) { } } -// nolint: gocyclo +//nolint:gocyclo func TestParseWithVolumes(t *testing.T) { // A single volume diff --git a/cli/command/container/run.go b/cli/command/container/run.go index fec9995841f8..c9080cb142b2 100644 --- a/cli/command/container/run.go +++ b/cli/command/container/run.go @@ -91,7 +91,7 @@ func runRun(dockerCli command.Cli, flags *pflag.FlagSet, ropts *runOptions, copt return runContainer(dockerCli, ropts, copts, containerConfig) } -// nolint: gocyclo +//nolint:gocyclo func runContainer(dockerCli command.Cli, opts *runOptions, copts *containerOptions, containerConfig *containerConfig) error { config := containerConfig.Config hostConfig := containerConfig.HostConfig diff --git a/cli/command/container/start.go b/cli/command/container/start.go index bec948225f3f..49378f0f93bf 100644 --- a/cli/command/container/start.go +++ b/cli/command/container/start.go @@ -53,7 +53,7 @@ func NewStartCommand(dockerCli command.Cli) *cobra.Command { return cmd } -// nolint: gocyclo +//nolint:gocyclo func runStart(dockerCli command.Cli, opts *startOptions) error { ctx, cancelFun := context.WithCancel(context.Background()) defer cancelFun() diff --git a/cli/command/container/stats.go b/cli/command/container/stats.go index c6a193cf12bc..eaea45c94e49 100644 --- a/cli/command/container/stats.go +++ b/cli/command/container/stats.go @@ -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. // 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 { showAll := len(opts.containers) == 0 closeChan := make(chan error) diff --git a/cli/command/formatter/container_test.go b/cli/command/formatter/container_test.go index 42dc0a3cdae4..bc5944770800 100644 --- a/cli/command/formatter/container_test.go +++ b/cli/command/formatter/container_test.go @@ -436,7 +436,7 @@ type ports struct { expected string } -// nolint: lll +//nolint:lll func TestDisplayablePorts(t *testing.T) { cases := []ports{ { diff --git a/cli/command/formatter/reflect_test.go b/cli/command/formatter/reflect_test.go index ffda51b858b5..58bd7fe42b3f 100644 --- a/cli/command/formatter/reflect_test.go +++ b/cli/command/formatter/reflect_test.go @@ -12,7 +12,7 @@ func (d *dummy) Func1() string { return "Func1" } -func (d *dummy) func2() string { // nolint: unused +func (d *dummy) func2() string { //nolint:unused return "func2(should not be marshalled)" } diff --git a/cli/command/image/build.go b/cli/command/image/build.go index 6d614b0fafa5..efc23cbb7da5 100644 --- a/cli/command/image/build.go +++ b/cli/command/image/build.go @@ -204,7 +204,7 @@ func (out *lastProgressOutput) WriteProgress(prog progress.Progress) error { return out.output.WriteProgress(prog) } -// nolint: gocyclo +//nolint:gocyclo func runBuild(dockerCli command.Cli, options buildOptions) error { buildkitEnabled, err := command.BuildKitEnabled(dockerCli.ServerInfo()) if err != nil { diff --git a/cli/command/image/formatter_history_test.go b/cli/command/image/formatter_history_test.go index 067e421ad16a..2facc0c90f43 100644 --- a/cli/command/image/formatter_history_test.go +++ b/cli/command/image/formatter_history_test.go @@ -84,8 +84,8 @@ func TestHistoryContext_CreatedSince(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 - 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 + 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 var ctx historyContext cases := []historyCase{ @@ -186,7 +186,7 @@ func TestHistoryContext_Table(t *testing.T) { {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"}}, } - // nolint: lll + //nolint:lll 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 imageID2 24 hours ago /bin/bash echo 183MB Hi diff --git a/cli/command/image/trust.go b/cli/command/image/trust.go index ac48ca364ed1..d1d4dcef6745 100644 --- a/cli/command/image/trust.go +++ b/cli/command/image/trust.go @@ -42,7 +42,8 @@ func TrustedPush(ctx context.Context, cli command.Cli, repoInfo *registry.Reposi } // 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 { // 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. diff --git a/cli/command/manifest/util.go b/cli/command/manifest/util.go index 26de5bf66385..1d530d9f2f02 100644 --- a/cli/command/manifest/util.go +++ b/cli/command/manifest/util.go @@ -68,7 +68,7 @@ func normalizeReference(ref string) (reference.Named, error) { } // 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) { data, err := dockerCli.ManifestStore().Get(listRef, namedRef) switch { diff --git a/cli/command/network/create.go b/cli/command/network/create.go index eb3961baf712..f9d6c411857e 100644 --- a/cli/command/network/create.go +++ b/cli/command/network/create.go @@ -128,7 +128,8 @@ func runCreate(dockerCli command.Cli, options createOptions) error { // possible to correlate the various related parameters and consolidate them. // consolidateIpam consolidates subnets, ip-ranges, gateways and auxiliary addresses into // structured ipam data. -// nolint: gocyclo +// +//nolint:gocyclo func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]string) ([]network.IPAMConfig, error) { if len(subnets) < len(ranges) || len(subnets) < len(gateways) { return nil, errors.Errorf("every ip-range or gateway must have a corresponding subnet") diff --git a/cli/command/registry/login.go b/cli/command/registry/login.go index b73c0792b243..76a24353bc5f 100644 --- a/cli/command/registry/login.go +++ b/cli/command/registry/login.go @@ -95,7 +95,7 @@ func verifyloginOptions(dockerCli command.Cli, opts *loginOptions) error { 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() clnt := dockerCli.Client() if err := verifyloginOptions(dockerCli, &opts); err != nil { diff --git a/cli/command/service/list.go b/cli/command/service/list.go index 56cb3a23bab9..e1c9f794ddea 100644 --- a/cli/command/service/list.go +++ b/cli/command/service/list.go @@ -106,7 +106,8 @@ func runList(dockerCli command.Cli, opts listOptions) error { // 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 // that don't have ServiceStatus set, and perform a lookup for those. -// nolint: gocyclo +// +//nolint:gocyclo func AppendServiceStatus(ctx context.Context, c client.APIClient, services []swarm.Service) ([]swarm.Service, error) { status := map[string]*swarm.ServiceStatus{} taskFilter := filters.NewArgs() diff --git a/cli/command/service/opts.go b/cli/command/service/opts.go index f7d7fcfa874f..4976176219f8 100644 --- a/cli/command/service/opts.go +++ b/cli/command/service/opts.go @@ -466,9 +466,13 @@ func (opts *healthCheckOptions) toHealthConfig() (*container.HealthConfig, error } // convertExtraHostsToSwarmHosts converts an array of extra hosts in cli -// : +// +// : +// // into a swarmkit host format: -// IP_address canonical_hostname [aliases...] +// +// IP_address canonical_hostname [aliases...] +// // This assumes input value (:) has already been validated func convertExtraHostsToSwarmHosts(extraHosts []string) []string { hosts := []string{} diff --git a/cli/command/service/progress/progress.go b/cli/command/service/progress/progress.go index 3ed41cb9e44a..367fa6e47172 100644 --- a/cli/command/service/progress/progress.go +++ b/cli/command/service/progress/progress.go @@ -75,7 +75,8 @@ func stateToProgress(state swarm.TaskState, rollback bool) int64 { } // 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 { defer progressWriter.Close() diff --git a/cli/command/service/update.go b/cli/command/service/update.go index 2a701ec0bd63..c8e14c0a8b27 100644 --- a/cli/command/service/update.go +++ b/cli/command/service/update.go @@ -123,7 +123,7 @@ func newListOptsVarWithValidator(validator opts.ValidatorFctType) *opts.ListOpts return opts.NewListOptsRef(&[]string{}, validator) } -// nolint: gocyclo +//nolint:gocyclo func runUpdate(dockerCli command.Cli, flags *pflag.FlagSet, options *serviceOptions, serviceID string) error { apiClient := dockerCli.Client() ctx := context.Background() @@ -249,7 +249,7 @@ func runUpdate(dockerCli command.Cli, flags *pflag.FlagSet, options *serviceOpti return waitOnService(ctx, dockerCli, serviceID, options.quiet) } -// nolint: gocyclo +//nolint:gocyclo func updateService(ctx context.Context, apiClient client.NetworkAPIClient, flags *pflag.FlagSet, spec *swarm.ServiceSpec) error { updateBoolPtr := func(flag string, field **bool) { if flags.Changed(flag) { @@ -1136,37 +1136,37 @@ type hostMapping struct { // Entries can be removed by either a specific `:` mapping, // or by `` alone: // -// - If both IP-address and host-name is provided, the hostname is removed only -// from entries that match the given IP-address. -// - If only a host-name is provided, the hostname is removed from any entry it -// is part of (either as canonical host-name, or as alias). -// - If, after removing the host-name from an entry, no host-names remain in -// the entry, the entry itself is removed. +// - If both IP-address and host-name is provided, the hostname is removed only +// from entries that match the given IP-address. +// - If only a host-name is provided, the hostname is removed from any entry it +// is part of (either as canonical host-name, or as alias). +// - If, after removing the host-name from an entry, no host-names remain in +// the entry, the entry itself is removed. // // For example, the list of host-entries before processing could look like this: // -// hosts = &[]string{ -// "127.0.0.2 host3 host1 host2 host4", -// "127.0.0.1 host1 host4", -// "127.0.0.3 host1", -// "127.0.0.1 host1", -// } +// hosts = &[]string{ +// "127.0.0.2 host3 host1 host2 host4", +// "127.0.0.1 host1 host4", +// "127.0.0.3 host1", +// "127.0.0.1 host1", +// } // // Removing `host1` removes every occurrence: // -// hosts = &[]string{ -// "127.0.0.2 host3 host2 host4", -// "127.0.0.1 host4", -// } +// hosts = &[]string{ +// "127.0.0.2 host3 host2 host4", +// "127.0.0.1 host4", +// } // // Removing `host1:127.0.0.1` on the other hand, only remove the host if the // IP-address matches: // -// hosts = &[]string{ -// "127.0.0.2 host3 host1 host2 host4", -// "127.0.0.1 host4", -// "127.0.0.3 host1", -// } +// hosts = &[]string{ +// "127.0.0.2 host3 host1 host2 host4", +// "127.0.0.1 host4", +// "127.0.0.3 host1", +// } func updateHosts(flags *pflag.FlagSet, hosts *[]string) error { var toRemove []hostMapping if flags.Changed(flagHostRemove) { @@ -1407,34 +1407,33 @@ func updateCredSpecConfig(flags *pflag.FlagSet, containerSpec *swarm.ContainerSp // // Adding/removing capabilities when updating a service is handled as a tri-state; // -// - if the capability was previously "dropped", then remove it from "CapabilityDrop", -// but NOT added to "CapabilityAdd". However, if the capability was not yet in -// the service's "CapabilityDrop", then it's simply added to the service's "CapabilityAdd" -// - likewise, if the capability was previously "added", then it's removed from -// "CapabilityAdd", but NOT added to "CapabilityDrop". If the capability was -// not yet in the service's "CapabilityAdd", then simply add it to the service's -// "CapabilityDrop". +// - if the capability was previously "dropped", then remove it from "CapabilityDrop", +// but NOT added to "CapabilityAdd". However, if the capability was not yet in +// the service's "CapabilityDrop", then it's simply added to the service's "CapabilityAdd" +// - likewise, if the capability was previously "added", then it's removed from +// "CapabilityAdd", but NOT added to "CapabilityDrop". If the capability was +// not yet in the service's "CapabilityAdd", then simply add it to the service's +// "CapabilityDrop". // // In other words, given a service with the following: // // | CapDrop | CapAdd | -// | -------------- | ------------- | +// |----------------|---------------| // | CAP_SOME_CAP | | // // When updating the service, and applying `--cap-add CAP_SOME_CAP`, the previously // dropped capability is removed: // // | CapDrop | CapAdd | -// | -------------- | ------------- | +// |----------------|---------------| // | | | // // After updating the service a second time, applying `--cap-add CAP_SOME_CAP`, // capability is now added: // // | CapDrop | CapAdd | -// | -------------- | ------------- | +// |----------------|---------------| // | | CAP_SOME_CAP | -// func updateCapabilities(flags *pflag.FlagSet, containerSpec *swarm.ContainerSpec) { var ( toAdd, toDrop map[string]bool diff --git a/cli/command/service/update_test.go b/cli/command/service/update_test.go index d750a21975ad..05c7c8c32edf 100644 --- a/cli/command/service/update_test.go +++ b/cli/command/service/update_test.go @@ -520,8 +520,9 @@ func (s secretAPIClientMock) SecretUpdate(ctx context.Context, id string, versio return nil } -// TestUpdateSecretUpdateInPlace tests the ability to update the "target" of an secret with "docker service update" -// by combining "--secret-rm" and "--secret-add" for the same secret. +// TestUpdateSecretUpdateInPlace tests the ability to update the "target" of a +// secret with "docker service update" by combining "--secret-rm" and +// "--secret-add" for the same secret. func TestUpdateSecretUpdateInPlace(t *testing.T) { apiClient := secretAPIClientMock{ listResult: []swarm.Secret{ diff --git a/cli/command/stack/swarm/deploy_composefile.go b/cli/command/stack/swarm/deploy_composefile.go index 2ab9be8a4f5b..8c77ca92f795 100644 --- a/cli/command/stack/swarm/deploy_composefile.go +++ b/cli/command/stack/swarm/deploy_composefile.go @@ -175,7 +175,7 @@ func createNetworks(ctx context.Context, dockerCli command.Cli, namespace conver return nil } -// nolint: gocyclo +//nolint:gocyclo func deployServices(ctx context.Context, dockerCli command.Cli, services map[string]swarm.ServiceSpec, namespace convert.Namespace, sendAuth bool, resolveImage string) error { apiClient := dockerCli.Client() out := dockerCli.Out() diff --git a/cli/command/system/info.go b/cli/command/system/info.go index 1095462a1df6..9fbd6b01bf1a 100644 --- a/cli/command/system/info.go +++ b/cli/command/system/info.go @@ -138,7 +138,7 @@ func prettyPrintClientInfo(dockerCli command.Cli, info clientInfo) { } } -// nolint: gocyclo +//nolint:gocyclo func prettyPrintServerInfo(dockerCli command.Cli, info types.Info) []error { var errs []error @@ -305,7 +305,7 @@ func prettyPrintServerInfo(dockerCli command.Cli, info types.Info) []error { return errs } -// nolint: gocyclo +//nolint:gocyclo func printSwarmInfo(dockerCli command.Cli, info types.Info) { if info.Swarm.LocalNodeState == swarm.LocalNodeStateInactive || info.Swarm.LocalNodeState == swarm.LocalNodeStateLocked { return diff --git a/cli/compose/loader/merge.go b/cli/compose/loader/merge.go index 0de8d8a1b608..f5fb4b397c3c 100644 --- a/cli/compose/loader/merge.go +++ b/cli/compose/loader/merge.go @@ -203,7 +203,7 @@ func mergeLoggingConfig(dst, src reflect.Value) error { return nil } -//nolint: unparam +//nolint:unparam func mergeUlimitsConfig(dst, src reflect.Value) error { if src.Interface() != reflect.Zero(reflect.TypeOf(src.Interface())).Interface() { dst.Elem().Set(src.Elem()) @@ -211,7 +211,7 @@ func mergeUlimitsConfig(dst, src reflect.Value) error { return nil } -//nolint: unparam +//nolint:unparam func mergeServiceNetworkConfig(dst, src reflect.Value) error { if src.Interface() != reflect.Zero(reflect.TypeOf(src.Interface())).Interface() { dst.Elem().FieldByName("Aliases").Set(src.Elem().FieldByName("Aliases")) diff --git a/cli/compose/loader/windows_path.go b/cli/compose/loader/windows_path.go index eaf41bf72aa5..3070bf88430d 100644 --- a/cli/compose/loader/windows_path.go +++ b/cli/compose/loader/windows_path.go @@ -28,7 +28,8 @@ func isAbs(path string) (b bool) { // volumeNameLen returns length of the leading volume name on Windows. // It returns 0 elsewhere. -// nolint: gocyclo +// +//nolint:gocyclo func volumeNameLen(path string) int { if len(path) < 2 { return 0 diff --git a/cli/connhelper/commandconn/commandconn.go b/cli/connhelper/commandconn/commandconn.go index 128da447b5f6..b9c8ae5f4070 100644 --- a/cli/connhelper/commandconn/commandconn.go +++ b/cli/connhelper/commandconn/commandconn.go @@ -4,13 +4,13 @@ // For example, to provide an http.Client that can connect to a Docker daemon // running in a Docker container ("DIND"): // -// httpClient := &http.Client{ -// Transport: &http.Transport{ -// DialContext: func(ctx context.Context, _network, _addr string) (net.Conn, error) { -// return commandconn.New(ctx, "docker", "exec", "-it", containerID, "docker", "system", "dial-stdio") -// }, -// }, -// } +// httpClient := &http.Client{ +// Transport: &http.Transport{ +// DialContext: func(ctx context.Context, _network, _addr string) (net.Conn, error) { +// return commandconn.New(ctx, "docker", "exec", "-it", containerID, "docker", "system", "dial-stdio") +// }, +// }, +// } package commandconn import ( diff --git a/cli/context/docker/load.go b/cli/context/docker/load.go index ccfee02d1c17..f25937105941 100644 --- a/cli/context/docker/load.go +++ b/cli/context/docker/load.go @@ -72,7 +72,7 @@ func (c *Endpoint) tlsConfig() (*tls.Config, error) { var err error // TODO should we follow Golang, and deprecate RFC 1423 encryption, and produce a warning (or just error)? see https://github.com/docker/cli/issues/3212 - if x509.IsEncryptedPEMBlock(pemBlock) { //nolint: staticcheck // SA1019: x509.IsEncryptedPEMBlock is deprecated, and insecure by design + if x509.IsEncryptedPEMBlock(pemBlock) { //nolint:staticcheck // SA1019: x509.IsEncryptedPEMBlock is deprecated, and insecure by design keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(c.TLSPassword)) //nolint: staticcheck // SA1019: x509.IsEncryptedPEMBlock is deprecated, and insecure by design if err != nil { return nil, errors.Wrap(err, "private key is encrypted, but could not decrypt it") diff --git a/cli/context/store/doc.go b/cli/context/store/doc.go index 5626a64d9127..705982ae4112 100644 --- a/cli/context/store/doc.go +++ b/cli/context/store/doc.go @@ -1,22 +1,32 @@ -// Package store provides a generic way to store credentials to connect to virtually any kind of remote system. -// The term `context` comes from the similar feature in Kubernetes kubectl config files. +// Package store provides a generic way to store credentials to connect to +// virtually any kind of remote system. +// The term `context` comes from the similar feature in Kubernetes kubectl +// config files. // -// Conceptually, a context is a set of metadata and TLS data, that can be used to connect to various endpoints -// of a remote system. TLS data and metadata are stored separately, so that in the future, we will be able to store sensitive -// information in a more secure way, depending on the os we are running on (e.g.: on Windows we could use the user Certificate Store, on Mac OS the user Keychain...). +// Conceptually, a context is a set of metadata and TLS data, that can be used +// to connect to various endpoints of a remote system. TLS data and metadata +// are stored separately, so that in the future, we will be able to store +// sensitive information in a more secure way, depending on the os we are running +// on (e.g.: on Windows we could use the user Certificate Store, on macOS the +// user Keychain...). // // Current implementation is purely file based with the following structure: -// ${CONTEXT_ROOT} -// - meta/ -// - /meta.json: contains context medata (key/value pairs) as well as a list of endpoints (themselves containing key/value pair metadata) -// - tls/ -// - /endpoint1/: directory containing TLS data for the endpoint1 in the corresponding context // -// The context store itself has absolutely no knowledge about what a docker or a kubernetes endpoint should contain in term of metadata or TLS config. -// Client code is responsible for generating and parsing endpoint metadata and TLS files. -// The multi-endpoints approach of this package allows to combine many different endpoints in the same "context" (e.g., the Docker CLI -// is able for a single context to define both a docker endpoint and a Kubernetes endpoint for the same cluster, and also specify which -// orchestrator to use by default when deploying a compose stack on this cluster). +// ${CONTEXT_ROOT} +// meta/ +// /meta.json: contains context medata (key/value pairs) as +// well as a list of endpoints (themselves containing +// key/value pair metadata). +// tls/ +// /endpoint1/: directory containing TLS data for the endpoint1 +// in the corresponding context. // -// Context IDs are actually SHA256 hashes of the context name, and are there only to avoid dealing with special characters in context names. +// The context store itself has absolutely no knowledge about what a docker +// endpoint should contain in term of metadata or TLS config. Client code is +// responsible for generating and parsing endpoint metadata and TLS files. The +// multi-endpoints approach of this package allows to combine many different +// endpoints in the same "context". +// +// Context IDs are actually SHA256 hashes of the context name, and are there +// only to avoid dealing with special characters in context names. package store diff --git a/cli/required.go b/cli/required.go index cce81c86ab9f..454e24761359 100644 --- a/cli/required.go +++ b/cli/required.go @@ -99,7 +99,7 @@ func ExactArgs(number int) cobra.PositionalArgs { } } -//nolint: unparam +//nolint:unparam func pluralize(word string, number int) string { if number == 1 { return word diff --git a/cli/winresources/res_windows.go b/cli/winresources/res_windows.go index 033995d0bcec..6c37d64736cc 100644 --- a/cli/winresources/res_windows.go +++ b/cli/winresources/res_windows.go @@ -1,9 +1,10 @@ -/*Package winresources is used to embed Windows resources into docker.exe. +/* +Package winresources is used to embed Windows resources into docker.exe. These resources are used to provide - * Version information - * An icon - * A Windows manifest declaring Windows version support + - Version information + - An icon + - A Windows manifest declaring Windows version support The resource object files are generated when building with scripts/build/binary . The resource source files are located in scripts/winresources. @@ -11,6 +12,5 @@ This occurs automatically when you run scripts/build/windows. These object files are picked up automatically by go build when this package is included. - */ package winresources diff --git a/e2e/image/push_test.go b/e2e/image/push_test.go index 48029d9a3296..fbc5095f3de3 100644 --- a/e2e/image/push_test.go +++ b/e2e/image/push_test.go @@ -325,7 +325,7 @@ func createImage(t *testing.T, repo string, tags ...string) string { return fmt.Sprintf("%s/%s:%s", registryPrefix, repo, tags[0]) } -//nolint: unparam +//nolint:unparam func withNotaryPassphrase(pwd string) func(*icmd.Cmd) { return func(c *icmd.Cmd) { c.Env = append(c.Env, []string{ diff --git a/internal/test/builders/doc.go b/internal/test/builders/doc.go index eac991c2e483..01fa86e41dfb 100644 --- a/internal/test/builders/doc.go +++ b/internal/test/builders/doc.go @@ -1,3 +1,2 @@ // Package builders helps you create struct for your unit test while keeping them expressive. -// package builders diff --git a/internal/test/doc.go b/internal/test/doc.go index 342441d533d2..401f02facfec 100644 --- a/internal/test/doc.go +++ b/internal/test/doc.go @@ -1,5 +1,4 @@ // Package test is a test-only package that can be used by other cli package to write unit test. // // It as an internal package and cannot be used outside of github.com/docker/cli package. -// package test diff --git a/kubernetes/client/clientset/scheme/register.go b/kubernetes/client/clientset/scheme/register.go index 9a42571b1767..61fc91e8b300 100644 --- a/kubernetes/client/clientset/scheme/register.go +++ b/kubernetes/client/clientset/scheme/register.go @@ -15,14 +15,14 @@ var ( // AddToScheme adds all types of this clientset into the given scheme. This allows composition // of clientsets, like in: // -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kuberentes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) +// import ( +// "k8s.io/client-go/kubernetes" +// clientsetscheme "k8s.io/client-go/kuberentes/scheme" +// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" +// ) // -// kclientset, _ := kubernetes.NewForConfig(c) -// aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) +// kclientset, _ := kubernetes.NewForConfig(c) +// aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) // // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // correctly. diff --git a/man/import.go b/man/import.go index 76cb75f473aa..4ba6b40bd5a4 100644 --- a/man/import.go +++ b/man/import.go @@ -1,3 +1,4 @@ +//go:build never // +build never package main diff --git a/opts/envfile.go b/opts/envfile.go index 69d3ca6f60ce..26aa3c3a9094 100644 --- a/opts/envfile.go +++ b/opts/envfile.go @@ -6,12 +6,12 @@ import ( // ParseEnvFile reads a file with environment variables enumerated by lines // -// ``Environment variable names used by the utilities in the Shell and +// “Environment variable names used by the utilities in the Shell and // Utilities volume of IEEE Std 1003.1-2001 consist solely of uppercase // letters, digits, and the '_' (underscore) from the characters defined in // Portable Character Set and do not begin with a digit. *But*, other // characters may be permitted by an implementation; applications shall -// tolerate the presence of such names.'' +// tolerate the presence of such names.” // -- http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html // // As of #16585, it's up to application inside docker to validate or not diff --git a/opts/gpus.go b/opts/gpus.go index e110a4771e51..8796a805d47f 100644 --- a/opts/gpus.go +++ b/opts/gpus.go @@ -24,7 +24,8 @@ func parseCount(s string) (int, error) { } // Set a new mount value -// nolint: gocyclo +// +//nolint:gocyclo func (o *GpuOpts) Set(value string) error { csvReader := csv.NewReader(strings.NewReader(value)) fields, err := csvReader.Read() diff --git a/opts/mount.go b/opts/mount.go index ef661dd51b75..1a6e1a61b0a6 100644 --- a/opts/mount.go +++ b/opts/mount.go @@ -17,7 +17,8 @@ type MountOpt struct { } // Set a new mount value -// nolint: gocyclo +// +//nolint:gocyclo func (m *MountOpt) Set(value string) error { csvReader := csv.NewReader(strings.NewReader(value)) fields, err := csvReader.Read() diff --git a/opts/opts_test.go b/opts/opts_test.go index a1be7b51475f..4ef3e19b6fff 100644 --- a/opts/opts_test.go +++ b/opts/opts_test.go @@ -118,7 +118,7 @@ func TestListOptsWithValidator(t *testing.T) { } } -// nolint: lll +//nolint:lll func TestValidateDNSSearch(t *testing.T) { valid := []string{ `.`, diff --git a/opts/parse.go b/opts/parse.go index 327c2775f6b4..4012c461fbaa 100644 --- a/opts/parse.go +++ b/opts/parse.go @@ -55,7 +55,9 @@ func ConvertKVStringsToMap(values []string) map[string]string { // ConvertKVStringsToMapWithNil converts ["key=value"] to {"key":"value"} // but set unset keys to nil - meaning the ones with no "=" in them. // We use this in cases where we need to distinguish between -// FOO= and FOO +// +// FOO= and FOO +// // where the latter case just means FOO was mentioned but not given a value func ConvertKVStringsToMapWithNil(values []string) map[string]*string { result := make(map[string]*string, len(values)) diff --git a/opts/port.go b/opts/port.go index f65367168d82..f3151571d887 100644 --- a/opts/port.go +++ b/opts/port.go @@ -25,7 +25,8 @@ type PortOpt struct { } // Set a new port value -// nolint: gocyclo +// +//nolint:gocyclo func (p *PortOpt) Set(value string) error { longSyntax, err := regexp.MatchString(`\w+=\w+(,\w+=\w+)*`, value) if err != nil { From 01c5120be7622f179ae129e1c26f5708d03682e0 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 2 Sep 2022 22:41:48 +0200 Subject: [PATCH 33/41] linting: use consts from stdlib (usestdlibvars) cli/command/image/build/context.go:238:23: "400" can be replaced by http.StatusBadRequest (usestdlibvars) if resp.StatusCode < 400 { ^ cli/trust/trust.go:139:30: "GET" can be replaced by http.MethodGet (usestdlibvars) req, err := http.NewRequest("GET", endpointStr, nil) ^ Signed-off-by: Sebastiaan van Stijn (cherry picked from commit d3d9301d2dfd8d3758e6b6f54b1573c60ce07a01) Signed-off-by: Cory Snider --- cli/command/image/build/context.go | 2 +- cli/trust/trust.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cli/command/image/build/context.go b/cli/command/image/build/context.go index 1b9f975d9b3f..b55ec22a5a05 100644 --- a/cli/command/image/build/context.go +++ b/cli/command/image/build/context.go @@ -235,7 +235,7 @@ func getWithStatusError(url string) (resp *http.Response, err error) { if resp, err = http.Get(url); err != nil { return nil, err } - if resp.StatusCode < 400 { + if resp.StatusCode < http.StatusBadRequest { return resp, nil } msg := fmt.Sprintf("failed to GET %s with status %s", url, resp.Status) diff --git a/cli/trust/trust.go b/cli/trust/trust.go index df11227e9341..bb8aad85243f 100644 --- a/cli/trust/trust.go +++ b/cli/trust/trust.go @@ -136,7 +136,7 @@ func GetNotaryRepository(in io.Reader, out io.Writer, userAgent string, repoInfo Timeout: 5 * time.Second, } endpointStr := server + "/v2/" - req, err := http.NewRequest("GET", endpointStr, nil) + req, err := http.NewRequest(http.MethodGet, endpointStr, nil) if err != nil { return nil, err } From f9a2af0a49437df5861f5c2b68642414dd7ef01f Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 2 Sep 2022 22:45:05 +0200 Subject: [PATCH 34/41] linting: remove unused nolint comments (nolintlint) cli-plugins/manager/plugin.go:37:1: directive `//nolint:gocyclo` is unused for linter "gocyclo" (nolintlint) //nolint:gocyclo ^ cli/command/image/formatter_history_test.go:189:2: directive `//nolint:lll` is unused for linter "lll" (nolintlint) //nolint:lll ^ cli/command/service/list.go:113:1: directive `//nolint:gocyclo` is unused for linter "gocyclo" (nolintlint) //nolint:gocyclo ^ cli/command/stack/swarm/deploy_composefile.go:178:1: directive `//nolint:gocyclo` is unused for linter "gocyclo" (nolintlint) //nolint:gocyclo ^ Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 491407b541cf9d568aca435f7e39a53fa3107017) Signed-off-by: Cory Snider --- cli-plugins/manager/plugin.go | 2 -- cli/command/image/formatter_history_test.go | 1 - cli/command/service/list.go | 2 -- cli/command/stack/swarm/deploy_composefile.go | 1 - 4 files changed, 6 deletions(-) diff --git a/cli-plugins/manager/plugin.go b/cli-plugins/manager/plugin.go index e501af722837..99db25d5c812 100644 --- a/cli-plugins/manager/plugin.go +++ b/cli-plugins/manager/plugin.go @@ -33,8 +33,6 @@ type Plugin struct { // is set, and is always a `pluginError`, but the `Plugin` is still // returned with no error. An error is only returned due to a // non-recoverable error. -// -//nolint:gocyclo func newPlugin(c Candidate, rootcmd *cobra.Command) (Plugin, error) { path := c.Path() if path == "" { diff --git a/cli/command/image/formatter_history_test.go b/cli/command/image/formatter_history_test.go index 2facc0c90f43..310c7572e398 100644 --- a/cli/command/image/formatter_history_test.go +++ b/cli/command/image/formatter_history_test.go @@ -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: "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 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 diff --git a/cli/command/service/list.go b/cli/command/service/list.go index e1c9f794ddea..fd22587c0b4e 100644 --- a/cli/command/service/list.go +++ b/cli/command/service/list.go @@ -106,8 +106,6 @@ func runList(dockerCli command.Cli, opts listOptions) error { // 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 // 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) { status := map[string]*swarm.ServiceStatus{} taskFilter := filters.NewArgs() diff --git a/cli/command/stack/swarm/deploy_composefile.go b/cli/command/stack/swarm/deploy_composefile.go index 8c77ca92f795..f3176624306a 100644 --- a/cli/command/stack/swarm/deploy_composefile.go +++ b/cli/command/stack/swarm/deploy_composefile.go @@ -175,7 +175,6 @@ func createNetworks(ctx context.Context, dockerCli command.Cli, namespace conver return nil } -//nolint:gocyclo func deployServices(ctx context.Context, dockerCli command.Cli, services map[string]swarm.ServiceSpec, namespace convert.Namespace, sendAuth bool, resolveImage string) error { apiClient := dockerCli.Client() out := dockerCli.Out() From c06cb423ebac412d7e35385aca62d1ed7ff81dd2 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 2 Sep 2022 22:49:01 +0200 Subject: [PATCH 35/41] linting: ST1019: package is being imported more than once (stylecheck) cli/command/manifest/inspect_test.go:9:2: ST1019: package "github.com/docker/cli/cli/manifest/types" is being imported more than once (stylecheck) "github.com/docker/cli/cli/manifest/types" ^ cli/command/manifest/inspect_test.go:10:2: ST1019(related information): other import of "github.com/docker/cli/cli/manifest/types" (stylecheck) manifesttypes "github.com/docker/cli/cli/manifest/types" ^ cli/command/stack/swarm/deploy_composefile.go:14:2: ST1019: package "github.com/docker/docker/client" is being imported more than once (stylecheck) apiclient "github.com/docker/docker/client" ^ cli/command/stack/swarm/deploy_composefile.go:15:2: ST1019(related information): other import of "github.com/docker/docker/client" (stylecheck) dockerclient "github.com/docker/docker/client" ^ Signed-off-by: Sebastiaan van Stijn (cherry picked from commit ce01160e745b0aaee1d3b49a4993738f3035be14) Signed-off-by: Cory Snider --- cli/command/manifest/inspect_test.go | 9 ++++----- cli/command/stack/swarm/deploy_composefile.go | 5 ++--- cli/command/trust/inspect_pretty_test.go | 4 ++-- 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/cli/command/manifest/inspect_test.go b/cli/command/manifest/inspect_test.go index 92bfd2e27a72..57e7a6b0031a 100644 --- a/cli/command/manifest/inspect_test.go +++ b/cli/command/manifest/inspect_test.go @@ -7,7 +7,6 @@ import ( "github.com/docker/cli/cli/manifest/store" "github.com/docker/cli/cli/manifest/types" - manifesttypes "github.com/docker/cli/cli/manifest/types" "github.com/docker/cli/internal/test" "github.com/docker/distribution" "github.com/docker/distribution/manifest/schema2" @@ -80,10 +79,10 @@ func TestInspectCommandNotFound(t *testing.T) { cli := test.NewFakeCli(nil) cli.SetManifestStore(store) cli.SetRegistryClient(&fakeRegistryClient{ - getManifestFunc: func(_ context.Context, _ reference.Named) (manifesttypes.ImageManifest, error) { - return manifesttypes.ImageManifest{}, errors.New("missing") + getManifestFunc: func(_ context.Context, _ reference.Named) (types.ImageManifest, error) { + 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) }, }) @@ -119,7 +118,7 @@ func TestInspectcommandRemoteManifest(t *testing.T) { cli := test.NewFakeCli(nil) cli.SetManifestStore(store) 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 }, }) diff --git a/cli/command/stack/swarm/deploy_composefile.go b/cli/command/stack/swarm/deploy_composefile.go index f3176624306a..d574125d2c19 100644 --- a/cli/command/stack/swarm/deploy_composefile.go +++ b/cli/command/stack/swarm/deploy_composefile.go @@ -12,7 +12,6 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/swarm" apiclient "github.com/docker/docker/client" - dockerclient "github.com/docker/docker/client" "github.com/pkg/errors" ) @@ -77,7 +76,7 @@ func getServicesDeclaredNetworks(serviceConfigs []composetypes.ServiceConfig) ma return serviceNetworks } -func validateExternalNetworks(ctx context.Context, client dockerclient.NetworkAPIClient, externalNetworks []string) error { +func validateExternalNetworks(ctx context.Context, client apiclient.NetworkAPIClient, externalNetworks []string) error { for _, networkName := range externalNetworks { if !container.NetworkMode(networkName).IsUserDefined() { // Networks that are not user defined always exist on all nodes as @@ -86,7 +85,7 @@ func validateExternalNetworks(ctx context.Context, client dockerclient.NetworkAP } network, err := client.NetworkInspect(ctx, networkName, types.NetworkInspectOptions{}) switch { - case dockerclient.IsErrNotFound(err): + case apiclient.IsErrNotFound(err): return errors.Errorf("network %q is declared as external, but could not be found. You need to create a swarm-scoped network before the stack is deployed", networkName) case err != nil: return err diff --git a/cli/command/trust/inspect_pretty_test.go b/cli/command/trust/inspect_pretty_test.go index 2d6e456e8ab2..626d5f9b6db1 100644 --- a/cli/command/trust/inspect_pretty_test.go +++ b/cli/command/trust/inspect_pretty_test.go @@ -11,7 +11,7 @@ import ( "github.com/docker/cli/internal/test" notaryfake "github.com/docker/cli/internal/test/notary" "github.com/docker/docker/api/types" - dockerClient "github.com/docker/docker/client" + apiclient "github.com/docker/docker/client" "github.com/theupdateframework/notary" "github.com/theupdateframework/notary/client" "github.com/theupdateframework/notary/tuf/data" @@ -24,7 +24,7 @@ import ( // TODO(n4ss): remove common tests with the regular inspect command type fakeClient struct { - dockerClient.Client + apiclient.Client } func (c *fakeClient) Info(ctx context.Context) (types.Info, error) { From 8dc18ce7d070fc6cc5a918b1cc7c3385dfca7241 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 2 Sep 2022 23:04:20 +0200 Subject: [PATCH 36/41] linting: os.Setenv() can be replaced by `t.Setenv()` (tenv) cli/command/cli_options_test.go:29:2: os.Setenv() can be replaced by `t.Setenv()` in TestWithContentTrustFromEnv (tenv) os.Setenv(envvar, "true") ^ cli/command/cli_options_test.go:31:2: os.Setenv() can be replaced by `t.Setenv()` in TestWithContentTrustFromEnv (tenv) os.Setenv(envvar, "false") ^ cli/command/cli_options_test.go:33:2: os.Setenv() can be replaced by `t.Setenv()` in TestWithContentTrustFromEnv (tenv) os.Setenv(envvar, "invalid") ^ Signed-off-by: Sebastiaan van Stijn (cherry picked from commit cef858170d1193661d95ccf61c869ca8d0e18b43) Signed-off-by: Cory Snider --- cli/command/cli_options_test.go | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/cli/command/cli_options_test.go b/cli/command/cli_options_test.go index 008502391384..4ed0f8f90e2c 100644 --- a/cli/command/cli_options_test.go +++ b/cli/command/cli_options_test.go @@ -15,23 +15,13 @@ func contentTrustEnabled(t *testing.T) bool { // NB: Do not t.Parallel() this test -- it messes with the process environment. func TestWithContentTrustFromEnv(t *testing.T) { - envvar := "DOCKER_CONTENT_TRUST" - if orig, ok := os.LookupEnv(envvar); ok { - defer func() { - os.Setenv(envvar, orig) - }() - } else { - defer func() { - 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)) + const envvar = "DOCKER_CONTENT_TRUST" + t.Setenv(envvar, "true") + assert.Check(t, contentTrustEnabled(t)) + t.Setenv(envvar, "false") + assert.Check(t, !contentTrustEnabled(t)) + t.Setenv(envvar, "invalid") + assert.Check(t, contentTrustEnabled(t)) os.Unsetenv(envvar) - assert.Assert(t, !contentTrustEnabled(t)) + assert.Check(t, !contentTrustEnabled(t)) } From 43c1e3d5cbf82bb1e907385e78d3e20834859dc8 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 2 Sep 2022 23:55:51 +0200 Subject: [PATCH 37/41] linting: ST1017: don't use Yoda conditions (stylecheck) opts/envfile_test.go:157:5: ST1017: don't use Yoda conditions (stylecheck) if 1 != len(variables) { ^ Signed-off-by: Sebastiaan van Stijn (cherry picked from commit b508b0fc315d1576bd4d3648614c0a771e2939c8) Signed-off-by: Cory Snider --- opts/envfile_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/opts/envfile_test.go b/opts/envfile_test.go index de84410a05de..be97373fcb4d 100644 --- a/opts/envfile_test.go +++ b/opts/envfile_test.go @@ -154,7 +154,7 @@ HOME t.Fatal("the HOME variable is not properly imported as the first variable (but it is the only one to import)") } - if 1 != len(variables) { + if len(variables) != 1 { t.Fatal("exactly one variable is imported (as the other one is not set at all)") } } From d3a4ff827f5b0fb9eedfc84baad84b6cdbd4c8b4 Mon Sep 17 00:00:00 2001 From: Cory Snider Date: Wed, 1 Mar 2023 10:21:08 -0500 Subject: [PATCH 38/41] linting: exclude ST1005: error strings should not be capitalized (stylecheck) Changing the output of errors would be unexpected in a patch release. Signed-off-by: Cory Snider --- .golangci.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.golangci.yml b/.golangci.yml index 9f32b0dee813..3b0940f2b7b0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -110,6 +110,12 @@ issues: - errcheck - 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. max-issues-per-linter: 0 From b8dd4ca57b01f14d802a6f96b424d03a78df5e7a Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 3 Sep 2022 17:49:54 +0200 Subject: [PATCH 39/41] linting: G112: Potential Slowloris Attack Picking 2 seconds, although that's just a randomly picked timeout; given that this is only for testing, it's not too important. e2e/plugin/basic/basic.go:25:12: G112: Potential Slowloris Attack because ReadHeaderTimeout is not configured in the http.Server (gosec) server := http.Server{ Addr: l.Addr().String(), Handler: http.NewServeMux(), } Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 98654202c2f70c4d53490a93dbfff4dc112958d2) Signed-off-by: Cory Snider --- e2e/plugin/basic/basic.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/e2e/plugin/basic/basic.go b/e2e/plugin/basic/basic.go index 892272826f4f..b03ca96ee036 100644 --- a/e2e/plugin/basic/basic.go +++ b/e2e/plugin/basic/basic.go @@ -6,6 +6,7 @@ import ( "net/http" "os" "path/filepath" + "time" ) func main() { @@ -23,8 +24,9 @@ func main() { mux := http.NewServeMux() server := http.Server{ - Addr: l.Addr().String(), - Handler: http.NewServeMux(), + Addr: l.Addr().String(), + Handler: http.NewServeMux(), + ReadHeaderTimeout: 2 * time.Second, // G112: Potential Slowloris Attack because ReadHeaderTimeout is not configured in the http.Server } mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1.1+json") From 2d955cbeed72c4b848bcceb9b4c1b50a10fad251 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 3 Sep 2022 18:50:45 +0200 Subject: [PATCH 40/41] linting: assigned to src, but reassigned without using the value (wastedassign) cli/command/container/opts.go:928:2: assigned to src, but reassigned without using the value (wastedassign) src := "" ^ Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 3dfdaa6458197deb7efa6c906e15c5db97d444ff) Signed-off-by: Cory Snider --- cli/command/container/opts.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cli/command/container/opts.go b/cli/command/container/opts.go index ef09b2272d89..3ad8a5887e3a 100644 --- a/cli/command/container/opts.go +++ b/cli/command/container/opts.go @@ -911,8 +911,7 @@ func parseDevice(device, serverOS string) (container.DeviceMapping, error) { // parseLinuxDevice parses a device mapping string to a container.DeviceMapping struct // knowing that the target is a Linux daemon func parseLinuxDevice(device string) (container.DeviceMapping, error) { - src := "" - dst := "" + var src, dst string permissions := "rwm" arr := strings.Split(device, ":") switch len(arr) { From 48151d432cca51f990b518c615a6dee860531f0c Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 2 Sep 2022 21:24:26 +0200 Subject: [PATCH 41/41] golangci-lint: update to v1.49.0 for compatibilty with go1.19 Remove the "deadcode", "structcheck", and "varcheck" linters, as they are deprecated: WARN [runner] The linter 'deadcode' is deprecated (since v1.49.0) due to: The owner seems to have abandoned the linter. Replaced by unused. WARN [runner] The linter 'structcheck' is deprecated (since v1.49.0) due to: The owner seems to have abandoned the linter. Replaced by unused. WARN [runner] The linter 'varcheck' is deprecated (since v1.49.0) due to: The owner seems to have abandoned the linter. Replaced by unused. WARN [linters context] structcheck is disabled because of generics. You can track the evolution of the generics support by following the golangci/golangci-lint#2649. And ignore gosec G113, which only affects gp < 1.16.14. and go < 1.17.7 opts/opts.go:398:13: G113: Potential uncontrolled memory consumption in Rat.SetString (CVE-2022-23772) (gosec) cpu, ok := new(big.Rat).SetString(value) ^ Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 0dd2c1808201f7f602d9e0ce12ca3f64e13b5f60) Signed-off-by: Cory Snider --- .golangci.yml | 16 ++++++++++++---- dockerfiles/Dockerfile.lint | 2 +- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 3b0940f2b7b0..1f5e9809577f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,7 +1,6 @@ linters: enable: - bodyclose - - deadcode - dogsled - gocyclo - goimports @@ -13,14 +12,12 @@ linters: - megacheck - misspell - nakedret + - revive - staticcheck - - structcheck - typecheck - unconvert - unparam - unused - - revive - - varcheck disable: - errcheck @@ -93,6 +90,12 @@ issues: linters: - 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 # TODO: consider upstreaming this to golangci-lint's default exclusion rules - text: "G204: Subprocess launched with a potential tainted input or cmd arguments" @@ -104,6 +107,11 @@ issues: linters: - 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. - path: _test\.go linters: diff --git a/dockerfiles/Dockerfile.lint b/dockerfiles/Dockerfile.lint index 13bd9acf0541..966c232bf546 100644 --- a/dockerfiles/Dockerfile.lint +++ b/dockerfiles/Dockerfile.lint @@ -2,7 +2,7 @@ ARG GO_VERSION=1.18.10 ARG ALPINE_VERSION=3.16 -ARG GOLANGCI_LINT_VERSION=v1.45.2 +ARG GOLANGCI_LINT_VERSION=v1.49.0 FROM golang:${GO_VERSION}-alpine${ALPINE_VERSION} AS build ENV CGO_ENABLED=0