From 65a68f87b8f344a41f0534300d75d7841f975d89 Mon Sep 17 00:00:00 2001 From: Craig MacKenzie Date: Mon, 22 Jan 2024 11:21:22 -0500 Subject: [PATCH] Remove all io/ioutil imports. (#4106) * Remove all io/ioutil imports. * Convert DirEntry to FileInfo for mode checks. --- dev-tools/cmd/buildfleetcfg/buildfleetcfg.go | 3 +- dev-tools/licenses/license_generate.go | 7 ++-- dev-tools/mage/common.go | 9 +++-- dev-tools/mage/config.go | 3 +- dev-tools/mage/copy.go | 34 +++++++++++++------ dev-tools/mage/gotest.go | 9 +++-- dev-tools/mage/integtest_docker.go | 8 ++--- dev-tools/mage/kubernetes/kind.go | 10 +++--- dev-tools/mage/kubernetes/kuberemote.go | 4 +-- dev-tools/mage/kubernetes/kubernetes.go | 5 ++- dev-tools/mage/pkgspecs.go | 4 +-- dev-tools/mage/pkgtypes.go | 7 ++-- dev-tools/mage/settings.go | 7 ++-- .../handlers/handler_action_policy_change.go | 3 +- .../agent/application/filelock/locker_test.go | 3 +- .../gateway/fleet/fleet_gateway_test.go | 5 ++- .../agent/application/monitoring/process.go | 4 +-- .../artifact/download/headers_rtt_test.go | 4 +-- .../artifact/download/http/downloader_test.go | 9 +++-- .../artifact/download/http/verifier.go | 4 +-- .../upgrade/artifact/download/verifier.go | 3 +- .../agent/application/upgrade/step_mark.go | 5 ++- .../agent/application/upgrade/upgrade_test.go | 7 ++-- internal/pkg/agent/cleaner/cleaner_test.go | 5 ++- internal/pkg/agent/cmd/component_spec.go | 4 +-- internal/pkg/agent/cmd/upgrade.go | 3 +- ...crypted_disk_storage_windows_linux_test.go | 6 ++-- internal/pkg/agent/storage/replace_store.go | 3 +- internal/pkg/agent/storage/storage_test.go | 21 ++++++------ .../agent/storage/store/action_store_test.go | 3 +- internal/pkg/agent/vault/seed.go | 7 ++-- internal/pkg/basecmd/version/cmd_test.go | 14 ++++---- internal/pkg/config/config.go | 3 +- internal/pkg/crypto/io_test.go | 15 ++++---- internal/pkg/dir/discover_test.go | 3 +- internal/pkg/filewatcher/watcher_test.go | 17 +++++----- internal/pkg/fleetapi/ack_cmd.go | 4 +-- .../fleetapi/acker/fleet/fleet_acker_test.go | 3 +- internal/pkg/fleetapi/checkin_cmd.go | 4 +-- internal/pkg/fleetapi/checkin_cmd_test.go | 6 ++-- internal/pkg/fleetapi/client/client.go | 3 +- internal/pkg/fleetapi/client/client_test.go | 6 ++-- internal/pkg/remote/client_test.go | 16 ++++----- internal/pkg/remote/round_trippers.go | 10 +++--- pkg/component/load.go | 3 +- pkg/component/load_test.go | 4 +-- pkg/packer/packer.go | 4 +-- pkg/packer/packer_test.go | 5 ++- pkg/testing/fixture.go | 5 ++- 49 files changed, 158 insertions(+), 176 deletions(-) diff --git a/dev-tools/cmd/buildfleetcfg/buildfleetcfg.go b/dev-tools/cmd/buildfleetcfg/buildfleetcfg.go index df35609de01..b0c93073bc9 100644 --- a/dev-tools/cmd/buildfleetcfg/buildfleetcfg.go +++ b/dev-tools/cmd/buildfleetcfg/buildfleetcfg.go @@ -9,7 +9,6 @@ import ( "flag" "fmt" "go/format" - "io/ioutil" "os" "text/template" @@ -84,7 +83,7 @@ func main() { return } - ioutil.WriteFile(output, data, 0640) + os.WriteFile(output, data, 0640) return } diff --git a/dev-tools/licenses/license_generate.go b/dev-tools/licenses/license_generate.go index e451cddb356..dc5ec58f8ba 100644 --- a/dev-tools/licenses/license_generate.go +++ b/dev-tools/licenses/license_generate.go @@ -8,7 +8,6 @@ import ( "bytes" "flag" "go/format" - "io/ioutil" "os" "text/template" ) @@ -52,13 +51,13 @@ func init() { func main() { Headers := make(map[string]string) - content, err := ioutil.ReadFile("ELASTIC-LICENSE-header.txt") + content, err := os.ReadFile("ELASTIC-LICENSE-header.txt") if err != nil { panic("could not read Elastic license.") } Headers["Elastic"] = string(content) - content, err = ioutil.ReadFile("ELASTIC-LICENSE-2.0-header.txt") + content, err = os.ReadFile("ELASTIC-LICENSE-2.0-header.txt") if err != nil { panic("could not read Elastic License 2.0 license.") } @@ -78,6 +77,6 @@ func main() { if output == "-" { os.Stdout.Write(bs) } else { - ioutil.WriteFile(output, bs, 0640) + os.WriteFile(output, bs, 0640) } } diff --git a/dev-tools/mage/common.go b/dev-tools/mage/common.go index 80108357b89..e7f38f20289 100644 --- a/dev-tools/mage/common.go +++ b/dev-tools/mage/common.go @@ -19,7 +19,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "log" "net/http" "os" @@ -118,7 +117,7 @@ func joinMaps(args ...map[string]interface{}) map[string]interface{} { } func expandFile(src, dst string, args ...map[string]interface{}) error { - tmplData, err := ioutil.ReadFile(src) + tmplData, err := os.ReadFile(src) if err != nil { return fmt.Errorf("failed reading from template %v, %w", src, err) } @@ -133,7 +132,7 @@ func expandFile(src, dst string, args ...map[string]interface{}) error { return err } - if err = ioutil.WriteFile(createDir(dst), []byte(output), 0644); err != nil { + if err = os.WriteFile(createDir(dst), []byte(output), 0644); err != nil { return fmt.Errorf("failed to write rendered template: %w", err) } @@ -236,13 +235,13 @@ func FindReplace(file string, re *regexp.Regexp, repl string) error { return err } - contents, err := ioutil.ReadFile(file) + contents, err := os.ReadFile(file) if err != nil { return err } out := re.ReplaceAllString(string(contents), repl) - return ioutil.WriteFile(file, []byte(out), info.Mode().Perm()) + return os.WriteFile(file, []byte(out), info.Mode().Perm()) } // MustFindReplace invokes FindReplace and panics if an error occurs. diff --git a/dev-tools/mage/config.go b/dev-tools/mage/config.go index 35cebcf759e..2c9763aa851 100644 --- a/dev-tools/mage/config.go +++ b/dev-tools/mage/config.go @@ -7,7 +7,6 @@ package mage import ( "bytes" "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -159,7 +158,7 @@ func makeConfigTemplate(destination string, mode os.FileMode, confParams ConfigF } } - data, err := ioutil.ReadFile(confFile.Template) + data, err := os.ReadFile(confFile.Template) if err != nil { return errors.Wrapf(err, "failed to read config template %q", confFile.Template) } diff --git a/dev-tools/mage/copy.go b/dev-tools/mage/copy.go index 4cb121fc2ad..f3daef703f3 100644 --- a/dev-tools/mage/copy.go +++ b/dev-tools/mage/copy.go @@ -5,8 +5,9 @@ package mage import ( + "fmt" "io" - "io/ioutil" + "io/fs" "os" "path/filepath" "regexp" @@ -41,7 +42,7 @@ func (t *CopyTask) Execute() error { return errors.Wrapf(err, "copy failed: cannot stat source file %v", t.Source) } - return errors.Wrap(t.recursiveCopy(t.Source, t.Dest, info), "copy failed") + return errors.Wrap(t.recursiveCopy(t.Source, t.Dest, fs.FileInfoToDirEntry(info)), "copy failed") } func (t *CopyTask) init() error { @@ -64,14 +65,14 @@ func (t *CopyTask) isExcluded(src string) bool { return false } -func (t *CopyTask) recursiveCopy(src, dest string, info os.FileInfo) error { - if info.IsDir() { - return t.dirCopy(src, dest, info) +func (t *CopyTask) recursiveCopy(src, dest string, entry fs.DirEntry) error { + if entry.IsDir() { + return t.dirCopy(src, dest, entry) } - return t.fileCopy(src, dest, info) + return t.fileCopy(src, dest, entry) } -func (t *CopyTask) fileCopy(src, dest string, info os.FileInfo) error { +func (t *CopyTask) fileCopy(src, dest string, entry fs.DirEntry) error { if t.isExcluded(src) { return nil } @@ -82,6 +83,11 @@ func (t *CopyTask) fileCopy(src, dest string, info os.FileInfo) error { } defer srcFile.Close() + info, err := entry.Info() + if err != nil { + return fmt.Errorf("converting dir entry: %w", err) + } + if !info.Mode().IsRegular() { return errors.Errorf("failed to copy source file because it is not a " + "regular file") @@ -104,28 +110,34 @@ func (t *CopyTask) fileCopy(src, dest string, info os.FileInfo) error { return destFile.Close() } -func (t *CopyTask) dirCopy(src, dest string, info os.FileInfo) error { +func (t *CopyTask) dirCopy(src, dest string, entry fs.DirEntry) error { if t.isExcluded(src) { return nil } + info, err := entry.Info() + if err != nil { + return fmt.Errorf("converting dir entry: %w", err) + } + mode := t.DirMode if mode == 0 { mode = info.Mode() } + if err := os.MkdirAll(dest, mode&os.ModePerm); err != nil { return errors.Wrap(err, "failed creating dirs") } - contents, err := ioutil.ReadDir(src) + contents, err := os.ReadDir(src) if err != nil { return errors.Wrapf(err, "failed to read dir %v", src) } - for _, info := range contents { + for _, entry := range contents { srcFile := filepath.Join(src, info.Name()) destFile := filepath.Join(dest, info.Name()) - if err = t.recursiveCopy(srcFile, destFile, info); err != nil { + if err = t.recursiveCopy(srcFile, destFile, entry); err != nil { return errors.Wrapf(err, "failed to copy %v to %v", srcFile, destFile) } } diff --git a/dev-tools/mage/gotest.go b/dev-tools/mage/gotest.go index 0583306e59a..3a99f2edd3d 100644 --- a/dev-tools/mage/gotest.go +++ b/dev-tools/mage/gotest.go @@ -10,7 +10,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "log" "os" "os/exec" @@ -126,14 +125,14 @@ func DefaultTestBinaryArgs() TestBinaryArgs { // Use MODULE=module to run only tests for `module`. func GoTestIntegrationForModule(ctx context.Context) error { module := EnvOr("MODULE", "") - modulesFileInfo, err := ioutil.ReadDir("./module") + modulesDirEntry, err := os.ReadDir("./module") if err != nil { return err } foundModule := false failedModules := []string{} - for _, fi := range modulesFileInfo { + for _, fi := range modulesDirEntry { if !fi.IsDir() { continue } @@ -327,7 +326,7 @@ func GoTest(ctx context.Context, params GoTestArgs) error { codecovReport = strings.TrimSuffix(params.CoverageProfileFile, filepath.Ext(params.CoverageProfileFile)) + "-cov.xml" - coverage, err := ioutil.ReadFile(params.CoverageProfileFile) + coverage, err := os.ReadFile(params.CoverageProfileFile) if err != nil { return fmt.Errorf("failed to read code coverage report: %w", err) } @@ -364,7 +363,7 @@ func makeCommand(ctx context.Context, env map[string]string, cmd string, args .. for k, v := range env { c.Env = append(c.Env, k+"="+v) } - c.Stdout = ioutil.Discard + c.Stdout = io.Discard if mg.Verbose() { c.Stdout = os.Stdout } diff --git a/dev-tools/mage/integtest_docker.go b/dev-tools/mage/integtest_docker.go index c08e5ba9b52..81c8716dcfc 100644 --- a/dev-tools/mage/integtest_docker.go +++ b/dev-tools/mage/integtest_docker.go @@ -7,7 +7,7 @@ package mage import ( "fmt" "go/build" - "io/ioutil" + "io" "os" "path" "path/filepath" @@ -138,14 +138,14 @@ func (d *DockerIntegrationTester) Test(dir string, mageTarget string, env map[st } // Docker-compose rm is noisy. So only pass through stderr when in verbose. - out := ioutil.Discard + out := io.Discard if mg.Verbose() { out = os.Stderr } _, err = sh.Exec( composeEnv, - ioutil.Discard, + io.Discard, out, "docker-compose", "-p", dockerComposeProjectName(), @@ -266,7 +266,7 @@ func dockerComposeBuildImages() error { args = append(args, "--pull") } - out := ioutil.Discard + out := io.Discard if mg.Verbose() { out = os.Stderr } diff --git a/dev-tools/mage/kubernetes/kind.go b/dev-tools/mage/kubernetes/kind.go index 7d8f0f47e52..957024e0e05 100644 --- a/dev-tools/mage/kubernetes/kind.go +++ b/dev-tools/mage/kubernetes/kind.go @@ -6,7 +6,7 @@ package kubernetes import ( "fmt" - "io/ioutil" + "io" "os" "os/exec" "path/filepath" @@ -53,8 +53,8 @@ func (m *KindIntegrationTestStep) Setup(env map[string]string) error { } clusterName := kubernetesClusterName() - stdOut := ioutil.Discard - stdErr := ioutil.Discard + stdOut := io.Discard + stdErr := io.Discard if mg.Verbose() { stdOut = os.Stdout stdErr = os.Stderr @@ -103,8 +103,8 @@ func (m *KindIntegrationTestStep) Setup(env map[string]string) error { // Teardown destroys the kubernetes cluster. func (m *KindIntegrationTestStep) Teardown(env map[string]string) error { - stdOut := ioutil.Discard - stdErr := ioutil.Discard + stdOut := io.Discard + stdErr := io.Discard if mg.Verbose() { stdOut = os.Stdout stdErr = os.Stderr diff --git a/dev-tools/mage/kubernetes/kuberemote.go b/dev-tools/mage/kubernetes/kuberemote.go index 8f027820971..4c6ad6fdcdf 100644 --- a/dev-tools/mage/kubernetes/kuberemote.go +++ b/dev-tools/mage/kubernetes/kuberemote.go @@ -14,10 +14,10 @@ import ( "encoding/pem" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" + "os" "os/exec" "strings" "time" @@ -610,7 +610,7 @@ func podDone(event watch.Event) (bool, error) { func createTempFile(content []byte) (string, error) { randBytes := make([]byte, 16) rand.Read(randBytes) - tmpfile, err := ioutil.TempFile("", hex.EncodeToString(randBytes)) + tmpfile, err := os.CreateTemp("", hex.EncodeToString(randBytes)) if err != nil { return "", err } diff --git a/dev-tools/mage/kubernetes/kubernetes.go b/dev-tools/mage/kubernetes/kubernetes.go index fc0feea6fab..f8a6f7c8a0a 100644 --- a/dev-tools/mage/kubernetes/kubernetes.go +++ b/dev-tools/mage/kubernetes/kubernetes.go @@ -7,7 +7,6 @@ package kubernetes import ( "fmt" "io" - "io/ioutil" "log" "os" "path/filepath" @@ -58,8 +57,8 @@ func (d *IntegrationTester) StepRequirements() mage.IntegrationTestSteps { // Test performs the tests with kubernetes. func (d *IntegrationTester) Test(dir string, mageTarget string, env map[string]string) error { - stdOut := ioutil.Discard - stdErr := ioutil.Discard + stdOut := io.Discard + stdErr := io.Discard if mg.Verbose() { stdOut = os.Stdout stdErr = os.Stderr diff --git a/dev-tools/mage/pkgspecs.go b/dev-tools/mage/pkgspecs.go index e03a6ff303b..c3450c8525f 100644 --- a/dev-tools/mage/pkgspecs.go +++ b/dev-tools/mage/pkgspecs.go @@ -7,8 +7,8 @@ package mage import ( "bytes" "fmt" - "io/ioutil" "log" + "os" "path/filepath" "gopkg.in/yaml.v2" @@ -138,7 +138,7 @@ func LoadNamedSpec(name string, files ...string) error { func LoadSpecs(files ...string) (map[string][]OSPackageArgs, error) { var data [][]byte for _, file := range files { - d, err := ioutil.ReadFile(file) + d, err := os.ReadFile(file) if err != nil { return nil, fmt.Errorf("failed to read from spec file: %w", err) } diff --git a/dev-tools/mage/pkgtypes.go b/dev-tools/mage/pkgtypes.go index 0d63efbef95..e446c90b47a 100644 --- a/dev-tools/mage/pkgtypes.go +++ b/dev-tools/mage/pkgtypes.go @@ -11,7 +11,6 @@ import ( "compress/gzip" "fmt" "io" - "io/ioutil" "log" "os" "path/filepath" @@ -434,7 +433,7 @@ func (s PackageSpec) Evaluate(args ...map[string]interface{}) PackageSpec { } f.Source = filepath.Join(s.packageDir, filepath.Base(f.Target)) - if err = ioutil.WriteFile(CreateDir(f.Source), []byte(content), 0644); err != nil { + if err = os.WriteFile(CreateDir(f.Source), []byte(content), 0644); err != nil { panic(fmt.Errorf("failed to write file containing content for target=%v: %w", target, err)) } case f.Template != "": @@ -575,7 +574,7 @@ func PackageZip(spec PackageSpec) error { spec.OutputFile = Zip.AddFileExtension(spec.OutputFile) // Write the zip file. - if err := ioutil.WriteFile(CreateDir(spec.OutputFile), buf.Bytes(), 0644); err != nil { + if err := os.WriteFile(CreateDir(spec.OutputFile), buf.Bytes(), 0644); err != nil { return fmt.Errorf("failed to write zip file: %w", err) } @@ -638,7 +637,7 @@ func PackageTarGz(spec PackageSpec) error { continue } - tmpdir, err := ioutil.TempDir("", "TmpSymlinkDropPath") + tmpdir, err := os.MkdirTemp("", "TmpSymlinkDropPath") if err != nil { return err } diff --git a/dev-tools/mage/settings.go b/dev-tools/mage/settings.go index d4c6081e597..cb033312c36 100644 --- a/dev-tools/mage/settings.go +++ b/dev-tools/mage/settings.go @@ -8,7 +8,6 @@ import ( "errors" "fmt" "go/build" - "io/ioutil" "log" "os" "path/filepath" @@ -516,7 +515,7 @@ func (s *BuildVariableSources) GetBeatVersion() (string, error) { return "", err } - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { return "", fmt.Errorf("failed to read beat version file=%v: %w", file, err) } @@ -534,7 +533,7 @@ func (s *BuildVariableSources) GetGoVersion() (string, error) { return "", err } - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { return "", fmt.Errorf("failed to read go version file=%v: %w", file, err) } @@ -552,7 +551,7 @@ func (s *BuildVariableSources) GetDocBranch() (string, error) { return "", err } - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { return "", fmt.Errorf("failed to read doc branch file=%v: %w", file, err) } diff --git a/internal/pkg/agent/application/actions/handlers/handler_action_policy_change.go b/internal/pkg/agent/application/actions/handlers/handler_action_policy_change.go index 25d7b2bdd4e..c4f2c10dc96 100644 --- a/internal/pkg/agent/application/actions/handlers/handler_action_policy_change.go +++ b/internal/pkg/agent/application/actions/handlers/handler_action_policy_change.go @@ -9,7 +9,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "net/http" "sort" "time" @@ -198,7 +197,7 @@ func (h *PolicyChangeHandler) handleFleetServerHosts(ctx context.Context, c *con } // discard body for proper cancellation and connection reuse - _, _ = io.Copy(ioutil.Discard, resp.Body) + _, _ = io.Copy(io.Discard, resp.Body) resp.Body.Close() reader, err := fleetToReader(h.agentInfo, h.config) diff --git a/internal/pkg/agent/application/filelock/locker_test.go b/internal/pkg/agent/application/filelock/locker_test.go index 1b7f764fb71..51191e6c0ea 100644 --- a/internal/pkg/agent/application/filelock/locker_test.go +++ b/internal/pkg/agent/application/filelock/locker_test.go @@ -5,7 +5,6 @@ package filelock import ( - "io/ioutil" "os" "testing" @@ -16,7 +15,7 @@ import ( const testLockFile = "test.lock" func TestAppLocker(t *testing.T) { - tmp, _ := ioutil.TempDir("", "locker") + tmp, _ := os.MkdirTemp("", "locker") defer os.RemoveAll(tmp) locker1 := NewAppLocker(tmp, testLockFile) diff --git a/internal/pkg/agent/application/gateway/fleet/fleet_gateway_test.go b/internal/pkg/agent/application/gateway/fleet/fleet_gateway_test.go index de40565c0b5..4c28aa8c0b2 100644 --- a/internal/pkg/agent/application/gateway/fleet/fleet_gateway_test.go +++ b/internal/pkg/agent/application/gateway/fleet/fleet_gateway_test.go @@ -11,7 +11,6 @@ import ( "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -115,7 +114,7 @@ func wrapStrToResp(code int, body string) *http.Response { Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, - Body: ioutil.NopCloser(bytes.NewBufferString(body)), + Body: io.NopCloser(bytes.NewBufferString(body)), ContentLength: int64(len(body)), Header: make(http.Header), } @@ -499,7 +498,7 @@ func runFleetGateway(ctx context.Context, g coordinator.FleetGateway) <-chan err } func newStateStore(t *testing.T, log *logger.Logger) *store.StateStore { - dir, err := ioutil.TempDir("", "fleet-gateway-unit-test") + dir, err := os.MkdirTemp("", "fleet-gateway-unit-test") require.NoError(t, err) filename := filepath.Join(dir, "state.enc") diff --git a/internal/pkg/agent/application/monitoring/process.go b/internal/pkg/agent/application/monitoring/process.go index f89597c6d03..dc969553d09 100644 --- a/internal/pkg/agent/application/monitoring/process.go +++ b/internal/pkg/agent/application/monitoring/process.go @@ -8,7 +8,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "strings" "syscall" @@ -174,7 +174,7 @@ func processMetrics(ctx context.Context, endpoint, path string) ([]byte, int, er } defer resp.Body.Close() - rb, err := ioutil.ReadAll(resp.Body) + rb, err := io.ReadAll(resp.Body) if err != nil { return nil, 0, errorWithStatus(http.StatusInternalServerError, err) } diff --git a/internal/pkg/agent/application/upgrade/artifact/download/headers_rtt_test.go b/internal/pkg/agent/application/upgrade/artifact/download/headers_rtt_test.go index 28fbf53b61e..9dfd1b252ae 100644 --- a/internal/pkg/agent/application/upgrade/artifact/download/headers_rtt_test.go +++ b/internal/pkg/agent/application/upgrade/artifact/download/headers_rtt_test.go @@ -6,7 +6,7 @@ package download import ( "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -31,7 +31,7 @@ func TestAddingHeaders(t *testing.T) { c.Transport = rtt resp, err := c.Get(server.URL) require.NoError(t, err) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) defer resp.Body.Close() require.NoError(t, err) assert.Equal(t, b, msg) diff --git a/internal/pkg/agent/application/upgrade/artifact/download/http/downloader_test.go b/internal/pkg/agent/application/upgrade/artifact/download/http/downloader_test.go index d8c6e2a9304..2faf2159876 100644 --- a/internal/pkg/agent/application/upgrade/artifact/download/http/downloader_test.go +++ b/internal/pkg/agent/application/upgrade/artifact/download/http/downloader_test.go @@ -9,7 +9,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "net" "net/http" "net/http/httptest" @@ -36,7 +35,7 @@ import ( ) func TestDownload(t *testing.T) { - targetDir, err := ioutil.TempDir(os.TempDir(), "") + targetDir, err := os.MkdirTemp(os.TempDir(), "") if err != nil { t.Fatal(err) } @@ -98,7 +97,7 @@ func TestDownloadBodyError(t *testing.T) { defer srv.Close() client := srv.Client() - targetDir, err := ioutil.TempDir(os.TempDir(), "") + targetDir, err := os.MkdirTemp(os.TempDir(), "") if err != nil { t.Fatal(err) } @@ -152,7 +151,7 @@ func TestDownloadLogProgressWithLength(t *testing.T) { defer srv.Close() client := srv.Client() - targetDir, err := ioutil.TempDir(os.TempDir(), "") + targetDir, err := os.MkdirTemp(os.TempDir(), "") if err != nil { t.Fatal(err) } @@ -235,7 +234,7 @@ func TestDownloadLogProgressWithoutLength(t *testing.T) { defer srv.Close() client := srv.Client() - targetDir, err := ioutil.TempDir(os.TempDir(), "") + targetDir, err := os.MkdirTemp(os.TempDir(), "") if err != nil { t.Fatal(err) } diff --git a/internal/pkg/agent/application/upgrade/artifact/download/http/verifier.go b/internal/pkg/agent/application/upgrade/artifact/download/http/verifier.go index 5197f931285..587b968ff66 100644 --- a/internal/pkg/agent/application/upgrade/artifact/download/http/verifier.go +++ b/internal/pkg/agent/application/upgrade/artifact/download/http/verifier.go @@ -7,7 +7,7 @@ package http import ( "context" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "os" @@ -182,5 +182,5 @@ func (v *Verifier) getPublicAsc(sourceURI string) ([]byte, error) { return nil, errors.New(fmt.Sprintf("call to '%s' returned unsuccessful status code: %d", sourceURI, resp.StatusCode), errors.TypeNetwork, errors.M(errors.MetaKeyURI, sourceURI)) } - return ioutil.ReadAll(resp.Body) + return io.ReadAll(resp.Body) } diff --git a/internal/pkg/agent/application/upgrade/artifact/download/verifier.go b/internal/pkg/agent/application/upgrade/artifact/download/verifier.go index e466c0119ea..991ab9ce16c 100644 --- a/internal/pkg/agent/application/upgrade/artifact/download/verifier.go +++ b/internal/pkg/agent/application/upgrade/artifact/download/verifier.go @@ -12,7 +12,6 @@ import ( "encoding/hex" "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -313,7 +312,7 @@ func fetchPgpFromURI(uri string, client HTTPClient) ([]byte, error) { return nil, errors.New(fmt.Sprintf("call to '%s' returned unsuccessful status code: %d", uri, resp.StatusCode), errors.TypeNetwork, errors.M(errors.MetaKeyURI, uri)) } - return ioutil.ReadAll(resp.Body) + return io.ReadAll(resp.Body) } type HTTPClient interface { diff --git a/internal/pkg/agent/application/upgrade/step_mark.go b/internal/pkg/agent/application/upgrade/step_mark.go index bca67d307f0..90bc11dfda6 100644 --- a/internal/pkg/agent/application/upgrade/step_mark.go +++ b/internal/pkg/agent/application/upgrade/step_mark.go @@ -6,7 +6,6 @@ package upgrade import ( "context" - "io/ioutil" "os" "path/filepath" "time" @@ -129,7 +128,7 @@ func (u *Upgrader) markUpgrade(_ context.Context, log *logger.Logger, hash strin markerPath := markerFilePath() log.Infow("Writing upgrade marker file", "file.path", markerPath, "hash", marker.Hash, "prev_hash", prevHash) - if err := ioutil.WriteFile(markerPath, markerBytes, 0600); err != nil { + if err := os.WriteFile(markerPath, markerBytes, 0600); err != nil { return errors.New(err, errors.TypeFilesystem, "failed to create update marker file", errors.M(errors.MetaKeyPath, markerPath)) } @@ -144,7 +143,7 @@ func (u *Upgrader) markUpgrade(_ context.Context, log *logger.Logger, hash strin func UpdateActiveCommit(log *logger.Logger, hash string) error { activeCommitPath := filepath.Join(paths.Top(), agentCommitFile) log.Infow("Updating active commit", "file.path", activeCommitPath, "hash", hash) - if err := ioutil.WriteFile(activeCommitPath, []byte(hash), 0600); err != nil { + if err := os.WriteFile(activeCommitPath, []byte(hash), 0600); err != nil { return errors.New(err, errors.TypeFilesystem, "failed to update active commit", errors.M(errors.MetaKeyPath, activeCommitPath)) } diff --git a/internal/pkg/agent/application/upgrade/upgrade_test.go b/internal/pkg/agent/application/upgrade/upgrade_test.go index d0e3f756ab4..57230fdedbe 100644 --- a/internal/pkg/agent/application/upgrade/upgrade_test.go +++ b/internal/pkg/agent/application/upgrade/upgrade_test.go @@ -8,7 +8,6 @@ import ( "context" "crypto/tls" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -112,7 +111,7 @@ func Test_CopyFile(t *testing.T) { func TestShutdownCallback(t *testing.T) { l, _ := logger.New("test", false) - tmpDir, err := ioutil.TempDir("", "shutdown-test-") + tmpDir, err := os.MkdirTemp("", "shutdown-test-") require.NoError(t, err) defer os.RemoveAll(tmpDir) @@ -135,14 +134,14 @@ func TestShutdownCallback(t *testing.T) { cb := shutdownCallback(l, homePath, sourceVersion, targetVersion, newCommit) oldFilename := filepath.Join(sourceDir, filename) - err = ioutil.WriteFile(oldFilename, content, 0640) + err = os.WriteFile(oldFilename, content, 0640) require.NoError(t, err, "preparing file failed") err = cb() require.NoError(t, err, "callback failed") newFilename := filepath.Join(targetDir, filename) - newContent, err := ioutil.ReadFile(newFilename) + newContent, err := os.ReadFile(newFilename) require.NoError(t, err, "reading file failed") require.Equal(t, content, newContent, "contents are not equal") } diff --git a/internal/pkg/agent/cleaner/cleaner_test.go b/internal/pkg/agent/cleaner/cleaner_test.go index cf189b784d3..f242f8fc257 100644 --- a/internal/pkg/agent/cleaner/cleaner_test.go +++ b/internal/pkg/agent/cleaner/cleaner_test.go @@ -6,7 +6,6 @@ package cleaner import ( "context" - "io/ioutil" "os" "path/filepath" "testing" @@ -31,14 +30,14 @@ func TestCleaner(t *testing.T) { checkDir(t, dir, 0) // Create files - err := ioutil.WriteFile(watchFilePath, []byte{}, 0600) + err := os.WriteFile(watchFilePath, []byte{}, 0600) if err != nil { t.Fatal(err) } for i, fn := range removeFiles { removeFilePaths[i] = filepath.Join(dir, fn) - err := ioutil.WriteFile(removeFilePaths[i], []byte{}, 0600) + err := os.WriteFile(removeFilePaths[i], []byte{}, 0600) if err != nil { t.Fatal(err) } diff --git a/internal/pkg/agent/cmd/component_spec.go b/internal/pkg/agent/cmd/component_spec.go index 1025e488b42..96eebeb123a 100644 --- a/internal/pkg/agent/cmd/component_spec.go +++ b/internal/pkg/agent/cmd/component_spec.go @@ -6,7 +6,7 @@ package cmd import ( "fmt" - "io/ioutil" + "os" "github.com/spf13/cobra" @@ -22,7 +22,7 @@ func newComponentSpecCommandWithArgs(_ []string, streams *cli.IOStreams) *cobra. Long: "Validates a component specification that instructs the Elastic Agent how it should be ran.", Args: cobra.ExactArgs(1), RunE: func(c *cobra.Command, args []string) error { - data, err := ioutil.ReadFile(args[0]) + data, err := os.ReadFile(args[0]) if err != nil { return err } diff --git a/internal/pkg/agent/cmd/upgrade.go b/internal/pkg/agent/cmd/upgrade.go index 767560f873f..6c33fa43498 100644 --- a/internal/pkg/agent/cmd/upgrade.go +++ b/internal/pkg/agent/cmd/upgrade.go @@ -7,7 +7,6 @@ package cmd import ( "context" "fmt" - "io/ioutil" "os" "github.com/spf13/cobra" @@ -80,7 +79,7 @@ func upgradeCmd(streams *cli.IOStreams, cmd *cobra.Command, args []string) error // get local PGP pgpPath, _ := cmd.Flags().GetString(flagPGPBytesPath) if len(pgpPath) > 0 { - content, err := ioutil.ReadFile(pgpPath) + content, err := os.ReadFile(pgpPath) if err != nil { return errors.New(err, "failed to read pgp file") } diff --git a/internal/pkg/agent/storage/encrypted_disk_storage_windows_linux_test.go b/internal/pkg/agent/storage/encrypted_disk_storage_windows_linux_test.go index c29c7ec8fd9..83d0106d308 100644 --- a/internal/pkg/agent/storage/encrypted_disk_storage_windows_linux_test.go +++ b/internal/pkg/agent/storage/encrypted_disk_storage_windows_linux_test.go @@ -10,8 +10,8 @@ import ( "bytes" "context" "errors" + "io" "io/fs" - "io/ioutil" "os" "path/filepath" "testing" @@ -42,7 +42,7 @@ func TestEncryptedDiskStorageWindowsLinuxLoad(t *testing.T) { } defer r.Close() - b, err := ioutil.ReadAll(r) + b, err := io.ReadAll(r) if err != nil { t.Fatal(err) } @@ -99,7 +99,7 @@ func TestEncryptedDiskStorageWindowsLinuxLoad(t *testing.T) { } defer nr.Close() - b, err = ioutil.ReadAll(nr) + b, err = io.ReadAll(nr) if err != nil { t.Fatal(err) } diff --git a/internal/pkg/agent/storage/replace_store.go b/internal/pkg/agent/storage/replace_store.go index 5c166613d9f..fa495f9dc1e 100644 --- a/internal/pkg/agent/storage/replace_store.go +++ b/internal/pkg/agent/storage/replace_store.go @@ -8,7 +8,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "time" @@ -43,7 +42,7 @@ func NewReplaceOnSuccessStore(target string, replaceWith []byte, wrapped Store) // Save will replace a target file with new content if the wrapped store is successful. func (r *ReplaceOnSuccessStore) Save(in io.Reader) error { // Ensure we can read the target files before delegating any call to the wrapped store. - target, err := ioutil.ReadFile(r.target) + target, err := os.ReadFile(r.target) if err != nil { return errors.New(err, fmt.Sprintf("fail to read content of %s", r.target), diff --git a/internal/pkg/agent/storage/storage_test.go b/internal/pkg/agent/storage/storage_test.go index 52cd1960b22..98f11a772e0 100644 --- a/internal/pkg/agent/storage/storage_test.go +++ b/internal/pkg/agent/storage/storage_test.go @@ -8,7 +8,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "path/filepath" "runtime" @@ -45,7 +44,7 @@ func TestReplaceOrRollbackStore(t *testing.T) { err = s.Save(in) require.NoError(t, err) - writtenContent, err := ioutil.ReadFile(target) + writtenContent, err := os.ReadFile(target) require.NoError(t, err) require.True(t, bytes.Equal(writtenContent, replaceWith)) @@ -70,7 +69,7 @@ func TestReplaceOrRollbackStore(t *testing.T) { err = s.Save(in) require.Error(t, err) - writtenContent, err := ioutil.ReadFile(target) + writtenContent, err := os.ReadFile(target) require.NoError(t, err) require.True(t, bytes.Equal(writtenContent, oldContent)) @@ -94,7 +93,7 @@ func TestReplaceOrRollbackStore(t *testing.T) { err = s.Save(in) require.Error(t, err) - writtenContent, err := ioutil.ReadFile(target) + writtenContent, err := os.ReadFile(target) require.NoError(t, err) require.True(t, bytes.Equal(writtenContent, replaceWith)) @@ -124,7 +123,7 @@ func TestDiskStore(t *testing.T) { err = d.Save(bytes.NewReader(msg)) require.NoError(t, err) - content, err := ioutil.ReadFile(target) + content, err := os.ReadFile(target) require.NoError(t, err) require.Equal(t, msg, content) @@ -132,7 +131,7 @@ func TestDiskStore(t *testing.T) { }) t.Run("when the target do no exist", func(t *testing.T) { - dir, err := ioutil.TempDir("", "configs") + dir, err := os.MkdirTemp("", "configs") require.NoError(t, err) defer os.Remove(dir) @@ -143,7 +142,7 @@ func TestDiskStore(t *testing.T) { err = d.Save(bytes.NewReader(msg)) require.NoError(t, err) - content, err := ioutil.ReadFile(target) + content, err := os.ReadFile(target) require.NoError(t, err) require.Equal(t, msg, content) @@ -160,7 +159,7 @@ func TestDiskStore(t *testing.T) { require.NoError(t, err) defer r.Close() - content, err := ioutil.ReadAll(r) + content, err := io.ReadAll(r) require.NoError(t, err) require.Equal(t, msg, content) checkPerms(t, target, perms) @@ -168,12 +167,12 @@ func TestDiskStore(t *testing.T) { } func genFile(b []byte) (string, error) { - dir, err := ioutil.TempDir("", "configs") + dir, err := os.MkdirTemp("", "configs") if err != nil { return "", err } - f, err := ioutil.TempFile(dir, "config-") + f, err := os.CreateTemp(dir, "config-") if err != nil { return "", err } @@ -187,7 +186,7 @@ func genFile(b []byte) (string, error) { } func requireFilesCount(t *testing.T, dir string, l int) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) require.NoError(t, err) require.Equal(t, l, len(files)) } diff --git a/internal/pkg/agent/storage/store/action_store_test.go b/internal/pkg/agent/storage/store/action_store_test.go index e193183ab22..5a5d56b8056 100644 --- a/internal/pkg/agent/storage/store/action_store_test.go +++ b/internal/pkg/agent/storage/store/action_store_test.go @@ -5,7 +5,6 @@ package store import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -21,7 +20,7 @@ func TestActionStore(t *testing.T) { log, _ := logger.New("action_store", false) withFile := func(fn func(t *testing.T, file string)) func(*testing.T) { return func(t *testing.T) { - dir, err := ioutil.TempDir("", "action-store") + dir, err := os.MkdirTemp("", "action-store") require.NoError(t, err) defer os.RemoveAll(dir) file := filepath.Join(dir, "config.yml") diff --git a/internal/pkg/agent/vault/seed.go b/internal/pkg/agent/vault/seed.go index 6112e48313e..50c96a4a715 100644 --- a/internal/pkg/agent/vault/seed.go +++ b/internal/pkg/agent/vault/seed.go @@ -10,7 +10,6 @@ import ( "errors" "fmt" "io/fs" - "io/ioutil" "os" "path/filepath" "sync" @@ -32,7 +31,7 @@ func getSeed(path string) ([]byte, error) { mxSeed.Lock() defer mxSeed.Unlock() - b, err := ioutil.ReadFile(fp) + b, err := os.ReadFile(fp) if err != nil { return nil, fmt.Errorf("could not read seed file: %w", err) } @@ -50,7 +49,7 @@ func createSeedIfNotExists(path string) ([]byte, error) { mxSeed.Lock() defer mxSeed.Unlock() - b, err := ioutil.ReadFile(fp) + b, err := os.ReadFile(fp) if err != nil { if !errors.Is(err, os.ErrNotExist) { return nil, err @@ -66,7 +65,7 @@ func createSeedIfNotExists(path string) ([]byte, error) { return nil, err } - err = ioutil.WriteFile(fp, seed, 0600) + err = os.WriteFile(fp, seed, 0600) if err != nil { return nil, err } diff --git a/internal/pkg/basecmd/version/cmd_test.go b/internal/pkg/basecmd/version/cmd_test.go index 2959c576183..93ed88101e2 100644 --- a/internal/pkg/basecmd/version/cmd_test.go +++ b/internal/pkg/basecmd/version/cmd_test.go @@ -5,7 +5,7 @@ package version import ( - "io/ioutil" + "io" "strings" "testing" @@ -30,7 +30,7 @@ func TestCmdBinaryOnly(t *testing.T) { require.NoError(t, err) err = cmd.Execute() require.NoError(t, err) - version, err := ioutil.ReadAll(out) + version, err := io.ReadAll(out) require.NoError(t, err) assert.True(t, strings.Contains(string(version), "Binary: ")) @@ -46,7 +46,7 @@ func TestCmdBinaryOnlyYAML(t *testing.T) { require.NoError(t, err) err = cmd.Execute() require.NoError(t, err) - version, err := ioutil.ReadAll(out) + version, err := io.ReadAll(out) require.NoError(t, err) @@ -67,7 +67,7 @@ func TestCmdDaemon(t *testing.T) { cmd := NewCommandWithArgs(streams) err := cmd.Execute() require.NoError(t, err) - version, err := ioutil.ReadAll(out) + version, err := io.ReadAll(out) require.NoError(t, err) assert.True(t, strings.Contains(string(version), "Binary: ")) @@ -85,7 +85,7 @@ func TestCmdDaemonYAML(t *testing.T) { require.NoError(t, err) err = cmd.Execute() require.NoError(t, err) - version, err := ioutil.ReadAll(out) + version, err := io.ReadAll(out) require.NoError(t, err) @@ -103,7 +103,7 @@ func TestCmdDaemonErr(t *testing.T) { cmd := NewCommandWithArgs(streams) err := cmd.Execute() require.Error(t, err) - version, err := ioutil.ReadAll(out) + version, err := io.ReadAll(out) require.NoError(t, err) assert.True(t, strings.Contains(string(version), "Binary: ")) @@ -118,7 +118,7 @@ func TestCmdDaemonErrYAML(t *testing.T) { require.NoError(t, err) err = cmd.Execute() require.Error(t, err) - version, err := ioutil.ReadAll(out) + version, err := io.ReadAll(out) require.NoError(t, err) var output Output diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index d9b5d956618..05e0dd02c76 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -7,7 +7,6 @@ package config import ( "fmt" "io" - "io/ioutil" "os" "gopkg.in/yaml.v2" @@ -74,7 +73,7 @@ func NewConfigFrom(from interface{}, opts ...interface{}) (*Config, error) { if closer, ok := from.(io.Closer); ok { defer closer.Close() } - fData, err := ioutil.ReadAll(in) + fData, err := io.ReadAll(in) if err != nil { return nil, err } diff --git a/internal/pkg/crypto/io_test.go b/internal/pkg/crypto/io_test.go index 1e3bd24685f..57daafe4bf2 100644 --- a/internal/pkg/crypto/io_test.go +++ b/internal/pkg/crypto/io_test.go @@ -8,7 +8,6 @@ import ( "bufio" "bytes" "io" - "io/ioutil" "testing" "github.com/stretchr/testify/require" @@ -34,7 +33,7 @@ func TestIO(t *testing.T) { r, err := NewReaderWithDefaults(dest, passwd) require.NoError(t, err) - content, err := ioutil.ReadAll(r) + content, err := io.ReadAll(r) require.NoError(t, err) require.Equal(t, msg, content) @@ -61,7 +60,7 @@ func TestIO(t *testing.T) { r, err := NewReaderWithDefaults(dest, passwd) require.NoError(t, err) - content, err := ioutil.ReadAll(r) + content, err := io.ReadAll(r) require.NoError(t, err) require.Equal(t, msg, content) @@ -86,7 +85,7 @@ func TestIO(t *testing.T) { r, err := NewReaderWithDefaults(dest, []byte("bad password")) require.NoError(t, err) - _, err = ioutil.ReadAll(r) + _, err = io.ReadAll(r) require.Error(t, err) }) @@ -115,7 +114,7 @@ func TestIO(t *testing.T) { r, err := NewReaderWithDefaults(dest, passwd) require.NoError(t, err) - content, err := ioutil.ReadAll(r) + content, err := io.ReadAll(r) require.NoError(t, err) require.Equal(t, msg, content) @@ -143,7 +142,7 @@ func TestIO(t *testing.T) { b := bufio.NewReaderSize(r, 100) - content, err := ioutil.ReadAll(b) + content, err := io.ReadAll(b) require.NoError(t, err) require.Equal(t, msg, content) @@ -159,7 +158,7 @@ func TestIO(t *testing.T) { b := bufio.NewReaderSize(r, 100) - _, err = ioutil.ReadAll(b) + _, err = io.ReadAll(b) require.Error(t, err) }) @@ -188,7 +187,7 @@ func TestIO(t *testing.T) { r, err := NewReaderWithDefaults(dest, passwd) require.NoError(t, err) - content, err := ioutil.ReadAll(r) + content, err := io.ReadAll(r) require.NoError(t, err) require.Equal(t, expected, content) diff --git a/internal/pkg/dir/discover_test.go b/internal/pkg/dir/discover_test.go index 153e94d0304..c4cc03a8c62 100644 --- a/internal/pkg/dir/discover_test.go +++ b/internal/pkg/dir/discover_test.go @@ -5,7 +5,6 @@ package dir import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -59,7 +58,7 @@ func TestDiscover(t *testing.T) { func withFiles(files []string, fn func(dst string, t *testing.T)) func(t *testing.T) { return func(t *testing.T) { - tmp, _ := ioutil.TempDir("", "watch") + tmp, _ := os.MkdirTemp("", "watch") defer os.RemoveAll(tmp) for _, file := range files { diff --git a/internal/pkg/filewatcher/watcher_test.go b/internal/pkg/filewatcher/watcher_test.go index 140376ca197..07dba632012 100644 --- a/internal/pkg/filewatcher/watcher_test.go +++ b/internal/pkg/filewatcher/watcher_test.go @@ -5,7 +5,6 @@ package filewatcher import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -24,7 +23,7 @@ func TestWatch(t *testing.T) { })) t.Run("newly added files are discovered", withWatch(func(t *testing.T, w *Watch) { - tmp, err := ioutil.TempDir("", "watch") + tmp, err := os.MkdirTemp("", "watch") require.NoError(t, err) defer os.RemoveAll(tmp) @@ -43,7 +42,7 @@ func TestWatch(t *testing.T) { })) t.Run("ignore old files", withWatch(func(t *testing.T, w *Watch) { - tmp, err := ioutil.TempDir("", "watch") + tmp, err := os.MkdirTemp("", "watch") require.NoError(t, err) defer os.RemoveAll(tmp) @@ -68,7 +67,7 @@ func TestWatch(t *testing.T) { })) t.Run("can unwatch a watched file", withWatch(func(t *testing.T, w *Watch) { - tmp, err := ioutil.TempDir("", "watch") + tmp, err := os.MkdirTemp("", "watch") require.NoError(t, err) defer os.RemoveAll(tmp) @@ -97,7 +96,7 @@ func TestWatch(t *testing.T) { w.Unwatch(path) // Add new content to the file. - ioutil.WriteFile(path, []byte("heeeelo"), 0644) + os.WriteFile(path, []byte("heeeelo"), 0644) // Should not find the file. r, u, err = w.scan() @@ -107,7 +106,7 @@ func TestWatch(t *testing.T) { })) t.Run("can returns the list of watched files", withWatch(func(t *testing.T, w *Watch) { - tmp, err := ioutil.TempDir("", "watch") + tmp, err := os.MkdirTemp("", "watch") require.NoError(t, err) defer os.RemoveAll(tmp) @@ -125,7 +124,7 @@ func TestWatch(t *testing.T) { })) t.Run("update returns updated, unchanged and watched files", withWatch(func(t *testing.T, w *Watch) { - tmp, err := ioutil.TempDir("", "watch") + tmp, err := os.MkdirTemp("", "watch") require.NoError(t, err) defer os.RemoveAll(tmp) @@ -184,7 +183,7 @@ func TestWatch(t *testing.T) { })) t.Run("should cleanup files that disapear", withWatch(func(t *testing.T, w *Watch) { - tmp, err := ioutil.TempDir("", "watch") + tmp, err := os.MkdirTemp("", "watch") require.NoError(t, err) defer os.RemoveAll(tmp) @@ -201,7 +200,7 @@ func TestWatch(t *testing.T) { })) t.Run("should allow to invalidate the cache ", withWatch(func(t *testing.T, w *Watch) { - tmp, err := ioutil.TempDir("", "watch") + tmp, err := os.MkdirTemp("", "watch") require.NoError(t, err) defer os.RemoveAll(tmp) diff --git a/internal/pkg/fleetapi/ack_cmd.go b/internal/pkg/fleetapi/ack_cmd.go index e5fe956753c..a12839dcb2d 100644 --- a/internal/pkg/fleetapi/ack_cmd.go +++ b/internal/pkg/fleetapi/ack_cmd.go @@ -9,7 +9,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "go.elastic.co/apm" @@ -124,7 +124,7 @@ func (e *AckCmd) Execute(ctx context.Context, r *AckRequest) (_ *AckResponse, er defer resp.Body.Close() // Read ack response always it can be sent with any status code. - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/internal/pkg/fleetapi/acker/fleet/fleet_acker_test.go b/internal/pkg/fleetapi/acker/fleet/fleet_acker_test.go index 6abe28fec72..fcde240fe34 100644 --- a/internal/pkg/fleetapi/acker/fleet/fleet_acker_test.go +++ b/internal/pkg/fleetapi/acker/fleet/fleet_acker_test.go @@ -10,7 +10,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "testing" @@ -64,7 +63,7 @@ func wrapStrToResp(code int, body string) *http.Response { Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, - Body: ioutil.NopCloser(bytes.NewBufferString(body)), + Body: io.NopCloser(bytes.NewBufferString(body)), ContentLength: int64(len(body)), Header: make(http.Header), } diff --git a/internal/pkg/fleetapi/checkin_cmd.go b/internal/pkg/fleetapi/checkin_cmd.go index 4c14454ce18..6f407708b8b 100644 --- a/internal/pkg/fleetapi/checkin_cmd.go +++ b/internal/pkg/fleetapi/checkin_cmd.go @@ -9,7 +9,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "time" @@ -137,7 +137,7 @@ func (e *CheckinCmd) Execute(ctx context.Context, r *CheckinRequest) (*CheckinRe return nil, sendDuration, client.ExtractError(resp.Body) } - rs, err := ioutil.ReadAll(resp.Body) + rs, err := io.ReadAll(resp.Body) if err != nil { return nil, sendDuration, errors.New(err, "failed to read checkin response") } diff --git a/internal/pkg/fleetapi/checkin_cmd_test.go b/internal/pkg/fleetapi/checkin_cmd_test.go index 56726bb5559..46a0b4db4d1 100644 --- a/internal/pkg/fleetapi/checkin_cmd_test.go +++ b/internal/pkg/fleetapi/checkin_cmd_test.go @@ -8,7 +8,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "testing" "time" @@ -214,7 +214,7 @@ func TestCheckin(t *testing.T) { var req *Request - content, err := ioutil.ReadAll(r.Body) + content, err := io.ReadAll(r.Body) assert.NoError(t, err) assert.NoError(t, json.Unmarshal(content, &req)) assert.Equal(t, "linux", req.Metadata.OS.Name) @@ -248,7 +248,7 @@ func TestCheckin(t *testing.T) { var req *Request - content, err := ioutil.ReadAll(r.Body) + content, err := io.ReadAll(r.Body) assert.NoError(t, err) assert.NoError(t, json.Unmarshal(content, &req)) assert.Nil(t, req.Metadata) diff --git a/internal/pkg/fleetapi/client/client.go b/internal/pkg/fleetapi/client/client.go index b6c9f7584ef..cddd162726b 100644 --- a/internal/pkg/fleetapi/client/client.go +++ b/internal/pkg/fleetapi/client/client.go @@ -9,7 +9,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -100,7 +99,7 @@ func ExtractError(resp io.Reader) error { Message string `json:"message"` }{} - data, err := ioutil.ReadAll(resp) + data, err := io.ReadAll(resp) if err != nil { return errors.New(err, "fail to read original error") } diff --git a/internal/pkg/fleetapi/client/client_test.go b/internal/pkg/fleetapi/client/client_test.go index cc5d2501aa8..40be306bc80 100644 --- a/internal/pkg/fleetapi/client/client_test.go +++ b/internal/pkg/fleetapi/client/client_test.go @@ -7,7 +7,7 @@ package client import ( "context" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "strings" @@ -47,7 +47,7 @@ func TestHTTPClient(t *testing.T) { resp, err := client.Send(ctx, "GET", "/echo-hello", nil, nil, nil) require.NoError(t, err) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) defer resp.Body.Close() assert.Equal(t, `{ message: "hello" }`, string(body)) @@ -104,7 +104,7 @@ func TestHTTPClient(t *testing.T) { resp, err := client.Send(ctx, "GET", "/echo-hello", nil, nil, nil) require.NoError(t, err) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) defer resp.Body.Close() assert.Equal(t, `{ message: "hello" }`, string(body)) diff --git a/internal/pkg/remote/client_test.go b/internal/pkg/remote/client_test.go index 892bd5099c5..696121395c8 100644 --- a/internal/pkg/remote/client_test.go +++ b/internal/pkg/remote/client_test.go @@ -8,7 +8,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "strings" @@ -102,7 +102,7 @@ func TestHTTPClient(t *testing.T) { resp, err := client.Send(ctx, http.MethodGet, "/nested/echo-hello", nil, nil, nil) require.NoError(t, err) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) defer resp.Body.Close() assert.Equal(t, successResp, string(body)) @@ -127,7 +127,7 @@ func TestHTTPClient(t *testing.T) { resp, err := client.Send(ctx, http.MethodGet, "/echo-hello", nil, nil, nil) require.NoError(t, err) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) defer resp.Body.Close() assert.Equal(t, successResp, string(body)) @@ -231,7 +231,7 @@ func TestHTTPClient(t *testing.T) { resp, err := client.Send(ctx, http.MethodGet, "/echo-hello", nil, nil, nil) require.NoError(t, err) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) defer resp.Body.Close() assert.Equal(t, successResp, string(body)) @@ -257,7 +257,7 @@ func TestHTTPClient(t *testing.T) { require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) defer resp.Body.Close() assert.Equal(t, successResp, string(body)) @@ -300,7 +300,7 @@ func TestHTTPClient(t *testing.T) { resp, err := client.Send(ctx, http.MethodGet, "/echo-hello", nil, nil, nil) require.NoError(t, err) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) defer resp.Body.Close() assert.Equal(t, successResp, string(body)) @@ -331,7 +331,7 @@ func TestHTTPClient(t *testing.T) { resp, err := client.Send(ctx, http.MethodGet, "/echo-hello", nil, nil, bytes.NewBuffer([]byte("hello"))) require.NoError(t, err) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) defer resp.Body.Close() assert.Equal(t, successResp, string(body)) @@ -363,7 +363,7 @@ func TestHTTPClient(t *testing.T) { resp, err := client.Send(ctx, http.MethodGet, "/echo-hello", nil, nil, nil) require.NoError(t, err) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) defer resp.Body.Close() assert.Equal(t, successResp, string(body)) diff --git a/internal/pkg/remote/round_trippers.go b/internal/pkg/remote/round_trippers.go index e6583af57a8..76c3fec139e 100644 --- a/internal/pkg/remote/round_trippers.go +++ b/internal/pkg/remote/round_trippers.go @@ -8,7 +8,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "strings" "time" @@ -67,13 +67,13 @@ func (r *DebugRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) } if req.Body != nil { - dataReq, err := ioutil.ReadAll(req.Body) + dataReq, err := io.ReadAll(req.Body) if err != nil { return nil, errors.Wrap(err, "fail to read the body of the request") } req.Body.Close() - req.Body = ioutil.NopCloser(bytes.NewBuffer(dataReq)) + req.Body = io.NopCloser(bytes.NewBuffer(dataReq)) b.WriteString("Request Body:\n") b.WriteString(string(prettyBody(dataReq)) + "\n") @@ -101,7 +101,7 @@ func (r *DebugRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) } // Hijack the body and output it in the log, this is only for debugging and development. - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return resp, errors.Wrap(err, "fail to read the body of the response") } @@ -110,7 +110,7 @@ func (r *DebugRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) b.WriteString("Response Body:\n") b.WriteString(string(prettyBody(data)) + "\n") - resp.Body = ioutil.NopCloser(bytes.NewBuffer(data)) + resp.Body = io.NopCloser(bytes.NewBuffer(data)) r.log.Debug(b.String()) diff --git a/pkg/component/load.go b/pkg/component/load.go index 021b42dbb43..39343842dc5 100644 --- a/pkg/component/load.go +++ b/pkg/component/load.go @@ -7,7 +7,6 @@ package component import ( "errors" "fmt" - "io/ioutil" "os" "path/filepath" @@ -196,7 +195,7 @@ func specFilesForDirectory(dir string) (map[string]Spec, error) { return nil, err } for _, match := range matches { - data, err := ioutil.ReadFile(match) + data, err := os.ReadFile(match) if err != nil { return nil, fmt.Errorf("failed reading spec %s: %w", match, err) } diff --git a/pkg/component/load_test.go b/pkg/component/load_test.go index 91a6d1a1be6..1bc4bed8915 100644 --- a/pkg/component/load_test.go +++ b/pkg/component/load_test.go @@ -5,7 +5,7 @@ package component import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -97,7 +97,7 @@ func TestLoadSpec_Components(t *testing.T) { for _, scenario := range scenarios { t.Run(scenario.Name, func(t *testing.T) { - data, err := ioutil.ReadFile(filepath.Join("..", "..", "specs", scenario.Path)) + data, err := os.ReadFile(filepath.Join("..", "..", "specs", scenario.Path)) require.NoError(t, err) _, err = LoadSpec(data) require.NoError(t, err) diff --git a/pkg/packer/packer.go b/pkg/packer/packer.go index 6bec521fe1c..2b220290293 100644 --- a/pkg/packer/packer.go +++ b/pkg/packer/packer.go @@ -10,7 +10,7 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" + "os" "path/filepath" "strings" @@ -33,7 +33,7 @@ func Pack(patterns ...string) (string, []string, error) { return "", []string{}, errors.New(err, fmt.Sprintf("error while reading pattern %s", p)) } for _, f := range files { - b, err := ioutil.ReadFile(f) + b, err := os.ReadFile(f) if err != nil { return "", []string{}, errors.New(err, fmt.Sprintf("cannot read file %s", f)) } diff --git a/pkg/packer/packer_test.go b/pkg/packer/packer_test.go index 253aa8d5e7d..e85d124736c 100644 --- a/pkg/packer/packer_test.go +++ b/pkg/packer/packer_test.go @@ -6,7 +6,6 @@ package packer import ( "crypto/rand" - "io/ioutil" "os" "path/filepath" "reflect" @@ -25,13 +24,13 @@ func TestPacker(t *testing.T) { withFiles := func(test tt, fn func(pattern []string, t *testing.T)) func(t *testing.T) { return func(t *testing.T) { - d, err := ioutil.TempDir("", "packer") + d, err := os.MkdirTemp("", "packer") require.NoError(t, err) defer os.RemoveAll(d) for f, v := range test.content { path := filepath.Join(d, f) - err := ioutil.WriteFile(path, []byte(v), 0666) + err := os.WriteFile(path, []byte(v), 0666) require.NoError(t, err) } diff --git a/pkg/testing/fixture.go b/pkg/testing/fixture.go index 7dc7e06fe74..f6ebe2d565d 100644 --- a/pkg/testing/fixture.go +++ b/pkg/testing/fixture.go @@ -9,7 +9,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -839,7 +838,7 @@ func (f *Fixture) prepareComponents(workDir string, components ...UsableComponen if err != nil { return err } - contents, err := ioutil.ReadDir(componentsDir) + contents, err := os.ReadDir(componentsDir) if err != nil { return fmt.Errorf("failed to read contents of components directory %s: %w", componentsDir, err) } @@ -979,7 +978,7 @@ func getCacheDir(caller string, name string) (string, error) { // FindComponentsDir identifies the directory that holds the components. func FindComponentsDir(dir string) (string, error) { dataDir := filepath.Join(dir, "data") - agentVersions, err := ioutil.ReadDir(dataDir) + agentVersions, err := os.ReadDir(dataDir) if err != nil { return "", fmt.Errorf("failed to read contents of the data directory %s: %w", dataDir, err) }