From 4581279c2c779b48f638a66696a7ff9fae9d49fd Mon Sep 17 00:00:00 2001 From: aram price Date: Thu, 29 Feb 2024 11:53:14 -0800 Subject: [PATCH 1/2] Add golangci-lint workflow --- .github/workflows/go.yml | 14 ++++++++++++++ .golangci.yml | 7 +++++++ 2 files changed, 21 insertions(+) create mode 100644 .github/workflows/go.yml create mode 100644 .golangci.yml diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml new file mode 100644 index 00000000..487b75a1 --- /dev/null +++ b/.github/workflows/go.yml @@ -0,0 +1,14 @@ +name: go +on: + push: + pull_request: +jobs: + lint: + strategy: + matrix: + os: [windows-2019, ubuntu-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + - uses: golangci/golangci-lint-action@v3 diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 00000000..51357d06 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,7 @@ +# https://golangci-lint.run/usage/configuration/ +run: + timeout: 5m # 1m default times out on github-action runners + +output: + # Sort results by: filepath, line and column. + sort-results: true From 582cdae3f91d245aea85c92dd005e3001349e8bd Mon Sep 17 00:00:00 2001 From: aram price Date: Thu, 29 Feb 2024 11:58:03 -0800 Subject: [PATCH 2/2] Address golangci-lint issues - mostly `//nolint:...` - some deprecation fixes --- blobstore/digest_verifiable_blobstore_test.go | 2 +- blobstore/external_blobstore.go | 5 +- blobstore/external_blobstore_test.go | 6 +- blobstore/local_blobstore.go | 8 +- blobstore/local_blobstore_test.go | 16 ++-- crypto/digest_test.go | 5 +- crypto/multiple_digest.go | 6 +- crypto/multiple_digest_test.go | 24 +++-- crypto/x509_test.go | 8 +- errors/multi_error.go | 2 +- fileutil/generic_cp_copier.go | 2 +- fileutil/generic_cp_copier_test.go | 2 +- fileutil/mover_test.go | 2 +- fileutil/mover_windows_test.go | 2 +- fileutil/tarball_compressor.go | 2 +- fileutil/tarball_compressor_test.go | 15 ++-- httpclient/default_http_clients.go | 6 +- httpclient/default_http_clients_test.go | 11 ++- httpclient/http_client.go | 10 +-- httpclient/http_client_test.go | 39 ++++---- httpclient/mutual_tls_client.go | 2 +- httpclient/mutual_tls_client_test.go | 8 +- httpclient/request_retryable.go | 20 ++--- httpclient/request_retryable_test.go | 16 ++-- httpclient/socksify.go | 3 +- httpclient/socksify_test.go | 26 +++--- logger/async.go | 8 +- logger/async_test.go | 2 +- logger/file/file_test.go | 4 +- logger/logger.go | 2 +- main/verify_multidigest_test.go | 5 +- property/builders.go | 2 +- retrystrategy/unlimited_retry_strategy.go | 2 +- system/exec_cmd_runner_fixtures/cat/cat.go | 2 +- .../child_ignore_term/child_ignore_term.go | 2 +- .../exe_exits/exe_exits.go | 2 +- .../parent_ignore_term/parent_ignore_term.go | 4 +- .../parent_term/parent_term.go | 2 +- .../windows_exe/windows_exe.go | 2 +- system/exec_cmd_runner_test.go | 4 +- system/exec_process.go | 6 +- system/exec_process_unix.go | 7 +- system/exec_process_unix_test.go | 5 +- system/fakes/fake_cmd_runner.go | 4 +- system/fakes/fake_cmd_runner_test.go | 2 +- system/fakes/fake_file_system.go | 20 ++--- system/fakes/fake_file_system_test.go | 46 +++++----- system/os_file_system.go | 24 +++-- system/os_file_system_test.go | 90 +++++++++---------- system/os_file_system_unix_test.go | 7 +- system/os_file_system_windows_test.go | 12 ++- system/os_long_path_test.go | 17 ++-- system/system_suite_test.go | 9 +- 53 files changed, 257 insertions(+), 283 deletions(-) diff --git a/blobstore/digest_verifiable_blobstore_test.go b/blobstore/digest_verifiable_blobstore_test.go index 0ba6bcab..0d4b8264 100644 --- a/blobstore/digest_verifiable_blobstore_test.go +++ b/blobstore/digest_verifiable_blobstore_test.go @@ -105,7 +105,7 @@ var _ = Describe("checksumVerifiableBlobstore", func() { Describe("Create", func() { BeforeEach(func() { fakeFile := fakesys.NewFakeFile(fixturePath, fs) - fakeFile.Write([]byte("blargityblargblarg")) + fakeFile.Write([]byte("blargityblargblarg")) //nolint:errcheck fs.RegisterOpenFile(fixturePath, fakeFile) }) diff --git a/blobstore/external_blobstore.go b/blobstore/external_blobstore.go index 3b8d7774..fe681ef2 100644 --- a/blobstore/external_blobstore.go +++ b/blobstore/external_blobstore.go @@ -2,11 +2,10 @@ package blobstore import ( "encoding/json" + "errors" "fmt" "path/filepath" - "errors" - bosherr "github.com/cloudfoundry/bosh-utils/errors" boshsys "github.com/cloudfoundry/bosh-utils/system" boshuuid "github.com/cloudfoundry/bosh-utils/uuid" @@ -50,7 +49,7 @@ func (b externalBlobstore) Get(blobID string) (string, error) { err = b.run("get", blobID, fileName) if err != nil { - b.fs.RemoveAll(fileName) + b.fs.RemoveAll(fileName) //nolint:errcheck return "", err } diff --git a/blobstore/external_blobstore_test.go b/blobstore/external_blobstore_test.go index df71a141..ab3aaf21 100644 --- a/blobstore/external_blobstore_test.go +++ b/blobstore/external_blobstore_test.go @@ -66,7 +66,7 @@ var _ = Describe("externalBlobstore", func() { Expect(err).ToNot(HaveOccurred()) fs.ReturnTempFile = tempFile - defer fs.RemoveAll(tempFile.Name()) + defer fs.RemoveAll(tempFile.Name()) //nolint:errcheck fileName, err := blobstore.Get("fake-blob-id") Expect(err).ToNot(HaveOccurred()) @@ -97,7 +97,7 @@ var _ = Describe("externalBlobstore", func() { Expect(err).ToNot(HaveOccurred()) fs.ReturnTempFile = tempFile - defer fs.RemoveAll(tempFile.Name()) + defer fs.RemoveAll(tempFile.Name()) //nolint:errcheck expectedCmd := []string{ "bosh-blobstore-fake-provider", "-c", configPath, "get", @@ -121,7 +121,7 @@ var _ = Describe("externalBlobstore", func() { Expect(err).ToNot(HaveOccurred()) fileName := file.Name() - defer fs.RemoveAll(fileName) + defer fs.RemoveAll(fileName) //nolint:errcheck err = blobstore.CleanUp(fileName) Expect(err).ToNot(HaveOccurred()) diff --git a/blobstore/local_blobstore.go b/blobstore/local_blobstore.go index 4fa79663..d83edc22 100644 --- a/blobstore/local_blobstore.go +++ b/blobstore/local_blobstore.go @@ -42,7 +42,7 @@ func (b localBlobstore) Get(blobID string) (fileName string, err error) { err = b.fs.CopyFile(path.Join(b.path(), blobID), fileName) if err != nil { - b.fs.RemoveAll(fileName) + b.fs.RemoveAll(fileName) //nolint:errcheck return "", bosherr.WrapError(err, "Copying file") } @@ -50,7 +50,7 @@ func (b localBlobstore) Get(blobID string) (fileName string, err error) { } func (b localBlobstore) CleanUp(fileName string) error { - b.fs.RemoveAll(fileName) + b.fs.RemoveAll(fileName) //nolint:errcheck return nil } @@ -83,12 +83,12 @@ func (b localBlobstore) Create(fileName string) (blobID string, err error) { } func (b localBlobstore) Validate() error { - path, found := b.options["blobstore_path"] + p, found := b.options["blobstore_path"] if !found { return bosherr.Error("missing blobstore_path") } - _, ok := path.(string) + _, ok := p.(string) if !ok { return bosherr.Error("blobstore_path must be a string") } diff --git a/blobstore/local_blobstore_test.go b/blobstore/local_blobstore_test.go index f90562bb..67ec9e0f 100644 --- a/blobstore/local_blobstore_test.go +++ b/blobstore/local_blobstore_test.go @@ -54,13 +54,13 @@ var _ = Describe("localBlobstore", func() { Describe("Get", func() { It("fetches the local blob contents", func() { - fs.WriteFileString(fakeBlobstorePath+"/fake-blob-id", "fake contents") + fs.WriteFileString(fakeBlobstorePath+"/fake-blob-id", "fake contents") //nolint:errcheck tempFile, err := fs.TempFile("bosh-blobstore-local-TestLocalGet") Expect(err).ToNot(HaveOccurred()) fs.ReturnTempFile = tempFile - defer fs.RemoveAll(tempFile.Name()) + defer fs.RemoveAll(tempFile.Name()) //nolint:errcheck _, err = blobstore.Get("fake-blob-id") Expect(err).ToNot(HaveOccurred()) @@ -85,7 +85,7 @@ var _ = Describe("localBlobstore", func() { Expect(err).ToNot(HaveOccurred()) fs.ReturnTempFile = tempFile - defer fs.RemoveAll(tempFile.Name()) + defer fs.RemoveAll(tempFile.Name()) //nolint:errcheck fs.CopyFileError = errors.New("fake-copy-file-error") @@ -104,7 +104,7 @@ var _ = Describe("localBlobstore", func() { Expect(err).ToNot(HaveOccurred()) fileName := file.Name() - defer fs.RemoveAll(fileName) + defer fs.RemoveAll(fileName) //nolint:errcheck err = blobstore.CleanUp(fileName) Expect(err).ToNot(HaveOccurred()) @@ -114,7 +114,7 @@ var _ = Describe("localBlobstore", func() { Describe("Create", func() { It("creates the local blob", func() { - fs.WriteFileString("/fake-file.txt", "fake-file-contents") + fs.WriteFileString("/fake-file.txt", "fake-file-contents") //nolint:errcheck uuidGen.GeneratedUUID = "some-uuid" @@ -148,7 +148,7 @@ var _ = Describe("localBlobstore", func() { }) It("errs when copy file errs", func() { - fs.WriteFileString("/fake-file.txt", "fake-file-contents") + fs.WriteFileString("/fake-file.txt", "fake-file-contents") //nolint:errcheck uuidGen.GeneratedUUID = "some-uuid" fs.CopyFileError = errors.New("fake-copy-file-error") @@ -161,7 +161,7 @@ var _ = Describe("localBlobstore", func() { Describe("Delete", func() { It("removes the blob from the blobstore", func() { - fs.WriteFileString("/fake-file.txt", "fake-file-contents") + fs.WriteFileString("/fake-file.txt", "fake-file-contents") //nolint:errcheck blobID, err := blobstore.Create("/fake-file.txt") Expect(err).ToNot(HaveOccurred()) @@ -180,7 +180,7 @@ var _ = Describe("localBlobstore", func() { fs.RemoveAllStub = func(_ string) error { return errors.New("failed to remove") } - fs.WriteFileString("/fake-file.txt", "fake-file-contents") + fs.WriteFileString("/fake-file.txt", "fake-file-contents") //nolint:errcheck blobID, err := blobstore.Create("/fake-file.txt") Expect(err).ToNot(HaveOccurred()) diff --git a/crypto/digest_test.go b/crypto/digest_test.go index 59132ea5..49a6c805 100644 --- a/crypto/digest_test.go +++ b/crypto/digest_test.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" - "io/ioutil" "os" "strings" @@ -114,10 +113,10 @@ var _ = Describe("digestImpl", func() { BeforeEach(func() { var err error - file, err = ioutil.TempFile("", "multiple-digest") + file, err = os.CreateTemp("", "multiple-digest") Expect(err).ToNot(HaveOccurred()) defer file.Close() - file.Write([]byte("fake-contents")) + file.Write([]byte("fake-contents")) //nolint:errcheck digest = NewDigest(DigestAlgorithmSHA1, "978ad524a02039f261773fe93d94973ae7de6470") }) diff --git a/crypto/multiple_digest.go b/crypto/multiple_digest.go index c4d17190..b2131617 100644 --- a/crypto/multiple_digest.go +++ b/crypto/multiple_digest.go @@ -4,12 +4,12 @@ import ( "errors" "fmt" "io" + "os" "strings" + "unicode" bosherr "github.com/cloudfoundry/bosh-utils/errors" boshsys "github.com/cloudfoundry/bosh-utils/system" - "os" - "unicode" ) type MultipleDigest struct { @@ -59,7 +59,7 @@ func NewMultipleDigest(stream io.ReadSeeker, algos []Algorithm) (MultipleDigest, digests := []Digest{} for _, algo := range algos { - stream.Seek(0, 0) + stream.Seek(0, 0) //nolint:errcheck digest, err := algo.CreateDigest(stream) if err != nil { return MultipleDigest{}, err diff --git a/crypto/multiple_digest_test.go b/crypto/multiple_digest_test.go index fe9bd4f1..445bbfae 100644 --- a/crypto/multiple_digest_test.go +++ b/crypto/multiple_digest_test.go @@ -2,8 +2,9 @@ package crypto_test import ( "encoding/json" + "errors" + "fmt" "io" - "io/ioutil" "os" "strings" @@ -13,9 +14,6 @@ import ( fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "errors" - "fmt" ) var _ = Describe("MultipleDigest", func() { @@ -77,10 +75,10 @@ var _ = Describe("MultipleDigest", func() { BeforeEach(func() { var err error - file, err = ioutil.TempFile("", "multiple-digest") + file, err = os.CreateTemp("", "multiple-digest") Expect(err).ToNot(HaveOccurred()) defer file.Close() - file.Write([]byte("fake-contents")) + file.Write([]byte("fake-contents")) //nolint:errcheck }) It("can read a file and verify its content aginst the digest", func() { @@ -261,10 +259,10 @@ var _ = Describe("MultipleDigest", func() { Describe("NewMultipleDigestFromPath", func() { It("returns a multi digest with provided algorithms", func() { - file, err := ioutil.TempFile("", "multiple-digest") + file, err := os.CreateTemp("", "multiple-digest") Expect(err).ToNot(HaveOccurred()) defer file.Close() - file.Write([]byte("fake-readSeeker-2-contents")) + file.Write([]byte("fake-readSeeker-2-contents")) //nolint:errcheck algos := []Algorithm{ DigestAlgorithmSHA1, DigestAlgorithmSHA256, @@ -278,10 +276,10 @@ var _ = Describe("MultipleDigest", func() { }) It("return an error when calculation the digest fails", func() { - file, err := ioutil.TempFile("", "multiple-digest") + file, err := os.CreateTemp("", "multiple-digest") Expect(err).ToNot(HaveOccurred()) defer file.Close() - file.Write([]byte("fake-readSeeker-2-contents")) + file.Write([]byte("fake-readSeeker-2-contents")) //nolint:errcheck algos := []Algorithm{ DigestAlgorithmSHA1, DigestAlgorithmSHA256, @@ -321,14 +319,14 @@ var _ = Describe("MultipleDigest", func() { ) BeforeEach(func() { - file, err := ioutil.TempFile("", "multiple-digest") + file, err := os.CreateTemp("", "multiple-digest") Expect(err).ToNot(HaveOccurred()) - file.Write([]byte("fake-readSeeker-2-contents")) + file.Write([]byte("fake-readSeeker-2-contents")) //nolint:errcheck readSeeker = file }) AfterEach(func() { - file.Close() + file.Close() //nolint:errcheck }) It("returns a multi digest with provided algorithms", func() { diff --git a/crypto/x509_test.go b/crypto/x509_test.go index 0d5c0b47..76553902 100644 --- a/crypto/x509_test.go +++ b/crypto/x509_test.go @@ -35,7 +35,7 @@ QAOSxgrLBblGLWcDF9fjMeYaUnI34pHviCKeVxfgsxDR+Jg11F78sPdYLOF6ipBe certPool, err := crypto.CertPoolFromPEM([]byte(caCert)) Expect(err).ToNot(HaveOccurred()) - Expect(certPool.Subjects()[0]).To(ContainSubstring("Internet Widgits Pty Ltd")) + Expect(certPool.Subjects()[0]).To(ContainSubstring("Internet Widgits Pty Ltd")) //nolint:staticcheck }) It("returns error if PEM formatted block is invalid", func() { @@ -133,9 +133,9 @@ nH9ttalAwSLBsobVaK8mmiAdtAdx+CmHWrB4UNxCPYasrt5A6a9A9SiQ2dLd certPool, err := crypto.CertPoolFromPEM([]byte(caCert)) Expect(err).ToNot(HaveOccurred()) - Expect(len(certPool.Subjects())).To(Equal(2)) - Expect(certPool.Subjects()[0]).To(ContainSubstring("Internet Widgits Pty Ltd")) - Expect(certPool.Subjects()[1]).To(ContainSubstring("Cloud Foundry")) + Expect(len(certPool.Subjects())).To(Equal(2)) //nolint:staticcheck + Expect(certPool.Subjects()[0]).To(ContainSubstring("Internet Widgits Pty Ltd")) //nolint:staticcheck + Expect(certPool.Subjects()[1]).To(ContainSubstring("Cloud Foundry")) //nolint:staticcheck }) }) }) diff --git a/errors/multi_error.go b/errors/multi_error.go index 866d9efb..e7dd48d0 100644 --- a/errors/multi_error.go +++ b/errors/multi_error.go @@ -13,7 +13,7 @@ func NewMultiError(errors ...error) error { } func (e MultiError) Error() string { - errors := make([]string, len(e.Errors), len(e.Errors)) + errors := make([]string, len(e.Errors), len(e.Errors)) //nolint:gosimple for i, err := range e.Errors { errors[i] = err.Error() } diff --git a/fileutil/generic_cp_copier.go b/fileutil/generic_cp_copier.go index 43bdf9aa..5a27495e 100644 --- a/fileutil/generic_cp_copier.go +++ b/fileutil/generic_cp_copier.go @@ -46,7 +46,7 @@ func (c genericCpCopier) FilteredMultiCopyToTemp(dirs []DirToCopy, filters []str err = os.Chmod(tempDir, os.FileMode(0755)) if err != nil { c.CleanUp(tempDir) - bosherr.WrapError(err, "Fixing permissions on temp dir") + bosherr.WrapError(err, "Fixing permissions on temp dir") //nolint:errcheck } for _, dirToCopy := range dirs { diff --git a/fileutil/generic_cp_copier_test.go b/fileutil/generic_cp_copier_test.go index a8cc2f91..e6c5943c 100644 --- a/fileutil/generic_cp_copier_test.go +++ b/fileutil/generic_cp_copier_test.go @@ -204,7 +204,7 @@ var _ = Describe("genericCpCopier", func() { Describe("CleanUp", func() { It("cleans up", func() { tempDir := filepath.Join(os.TempDir(), "test-copier-cleanup") - fs.MkdirAll(tempDir, os.ModePerm) + fs.MkdirAll(tempDir, os.ModePerm) //nolint:errcheck cpCopier.CleanUp(tempDir) diff --git a/fileutil/mover_test.go b/fileutil/mover_test.go index ac689be7..78047cea 100644 --- a/fileutil/mover_test.go +++ b/fileutil/mover_test.go @@ -25,7 +25,7 @@ var _ = Describe("Mover", func() { oldLocation = "/path/to/old_file" newLocation = "/path/to/new_file" - fs.WriteFileString(oldLocation, "some content") + fs.WriteFileString(oldLocation, "some content") //nolint:errcheck }) It("renames the file", func() { diff --git a/fileutil/mover_windows_test.go b/fileutil/mover_windows_test.go index 1b6fed3c..5bcb757b 100644 --- a/fileutil/mover_windows_test.go +++ b/fileutil/mover_windows_test.go @@ -28,7 +28,7 @@ var _ = Describe("Mover", func() { oldLocation = "/path/to/old_file" newLocation = "/path/to/new_file" - fs.WriteFileString(oldLocation, "some content") + fs.WriteFileString(oldLocation, "some content") //nolint:errcheck }) Context("when Rename fails due to Win32 Error Code ERROR_NOT_SAME_DEVICE", func() { diff --git a/fileutil/tarball_compressor.go b/fileutil/tarball_compressor.go index 90825666..df65d144 100644 --- a/fileutil/tarball_compressor.go +++ b/fileutil/tarball_compressor.go @@ -39,7 +39,7 @@ func (c tarballCompressor) CompressSpecificFilesInDir(dir string, files []string args = append([]string{"--no-mac-metadata"}, args...) } - for _, file := range files { + for _, file := range files { //nolint:gosimple args = append(args, file) } diff --git a/fileutil/tarball_compressor_test.go b/fileutil/tarball_compressor_test.go index ff8332bb..6ec86832 100644 --- a/fileutil/tarball_compressor_test.go +++ b/fileutil/tarball_compressor_test.go @@ -5,12 +5,11 @@ import ( "fmt" "os" "path/filepath" + "strings" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - "strings" - . "github.com/cloudfoundry/bosh-utils/fileutil" boshlog "github.com/cloudfoundry/bosh-utils/logger" boshsys "github.com/cloudfoundry/bosh-utils/system" @@ -44,8 +43,8 @@ func beDir() beDirMatcher { type beDirMatcher struct { } -//FailureMessage(actual interface{}) (message string) -//NegatedFailureMessage(actual interface{}) (message string) +// FailureMessage(actual interface{}) (message string) +// NegatedFailureMessage(actual interface{}) (message string) func (m beDirMatcher) Match(actual interface{}) (bool, error) { path, ok := actual.(string) if !ok { @@ -93,11 +92,11 @@ var _ = Describe("tarballCompressor", func() { }) BeforeEach(func() { - fs.MkdirAll(dstDir, os.ModePerm) + fs.MkdirAll(dstDir, os.ModePerm) //nolint:errcheck }) AfterEach(func() { - fs.RemoveAll(dstDir) + fs.RemoveAll(dstDir) //nolint:errcheck }) Describe("CompressFilesInDir", func() { @@ -176,7 +175,7 @@ var _ = Describe("tarballCompressor", func() { "app.stderr.log", })) - _, _, _, err = cmdRunner.RunCommand("cp", tgzName, "/tmp") + _, _, _, err = cmdRunner.RunCommand("cp", tgzName, "/tmp") //nolint:ineffassign,staticcheck _, _, _, err = cmdRunner.RunCommand("tar", "-xzpf", tgzName, "-C", dstDir) Expect(err).ToNot(HaveOccurred()) @@ -217,7 +216,7 @@ var _ = Describe("tarballCompressor", func() { }) It("returns error if the destination does not exist", func() { - fs.RemoveAll(dstDir) + fs.RemoveAll(dstDir) //nolint:errcheck err := compressor.DecompressFileToDir(fixtureSrcTgz(), dstDir, CompressorOptions{}) Expect(err).To(HaveOccurred()) diff --git a/httpclient/default_http_clients.go b/httpclient/default_http_clients.go index 90e9bf31..cc9b8d9a 100644 --- a/httpclient/default_http_clients.go +++ b/httpclient/default_http_clients.go @@ -3,7 +3,7 @@ package httpclient import ( "crypto/tls" "crypto/x509" - "io/ioutil" + "io" "log" "net" "net/http" @@ -19,7 +19,7 @@ var ( defaultDialerContextFunc = SOCKS5DialContextFuncFromEnvironment((&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, - }), proxy.NewSocks5Proxy(proxy.NewHostKey(), log.New(ioutil.Discard, "", log.LstdFlags), 1*time.Minute)) + }), proxy.NewSocks5Proxy(proxy.NewHostKey(), log.New(io.Discard, "", log.LstdFlags), 1*time.Minute)) ) type Client interface { @@ -58,7 +58,7 @@ func ResetDialerContext() { defaultDialerContextFunc = SOCKS5DialContextFuncFromEnvironment((&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, - }), proxy.NewSocks5Proxy(proxy.NewHostKey(), log.New(ioutil.Discard, "", log.LstdFlags), 1*time.Minute)) + }), proxy.NewSocks5Proxy(proxy.NewHostKey(), log.New(io.Discard, "", log.LstdFlags), 1*time.Minute)) } type factory struct{} diff --git a/httpclient/default_http_clients_test.go b/httpclient/default_http_clients_test.go index 848f7c13..0f538bbc 100644 --- a/httpclient/default_http_clients_test.go +++ b/httpclient/default_http_clients_test.go @@ -19,10 +19,9 @@ var _ = Describe("Default HTTP clients", func() { Expect(client).ToNot(BeNil()) Expect(client).To(Equal(DefaultClient)) }) - It("disables HTTP Transport keep-alive (disables HTTP/1.[01] connection reuse)", func() { - var client *http.Client - client = DefaultClient + It("disables HTTP Transport keep-alive (disables HTTP/1.[01] connection reuse)", func() { + client := DefaultClient Expect(client.Transport.(*http.Transport).DisableKeepAlives).To(Equal(true)) }) }) @@ -79,16 +78,16 @@ var _ = Describe("Default HTTP clients", func() { clientTransport, _ := client.Transport.(*http.Transport) originalProxyEnv := os.Getenv("BOSH_ALL_PROXY") - os.Setenv("BOSH_ALL_PROXY", "socks5://127.0.0.1:22") + os.Setenv("BOSH_ALL_PROXY", "socks5://127.0.0.1:22") //nolint:errcheck ResetDialerContext() - os.Setenv("BOSH_ALL_PROXY", originalProxyEnv) + os.Setenv("BOSH_ALL_PROXY", originalProxyEnv) //nolint:errcheck clientAfterReset := CreateDefaultClient(nil) clientAfterResetTransport, _ := clientAfterReset.Transport.(*http.Transport) clientDialContextPointer := reflect.ValueOf(clientTransport.DialContext).Pointer() clientAfterResetDialContextPointer := reflect.ValueOf(clientAfterResetTransport.DialContext).Pointer() Expect(clientAfterResetDialContextPointer).ToNot(Equal(clientDialContextPointer)) // don't pollute other tests with a PROXY'd dialer - os.Unsetenv("BOSH_ALL_PROXY") + os.Unsetenv("BOSH_ALL_PROXY") //nolint:errcheck ResetDialerContext() }) }) diff --git a/httpclient/http_client.go b/httpclient/http_client.go index dc4e514f..210b98b9 100644 --- a/httpclient/http_client.go +++ b/httpclient/http_client.go @@ -1,13 +1,11 @@ package httpclient import ( - "net/http" - "strings" - "errors" - "regexp" - + "net/http" "net/url" + "regexp" + "strings" bosherr "github.com/cloudfoundry/bosh-utils/errors" boshlog "github.com/cloudfoundry/bosh-utils/logger" @@ -173,7 +171,7 @@ func scrubEndpointQuery(endpoint string) string { } query := parsedURL.Query() - for key, _ := range query { + for key, _ := range query { //nolint:gosimple query[key] = []string{""} } diff --git a/httpclient/http_client_test.go b/httpclient/http_client_test.go index 0863c4bb..6682d4f8 100644 --- a/httpclient/http_client_test.go +++ b/httpclient/http_client_test.go @@ -2,17 +2,16 @@ package httpclient_test import ( "bytes" - "io/ioutil" + "crypto/tls" + "io" "net" "net/http" + "time" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/ghttp" - "crypto/tls" - "time" - . "github.com/cloudfoundry/bosh-utils/httpclient" "github.com/cloudfoundry/bosh-utils/logger/loggerfakes" ) @@ -70,7 +69,7 @@ var _ = Describe("HTTPClient", func() { defer response.Body.Close() - responseBody, err := ioutil.ReadAll(response.Body) + responseBody, err := io.ReadAll(response.Body) Expect(err).ToNot(HaveOccurred()) Expect(responseBody).To(Equal([]byte("post-response"))) @@ -95,7 +94,7 @@ var _ = Describe("HTTPClient", func() { setHeaders := func(r *http.Request) { r.Header.Add("X-Custom", "custom") - r.Body = ioutil.NopCloser(bytes.NewBufferString("post-request-override")) + r.Body = io.NopCloser(bytes.NewBufferString("post-request-override")) r.ContentLength = 21 } @@ -104,7 +103,7 @@ var _ = Describe("HTTPClient", func() { defer response.Body.Close() - responseBody, err := ioutil.ReadAll(response.Body) + responseBody, err := io.ReadAll(response.Body) Expect(err).ToNot(HaveOccurred()) Expect(responseBody).To(Equal([]byte("post-response"))) @@ -162,7 +161,7 @@ var _ = Describe("HTTPClient", func() { url := "https://oauth-url?refresh_token=abc¶m2=xyz" - httpClient.PostCustomized(url, []byte("post-request"), func(r *http.Request) {}) + httpClient.PostCustomized(url, []byte("post-request"), func(r *http.Request) {}) //nolint:errcheck _, _, args := logger.DebugArgsForCall(0) Expect(args[0]).To(ContainSubstring("param2=xyz")) Expect(args[0]).To(ContainSubstring("refresh_token=abc")) @@ -198,7 +197,7 @@ var _ = Describe("HTTPClient", func() { It("redacts every query param from endpoint for https calls", func() { url := "https://oauth-url?refresh_token=abc¶m2=xyz" - httpClient.PostCustomized(url, []byte("post-request"), func(r *http.Request) {}) + httpClient.PostCustomized(url, []byte("post-request"), func(r *http.Request) {}) //nolint:errcheck _, _, args := logger.DebugArgsForCall(0) Expect(args[0]).To(ContainSubstring("param2=")) Expect(args[0]).To(ContainSubstring("refresh_token=")) @@ -266,7 +265,7 @@ var _ = Describe("HTTPClient", func() { It("does not redact every query param from endpoint for https calls", func() { url := "https://oauth-url?refresh_token=abc¶m2=xyz" - httpClient.Delete(url) + httpClient.Delete(url) //nolint:errcheck _, _, args := logger.DebugArgsForCall(0) Expect(args[0]).To(ContainSubstring("param2=xyz")) Expect(args[0]).To(ContainSubstring("refresh_token=abc")) @@ -302,7 +301,7 @@ var _ = Describe("HTTPClient", func() { It("redacts every query param from endpoint for https calls", func() { url := "https://oauth-url?refresh_token=abc¶m2=xyz" - httpClient.Delete(url) + httpClient.Delete(url) //nolint:errcheck _, _, args := logger.DebugArgsForCall(0) Expect(args[0]).To(ContainSubstring("param2=")) Expect(args[0]).To(ContainSubstring("refresh_token=")) @@ -330,7 +329,7 @@ var _ = Describe("HTTPClient", func() { defer response.Body.Close() - responseBody, err := ioutil.ReadAll(response.Body) + responseBody, err := io.ReadAll(response.Body) Expect(err).ToNot(HaveOccurred()) Expect(responseBody).To(Equal([]byte("put-response"))) @@ -355,7 +354,7 @@ var _ = Describe("HTTPClient", func() { setHeaders := func(r *http.Request) { r.Header.Add("X-Custom", "custom") - r.Body = ioutil.NopCloser(bytes.NewBufferString("put-request-override")) + r.Body = io.NopCloser(bytes.NewBufferString("put-request-override")) r.ContentLength = 20 } @@ -364,7 +363,7 @@ var _ = Describe("HTTPClient", func() { defer response.Body.Close() - responseBody, err := ioutil.ReadAll(response.Body) + responseBody, err := io.ReadAll(response.Body) Expect(err).ToNot(HaveOccurred()) Expect(responseBody).To(Equal([]byte("put-response"))) @@ -421,7 +420,7 @@ var _ = Describe("HTTPClient", func() { It("does not redact every query param from endpoint for https calls", func() { url := "https://oauth-url?refresh_token=abc¶m2=xyz" - httpClient.PutCustomized(url, []byte("post-request"), func(r *http.Request) {}) + httpClient.PutCustomized(url, []byte("post-request"), func(r *http.Request) {}) //nolint:errcheck _, _, args := logger.DebugArgsForCall(0) Expect(args[0]).To(ContainSubstring("param2=xyz")) Expect(args[0]).To(ContainSubstring("refresh_token=abc")) @@ -457,7 +456,7 @@ var _ = Describe("HTTPClient", func() { It("redacts every query param from endpoint for https calls", func() { url := "https://oauth-url?refresh_token=abc¶m2=xyz" - httpClient.PutCustomized(url, []byte("post-request"), func(r *http.Request) {}) + httpClient.PutCustomized(url, []byte("post-request"), func(r *http.Request) {}) //nolint:errcheck _, _, args := logger.DebugArgsForCall(0) Expect(args[0]).To(ContainSubstring("param2=")) Expect(args[0]).To(ContainSubstring("refresh_token=")) @@ -484,7 +483,7 @@ var _ = Describe("HTTPClient", func() { defer response.Body.Close() - responseBody, err := ioutil.ReadAll(response.Body) + responseBody, err := io.ReadAll(response.Body) Expect(err).ToNot(HaveOccurred()) Expect(responseBody).To(Equal([]byte("get-response"))) @@ -515,7 +514,7 @@ var _ = Describe("HTTPClient", func() { defer response.Body.Close() - responseBody, err := ioutil.ReadAll(response.Body) + responseBody, err := io.ReadAll(response.Body) Expect(err).ToNot(HaveOccurred()) Expect(responseBody).To(Equal([]byte("get-response"))) @@ -572,7 +571,7 @@ var _ = Describe("HTTPClient", func() { It("does not redact every query param from endpoint for https calls", func() { url := "https://oauth-url?refresh_token=abc¶m2=xyz" - httpClient.GetCustomized(url, func(r *http.Request) {}) + httpClient.GetCustomized(url, func(r *http.Request) {}) //nolint:errcheck _, _, args := logger.DebugArgsForCall(0) Expect(args[0]).To(ContainSubstring("param2=xyz")) Expect(args[0]).To(ContainSubstring("refresh_token=abc")) @@ -608,7 +607,7 @@ var _ = Describe("HTTPClient", func() { It("redacts every query param from endpoint for https calls", func() { url := "https://oauth-url?refresh_token=abc¶m2=xyz" - httpClient.GetCustomized(url, func(r *http.Request) {}) + httpClient.GetCustomized(url, func(r *http.Request) {}) //nolint:errcheck _, _, args := logger.DebugArgsForCall(0) Expect(args[0]).To(ContainSubstring("param2=")) Expect(args[0]).To(ContainSubstring("refresh_token=")) diff --git a/httpclient/mutual_tls_client.go b/httpclient/mutual_tls_client.go index 037257d1..e28839f3 100644 --- a/httpclient/mutual_tls_client.go +++ b/httpclient/mutual_tls_client.go @@ -17,7 +17,7 @@ func NewMutualTLSClient(identity tls.Certificate, caCertPool *x509.CertPool, ser ) clientConfig := tlsConfig.Client(tlsconfig.WithAuthority(caCertPool)) - clientConfig.BuildNameToCertificate() + clientConfig.BuildNameToCertificate() //nolint:staticcheck clientConfig.ServerName = serverName return &http.Client{ diff --git a/httpclient/mutual_tls_client_test.go b/httpclient/mutual_tls_client_test.go index 3377adcb..bcb31b69 100644 --- a/httpclient/mutual_tls_client_test.go +++ b/httpclient/mutual_tls_client_test.go @@ -3,8 +3,8 @@ package httpclient_test import ( "crypto/tls" "crypto/x509" - "io/ioutil" "net/http" + "os" "time" "github.com/cloudfoundry/bosh-utils/httpclient" @@ -30,7 +30,7 @@ var _ = Describe("NewMutualTLSClient", func() { identity, err = tls.LoadX509KeyPair("./assets/test_client.pem", "./assets/test_client.key") Expect(err).ToNot(HaveOccurred()) // Load CA cert - caCert, err := ioutil.ReadFile("./assets/test_ca.pem") + caCert, err := os.ReadFile("./assets/test_ca.pem") Expect(err).ToNot(HaveOccurred()) caCertPool = x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) @@ -53,11 +53,11 @@ var _ = Describe("NewMutualTLSClient", func() { }) It("has secure tls defaults", func() { - tlsConfigBefore := *tlsConfig + tlsConfigBefore := *tlsConfig //nolint:govet tlsconfig.WithInternalServiceDefaults()(tlsConfig) - Expect(*tlsConfig).To(Equal(tlsConfigBefore)) + Expect(*tlsConfig).To(Equal(tlsConfigBefore)) //nolint:govet }) It("sets up a timeout", func() { diff --git a/httpclient/request_retryable.go b/httpclient/request_retryable.go index 484b7472..2a09f5bf 100644 --- a/httpclient/request_retryable.go +++ b/httpclient/request_retryable.go @@ -3,10 +3,8 @@ package httpclient import ( "bytes" "fmt" - "io/ioutil" - "net/http" - "io" + "net/http" bosherr "github.com/cloudfoundry/bosh-utils/errors" boshlog "github.com/cloudfoundry/bosh-utils/logger" @@ -68,7 +66,7 @@ func (r *RequestRetryable) Attempt() (bool, error) { r.request.Body, err = r.request.GetBody() if err != nil { if r.originalBody != nil { - r.originalBody.Close() + r.originalBody.Close() //nolint:errcheck } return false, bosherr.WrapError(err, "Updating request body for retry") @@ -85,9 +83,9 @@ func (r *RequestRetryable) Attempt() (bool, error) { // forcing an EOF. // This should not be necessary when the following CL gets accepted: // https://go-review.googlesource.com/c/go/+/62891 - io.Copy(ioutil.Discard, r.response.Body) + io.Copy(io.Discard, r.response.Body) //nolint:errcheck - r.response.Body.Close() + r.response.Body.Close() //nolint:errcheck } r.attempt++ @@ -97,7 +95,7 @@ func (r *RequestRetryable) Attempt() (bool, error) { attemptable, err := r.isResponseAttemptable(r.response, err) if !attemptable && r.originalBody != nil { - r.originalBody.Close() + r.originalBody.Close() //nolint:errcheck } return attemptable, err @@ -127,7 +125,7 @@ func formatRequest(req *http.Request) string { return fmt.Sprintf("Request{ Method: '%s', URL: '%s' }", req.Method, req.URL) } -func formatResponse(resp *http.Response) string { +func formatResponse(resp *http.Response) string { //nolint:unused if resp == nil { return "Response(nil)" } @@ -153,16 +151,16 @@ func MakeReplayable(r *http.Request) (io.ReadCloser, error) { return nil, bosherr.WrapError(err, "Seeking to beginning of seekable request body") } - return ioutil.NopCloser(seekableBody), nil + return io.NopCloser(seekableBody), nil } } else { - bodyBytes, err := ioutil.ReadAll(r.Body) + bodyBytes, err := io.ReadAll(r.Body) if err != nil { return originalBody, bosherr.WrapError(err, "Buffering request body") } r.GetBody = func() (io.ReadCloser, error) { - return ioutil.NopCloser(bytes.NewReader(bodyBytes)), nil + return io.NopCloser(bytes.NewReader(bodyBytes)), nil } } diff --git a/httpclient/request_retryable_test.go b/httpclient/request_retryable_test.go index f99941a6..8f75da0b 100644 --- a/httpclient/request_retryable_test.go +++ b/httpclient/request_retryable_test.go @@ -1,10 +1,11 @@ package httpclient_test import ( + "bytes" "errors" "io" - "io/ioutil" "net/http" + "os" "strings" "sync" @@ -14,9 +15,6 @@ import ( . "github.com/onsi/gomega" "github.com/onsi/gomega/ghttp" - "bytes" - "os" - boshlog "github.com/cloudfoundry/bosh-utils/logger" ) @@ -34,7 +32,7 @@ var _ = Describe("RequestRetryable", func() { logger = boshlog.NewLogger(boshlog.LevelNone) var err error - request, err = http.NewRequest("GET", server.URL(), ioutil.NopCloser(strings.NewReader("fake-request-body"))) + request, err = http.NewRequest("GET", server.URL(), io.NopCloser(strings.NewReader("fake-request-body"))) Expect(err).NotTo(HaveOccurred()) client := &http.Client{Transport: &http.Transport{}} @@ -100,7 +98,7 @@ var _ = Describe("RequestRetryable", func() { It("os.File conforms to the Seekable interface", func() { var seekable io.ReadSeeker - seekable, err := ioutil.TempFile(os.TempDir(), "seekable") + seekable, err := os.CreateTemp(os.TempDir(), "seekable") Expect(err).ToNot(HaveOccurred()) _, err = seekable.Seek(0, 0) Expect(err).ToNot(HaveOccurred()) @@ -306,7 +304,7 @@ func NewSeekableReadClose(content []byte) *seekableReadClose { return &seekableReadClose{ Seeked: false, content: content, - readCloser: ioutil.NopCloser(bytes.NewReader(content)), + readCloser: io.NopCloser(bytes.NewReader(content)), } } @@ -314,7 +312,7 @@ func (s *seekableReadClose) Seek(offset int64, whence int) (ret int64, err error s.readCloserMutex.Lock() defer s.readCloserMutex.Unlock() - s.readCloser = ioutil.NopCloser(bytes.NewReader(s.content)) + s.readCloser = io.NopCloser(bytes.NewReader(s.content)) s.Seeked = true return 0, nil } @@ -337,7 +335,7 @@ func (s *seekableReadClose) Close() error { func readString(body io.ReadCloser) string { defer body.Close() - content, err := ioutil.ReadAll(body) + content, err := io.ReadAll(body) Expect(err).ToNot(HaveOccurred()) return string(content) } diff --git a/httpclient/socksify.go b/httpclient/socksify.go index abe8c251..5c949470 100644 --- a/httpclient/socksify.go +++ b/httpclient/socksify.go @@ -2,7 +2,6 @@ package httpclient import ( "context" - "io/ioutil" "net" "net/url" "os" @@ -57,7 +56,7 @@ func SOCKS5DialContextFuncFromEnvironment(origDialer *net.Dialer, socks5Proxy Pr ) } - proxySSHKey, err := ioutil.ReadFile(proxySSHKeyPath) + proxySSHKey, err := os.ReadFile(proxySSHKeyPath) if err != nil { return errorDialFunc(err, "Reading private key file for SOCKS5 Proxy") } diff --git a/httpclient/socksify_test.go b/httpclient/socksify_test.go index 1c1496ea..ab27fcfe 100644 --- a/httpclient/socksify_test.go +++ b/httpclient/socksify_test.go @@ -2,15 +2,13 @@ package httpclient_test import ( "context" + "errors" "fmt" - "io/ioutil" "net" "os" "path/filepath" "sync" - "errors" - . "github.com/cloudfoundry/bosh-utils/httpclient" proxy "github.com/cloudfoundry/socks5-proxy" . "github.com/onsi/ginkgo/v2" @@ -38,12 +36,12 @@ var _ = Describe("Socksify", func() { proxyDialer.DialerCall.Returns.DialFunc = proxy.DialFunc(func(x, y string) (net.Conn, error) { return nil, errors.New("proxy dialer") }) - tempDir, err := ioutil.TempDir("", "") + tempDir, err := os.MkdirTemp("", "") Expect(err).NotTo(HaveOccurred()) privateKeyPath := filepath.Join(tempDir, "test.key") - err = ioutil.WriteFile(privateKeyPath, []byte("some-key"), 0600) + err = os.WriteFile(privateKeyPath, []byte("some-key"), 0600) Expect(err).NotTo(HaveOccurred()) - os.Setenv("BOSH_ALL_PROXY", fmt.Sprintf("ssh+socks5://localhost:12345?private-key=%s", privateKeyPath)) + os.Setenv("BOSH_ALL_PROXY", fmt.Sprintf("ssh+socks5://localhost:12345?private-key=%s", privateKeyPath)) //nolint:errcheck dialFunc = SOCKS5DialContextFuncFromEnvironment(&origDial, proxyDialer) }) @@ -61,12 +59,12 @@ var _ = Describe("Socksify", func() { Context("When a 'custom-username' is given in the URL", func() { JustBeforeEach(func() { - tempDir, err := ioutil.TempDir("", "") + tempDir, err := os.MkdirTemp("", "") Expect(err).NotTo(HaveOccurred()) privateKeyPath := filepath.Join(tempDir, "test.key") - err = ioutil.WriteFile(privateKeyPath, []byte("some-key"), 0600) + err = os.WriteFile(privateKeyPath, []byte("some-key"), 0600) Expect(err).NotTo(HaveOccurred()) - os.Setenv("BOSH_ALL_PROXY", fmt.Sprintf("ssh+socks5://custom-username@localhost:12345?private-key=%s", privateKeyPath)) + os.Setenv("BOSH_ALL_PROXY", fmt.Sprintf("ssh+socks5://custom-username@localhost:12345?private-key=%s", privateKeyPath)) //nolint:errcheck dialFunc = SOCKS5DialContextFuncFromEnvironment(&origDial, proxyDialer) }) It("Returns a function that creates a socks5 proxy dialer for user 'custom-username'", func() { @@ -110,7 +108,7 @@ var _ = Describe("Socksify", func() { Context("when the URL after the ssh+ prefix cannot be parsed", func() { BeforeEach(func() { - os.Setenv("BOSH_ALL_PROXY", fmt.Sprintf("ssh+:cannot-start-with-colon")) + os.Setenv("BOSH_ALL_PROXY", "ssh+:cannot-start-with-colon") //nolint:errcheck dialFunc = SOCKS5DialContextFuncFromEnvironment(&origDial, proxyDialer) }) It("returns a dialer that returns the url parsing error", func() { @@ -138,7 +136,7 @@ var _ = Describe("Socksify", func() { Context("when the query params do not contain the private key path", func() { BeforeEach(func() { - os.Setenv("BOSH_ALL_PROXY", fmt.Sprintf("ssh+socks5://localhost:12345?foo=bar")) + os.Setenv("BOSH_ALL_PROXY", "ssh+socks5://localhost:12345?foo=bar") //nolint:errcheck dialFunc = SOCKS5DialContextFuncFromEnvironment(&origDial, proxyDialer) }) It("returns a dialer that returns the param not found error", func() { @@ -152,7 +150,7 @@ var _ = Describe("Socksify", func() { Context("when no key exists at the private key path", func() { BeforeEach(func() { - os.Setenv("BOSH_ALL_PROXY", fmt.Sprintf("ssh+socks5://localhost:12345?private-key=/no/file/here")) + os.Setenv("BOSH_ALL_PROXY", "ssh+socks5://localhost:12345?private-key=/no/file/here") //nolint:errcheck dialFunc = SOCKS5DialContextFuncFromEnvironment(&origDial, proxyDialer) }) It("returns a dialer that returns the private key file not found error", func() { @@ -169,7 +167,7 @@ var _ = Describe("Socksify", func() { // Happy paths not tested Context("when the URL cannot be parsed", func() { BeforeEach(func() { - os.Setenv("BOSH_ALL_PROXY", fmt.Sprintf(":cannot-start-with-colon")) + os.Setenv("BOSH_ALL_PROXY", ":cannot-start-with-colon") //nolint:errcheck dialFunc = SOCKS5DialContextFuncFromEnvironment(&origDial, proxyDialer) }) It("returns a dialer that returns the parsing error", func() { @@ -183,7 +181,7 @@ var _ = Describe("Socksify", func() { Context("when the URL is not a valid proxy scheme", func() { BeforeEach(func() { - os.Setenv("BOSH_ALL_PROXY", fmt.Sprintf("foo://cannot-start-with-colon")) + os.Setenv("BOSH_ALL_PROXY", "foo://cannot-start-with-colon") //nolint:errcheck dialFunc = SOCKS5DialContextFuncFromEnvironment(&origDial, proxyDialer) }) It("returns a dialer returns the invalid proxy scheme error", func() { diff --git a/logger/async.go b/logger/async.go index ff01ed46..27e8c4ad 100644 --- a/logger/async.go +++ b/logger/async.go @@ -43,7 +43,7 @@ func (w *asyncWriter) doFlush() { for i := 0; i < n; i++ { select { case p := <-w.queue: - w.w.Write(p) + w.w.Write(p) //nolint:errcheck default: } } @@ -56,7 +56,7 @@ func (w *asyncWriter) doWork() { w.doFlush() close(c) case p := <-w.queue: - w.w.Write(p) + w.w.Write(p) //nolint:errcheck } } } @@ -67,7 +67,7 @@ type asyncLogger struct { } func (l *asyncLogger) Flush() error { - l.writer.Flush() + l.writer.Flush() //nolint:errcheck return nil } @@ -122,7 +122,7 @@ func (l *asyncLogger) ErrorWithDetails(tag, msg string, args ...interface{}) { func (l *asyncLogger) HandlePanic(tag string) { if l.log.recoverPanic(tag) { - l.FlushTimeout(time.Second * 30) + l.FlushTimeout(time.Second * 30) //nolint:errcheck os.Exit(2) } } diff --git a/logger/async_test.go b/logger/async_test.go index c345a111..0d834ef4 100644 --- a/logger/async_test.go +++ b/logger/async_test.go @@ -182,7 +182,7 @@ var _ = Describe("Logger", func() { tick := time.NewTicker(WriteInterval / 10) defer tick.Stop() go func() { - for _ = range tick.C { + for _ = range tick.C { //nolint:gosimple logger.Debug("NEW", "new") } }() diff --git a/logger/file/file_test.go b/logger/file/file_test.go index b7aa5adf..92e16c6d 100644 --- a/logger/file/file_test.go +++ b/logger/file/file_test.go @@ -35,8 +35,8 @@ var _ = Describe("NewFileLogger", func() { }) AfterEach(func() { - logFile.Close() - fs.RemoveAll(logFile.Name()) + logFile.Close() //nolint:errcheck + fs.RemoveAll(logFile.Name()) //nolint:errcheck }) It("logs the formatted DEBUG message to the file", func() { diff --git a/logger/logger.go b/logger/logger.go index eaaed0c5..3eba37e2 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -198,7 +198,7 @@ func (l *logger) printf(tag, msg string, args ...interface{}) { l.loggerMu.Lock() timestamp := time.Now().Format(l.timestampFormat) l.logger.SetPrefix("[" + tag + "] " + timestamp + " ") - l.logger.Output(2, s) + l.logger.Output(2, s) //nolint:errcheck l.loggerMu.Unlock() } diff --git a/main/verify_multidigest_test.go b/main/verify_multidigest_test.go index 1d443e7a..43022bb2 100644 --- a/main/verify_multidigest_test.go +++ b/main/verify_multidigest_test.go @@ -1,7 +1,6 @@ package main_test import ( - "io/ioutil" "os" "os/exec" @@ -18,7 +17,7 @@ var _ = Describe("Verify_multidigest", func() { BeforeEach(func() { var err error - tempFile, err = ioutil.TempFile("", "multi-digest-test") + tempFile, err = os.CreateTemp("", "multi-digest-test") Expect(err).ToNot(HaveOccurred()) _, err = tempFile.WriteString("sample content") Expect(err).ToNot(HaveOccurred()) @@ -32,7 +31,7 @@ var _ = Describe("Verify_multidigest", func() { }) AfterEach(func() { - os.Remove(tempFile.Name()) + os.Remove(tempFile.Name()) //nolint:errcheck }) Describe("version option", func() { diff --git a/property/builders.go b/property/builders.go index 160b21fe..50f5a292 100644 --- a/property/builders.go +++ b/property/builders.go @@ -30,7 +30,7 @@ func BuildMap(rawProperties map[interface{}]interface{}) (Map, error) { // BuildList creates a new property List from an slice of interface{}, erroring if any elements are maps with non-string keys. // Slices in the property List are converted to property Lists. Maps in the property List are converted to property Maps. func BuildList(rawProperties []interface{}) (List, error) { - result := make(List, len(rawProperties), len(rawProperties)) + result := make(List, len(rawProperties), len(rawProperties)) //nolint:gosimple for i, val := range rawProperties { convertedVal, err := Build(val) diff --git a/retrystrategy/unlimited_retry_strategy.go b/retrystrategy/unlimited_retry_strategy.go index c312aa5a..b3f076ad 100644 --- a/retrystrategy/unlimited_retry_strategy.go +++ b/retrystrategy/unlimited_retry_strategy.go @@ -7,7 +7,7 @@ import ( ) type unlimitedRetryStrategy struct { - maxAttempts int + maxAttempts int //nolint:unused delay time.Duration retryable Retryable logger boshlog.Logger diff --git a/system/exec_cmd_runner_fixtures/cat/cat.go b/system/exec_cmd_runner_fixtures/cat/cat.go index 37e46c12..11fa5ddb 100644 --- a/system/exec_cmd_runner_fixtures/cat/cat.go +++ b/system/exec_cmd_runner_fixtures/cat/cat.go @@ -31,7 +31,7 @@ func TimedReader(buf *bytes.Buffer) error { case <-time.After(time.Second): return errors.New("timeout") } - return errors.New("THIS SHOULD NEVER HAPPEN!") + return errors.New("THIS SHOULD NEVER HAPPEN!") //nolint:govet } func main() { diff --git a/system/exec_cmd_runner_fixtures/child_ignore_term/child_ignore_term.go b/system/exec_cmd_runner_fixtures/child_ignore_term/child_ignore_term.go index 44a083fa..33a995a0 100644 --- a/system/exec_cmd_runner_fixtures/child_ignore_term/child_ignore_term.go +++ b/system/exec_cmd_runner_fixtures/child_ignore_term/child_ignore_term.go @@ -11,7 +11,7 @@ func main() { fmt.Printf("child_pid=%d\n", os.Getpid()) sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGKILL) + signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGKILL) //nolint:staticcheck go func() { for { diff --git a/system/exec_cmd_runner_fixtures/exe_exits/exe_exits.go b/system/exec_cmd_runner_fixtures/exe_exits/exe_exits.go index 96e3106c..29e254c2 100644 --- a/system/exec_cmd_runner_fixtures/exe_exits/exe_exits.go +++ b/system/exec_cmd_runner_fixtures/exe_exits/exe_exits.go @@ -9,7 +9,7 @@ import ( func main() { sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGKILL) + signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGKILL) //nolint:staticcheck go func() { for { diff --git a/system/exec_cmd_runner_fixtures/parent_ignore_term/parent_ignore_term.go b/system/exec_cmd_runner_fixtures/parent_ignore_term/parent_ignore_term.go index c84c1fc8..1bf00656 100644 --- a/system/exec_cmd_runner_fixtures/parent_ignore_term/parent_ignore_term.go +++ b/system/exec_cmd_runner_fixtures/parent_ignore_term/parent_ignore_term.go @@ -13,7 +13,7 @@ func main() { fmt.Printf("parent_pid=%d\n", os.Getpid()) sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGKILL) + signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGKILL) //nolint:staticcheck go func() { for { @@ -30,7 +30,7 @@ func main() { cmd := exec.Command(filepath.Join(filepath.Dir(os.Args[0]), "child_ignore_term")) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr - cmd.Run() + cmd.Run() //nolint:errcheck // Keep on running even if child dies select {} diff --git a/system/exec_cmd_runner_fixtures/parent_term/parent_term.go b/system/exec_cmd_runner_fixtures/parent_term/parent_term.go index 1a92c2a9..9f80fd13 100644 --- a/system/exec_cmd_runner_fixtures/parent_term/parent_term.go +++ b/system/exec_cmd_runner_fixtures/parent_term/parent_term.go @@ -25,7 +25,7 @@ func main() { cmd := exec.Command(filepath.Join(filepath.Dir(os.Args[0]), "child_term")) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr - cmd.Run() + cmd.Run() //nolint:errcheck // Keep on running even if child dies select {} diff --git a/system/exec_cmd_runner_fixtures/windows_exe/windows_exe.go b/system/exec_cmd_runner_fixtures/windows_exe/windows_exe.go index c879b607..38ef173a 100644 --- a/system/exec_cmd_runner_fixtures/windows_exe/windows_exe.go +++ b/system/exec_cmd_runner_fixtures/windows_exe/windows_exe.go @@ -10,7 +10,7 @@ import ( func main() { sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGKILL) + signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGKILL) //nolint:staticcheck done := make(chan struct{}) var exitStatus int diff --git a/system/exec_cmd_runner_test.go b/system/exec_cmd_runner_test.go index 39b21905..4eeab794 100644 --- a/system/exec_cmd_runner_test.go +++ b/system/exec_cmd_runner_test.go @@ -141,7 +141,7 @@ var _ = Describe("execCmdRunner", func() { cmd := GetPlatformCommand("env") cmd.UseIsolatedEnv = true if runtime.GOOS == "windows" { - Expect(func() { runner.RunComplexCommand(cmd) }).To(Panic()) + Expect(func() { runner.RunComplexCommand(cmd) }).To(Panic()) //nolint:errcheck } else { stdout, stderr, status, err := runner.RunComplexCommand(cmd) Expect(err).ToNot(HaveOccurred()) @@ -155,7 +155,7 @@ var _ = Describe("execCmdRunner", func() { }) setupWindowsEnvTest := func(cmdVars map[string]string) (map[string]string, error) { - os.Setenv("_FOO", "BAR") + os.Setenv("_FOO", "BAR") //nolint:errcheck defer os.Unsetenv("_FOO") cmd := GetPlatformCommand("env") diff --git a/system/exec_process.go b/system/exec_process.go index b02c904a..dbbc9687 100644 --- a/system/exec_process.go +++ b/system/exec_process.go @@ -21,7 +21,7 @@ type execProcess struct { keepAttached bool quiet bool pid int - pgid int + pgid int //nolint:unused logger boshlog.Logger waitCh chan Result } @@ -56,12 +56,12 @@ func (p *execProcess) wait() Result { // err will be non-nil if command exits with non-0 status err := p.cmd.Wait() - stdout := string(p.stdoutWriter.Bytes()) + stdout := p.stdoutWriter.String() if !p.quiet { p.logger.Debug(execProcessLogTag, "Stdout: %s", stdout) } - stderr := string(p.stderrWriter.Bytes()) + stderr := p.stderrWriter.String() if !p.quiet { p.logger.Debug(execProcessLogTag, "Stderr: %s", stderr) } diff --git a/system/exec_process_unix.go b/system/exec_process_unix.go index 0bb9eae6..4e46d74e 100644 --- a/system/exec_process_unix.go +++ b/system/exec_process_unix.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package system @@ -108,10 +109,8 @@ func (p *execProcess) signalGroup(sig syscall.Signal) error { func (p *execProcess) groupExists() bool { err := syscall.Kill(-p.pgid, syscall.Signal(0)) - if p.isGroupDoesNotExistError(err) { - return false - } - return true + + return !p.isGroupDoesNotExistError(err) } func (p *execProcess) isGroupDoesNotExistError(err error) bool { diff --git a/system/exec_process_unix_test.go b/system/exec_process_unix_test.go index d53afcb1..8acd1356 100644 --- a/system/exec_process_unix_test.go +++ b/system/exec_process_unix_test.go @@ -5,7 +5,6 @@ package system_test import ( "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -56,7 +55,7 @@ var _ = Describe("execProcess", func() { err error ) - buildDir, err = ioutil.TempDir("", "TerminateNicely") + buildDir, err = os.MkdirTemp("", "TerminateNicely") Expect(err).ToNot(HaveOccurred()) exesToCompile := []string{ @@ -76,7 +75,7 @@ var _ = Describe("execProcess", func() { }) AfterEach(func() { - os.RemoveAll(buildDir) + os.RemoveAll(buildDir) //nolint:errcheck }) //for _, keepAttached := range []bool{true, false} { diff --git a/system/fakes/fake_cmd_runner.go b/system/fakes/fake_cmd_runner.go index a34e5d55..dae1670f 100644 --- a/system/fakes/fake_cmd_runner.go +++ b/system/fakes/fake_cmd_runner.go @@ -100,11 +100,11 @@ func (r *FakeCmdRunner) RunComplexCommand(cmd boshsys.Command) (string, string, stdout, stderr, exitstatus, err := r.getOutputsForCmd(runCmd) if cmd.Stdout != nil { - cmd.Stdout.Write([]byte(stdout)) + cmd.Stdout.Write([]byte(stdout)) //nolint:errcheck } if cmd.Stderr != nil { - cmd.Stderr.Write([]byte(stderr)) + cmd.Stderr.Write([]byte(stderr)) //nolint:errcheck } return stdout, stderr, exitstatus, err diff --git a/system/fakes/fake_cmd_runner_test.go b/system/fakes/fake_cmd_runner_test.go index 3a0e9f5f..1a60d593 100644 --- a/system/fakes/fake_cmd_runner_test.go +++ b/system/fakes/fake_cmd_runner_test.go @@ -46,7 +46,7 @@ var _ = Describe("FakeCmdRunner", func() { }) It("pops first result then succeeds properly", func() { - _, _, _, err := runner.RunCommand("foo", "bar") + _, _, _, err := runner.RunCommand("foo", "bar") //nolint:ineffassign,staticcheck _, _, _, err = runner.RunCommand("foo", "bar") Expect(err).ToNot(HaveOccurred()) diff --git a/system/fakes/fake_file_system.go b/system/fakes/fake_file_system.go index ad4b35ce..832c8d10 100644 --- a/system/fakes/fake_file_system.go +++ b/system/fakes/fake_file_system.go @@ -404,7 +404,7 @@ func (fs *FakeFileSystem) StatHelper(path string) (os.FileInfo, error) { return nil, fmt.Errorf("stat: %s: no such file or directory", path) } - stats = targetStats + stats = targetStats //nolint:staticcheck } return NewFakeFile(path, fs).Stat() @@ -439,7 +439,7 @@ func (fs *FakeFileSystem) readlink(path string) (string, error) { } if stats.FileType != FakeFileTypeSymlink { - return "", errors.New(fmt.Sprintf("cannot readlink of non-symlink")) + return "", fmt.Errorf("cannot readlink of non-symlink") } return stats.SymlinkTarget, nil @@ -536,7 +536,7 @@ func (fs *FakeFileSystem) writeFile(path string, content []byte) error { path = fs.fileRegistry.UnifiedPath(path) parent := gopath.Dir(path) if parent != "." { - fs.writeDir(parent) + fs.writeDir(parent) //nolint:errcheck } stats := fs.getOrCreateFile(path) @@ -550,7 +550,7 @@ func (fs *FakeFileSystem) writeDir(path string) error { grandparent := gopath.Dir(parent) if grandparent != parent { - fs.writeDir(parent) + fs.writeDir(parent) //nolint:errcheck } stats := fs.getOrCreateFile(path) @@ -576,13 +576,13 @@ func (fs *FakeFileSystem) ConvergeFileContents(path string, content []byte, opts if stats == nil { return true, nil } - return bytes.Compare(stats.Content, content) != 0, nil + return bytes.Compare(stats.Content, content) != 0, nil //nolint:gosimple } stats := fs.getOrCreateFile(path) stats.FileType = FakeFileTypeFile - if bytes.Compare(stats.Content, content) != 0 { + if bytes.Compare(stats.Content, content) != 0 { //nolint:gosimple stats.Content = content return true, nil } @@ -591,12 +591,12 @@ func (fs *FakeFileSystem) ConvergeFileContents(path string, content []byte, opts } func (fs *FakeFileSystem) ReadFileString(path string) (string, error) { - bytes, err := fs.ReadFile(path) + b, err := fs.ReadFile(path) if err != nil { return "", err } - return string(bytes), nil + return string(b), nil } func (fs *FakeFileSystem) RegisterReadFileError(path string, err error) { @@ -684,7 +684,7 @@ func (fs *FakeFileSystem) Rename(oldPath, newPath string) error { } // Ignore error from RemoveAll - fs.removeAll(oldPath) + fs.removeAll(oldPath) //nolint:errcheck return nil } @@ -779,7 +779,7 @@ func (fs *FakeFileSystem) CopyFile(srcPath, dstPath string) error { srcFile := fs.fileRegistry.Get(srcPath) if srcFile == nil { - return errors.New(fmt.Sprintf("%s doesn't exist", srcPath)) + return fmt.Errorf("%s doesn't exist", srcPath) } fs.fileRegistry.Register(dstPath, srcFile) diff --git a/system/fakes/fake_file_system_test.go b/system/fakes/fake_file_system_test.go index 0eb53d6f..59491199 100644 --- a/system/fakes/fake_file_system_test.go +++ b/system/fakes/fake_file_system_test.go @@ -109,8 +109,8 @@ var _ = Describe("FakeFileSystem", func() { Describe("RemoveAll", func() { It("removes the specified file", func() { - fs.WriteFileString("foobar", "asdfghjk") - fs.WriteFileString("foobarbaz", "qwertyuio") + fs.WriteFileString("foobar", "asdfghjk") //nolint:errcheck + fs.WriteFileString("foobarbaz", "qwertyuio") //nolint:errcheck err := fs.RemoveAll("foobar") Expect(err).ToNot(HaveOccurred()) @@ -125,10 +125,10 @@ var _ = Describe("FakeFileSystem", func() { }) It("works with windows drives", func() { - fs.WriteFileString("D:/env1", "fake-content1") + fs.WriteFileString("D:/env1", "fake-content1") //nolint:errcheck Expect(fs.FileExists("D:/env1")).To(BeTrue()) - fs.WriteFileString("C:/env2", "fake-content2") + fs.WriteFileString("C:/env2", "fake-content2") //nolint:errcheck Expect(fs.FileExists("C:/env2")).To(BeTrue()) }) @@ -182,7 +182,7 @@ var _ = Describe("FakeFileSystem", func() { called = true return nil } - fs.WriteFileString("foobar", "asdfghjk") + fs.WriteFileString("foobar", "asdfghjk") //nolint:errcheck err := fs.RemoveAll("foobar") Expect(err).ToNot(HaveOccurred()) @@ -214,7 +214,7 @@ var _ = Describe("FakeFileSystem", func() { BeforeEach(func() { for fixtureFile, contents := range fixtureFiles { - fs.WriteFileString(filepath.Join(fixtureDirPath, fixtureFile), contents) + fs.WriteFileString(filepath.Join(fixtureDirPath, fixtureFile), contents) //nolint:errcheck } }) @@ -222,7 +222,7 @@ var _ = Describe("FakeFileSystem", func() { srcPath := fixtureDirPath tmpDir, err := fs.TempDir("CopyDirTestDir") Expect(err).ToNot(HaveOccurred()) - defer fs.RemoveAll(tmpDir) + defer fs.RemoveAll(tmpDir) //nolint:errcheck destPath := filepath.Join(tmpDir, "dest") @@ -259,7 +259,7 @@ var _ = Describe("FakeFileSystem", func() { dstPath, err := fs.TempDir("CopyDirTestDest") Expect(err).ToNot(HaveOccurred()) - defer fs.RemoveAll(dstPath) + defer fs.RemoveAll(dstPath) //nolint:errcheck err = fs.CopyDir(srcPath, dstPath) Expect(err).ToNot(HaveOccurred()) @@ -452,7 +452,7 @@ var _ = Describe("FakeFileSystem", func() { Context("when the target path exists", func() { It("returns the target path without error", func() { - fs.WriteFileString("foobarTarget", "asdfasdf") + fs.WriteFileString("foobarTarget", "asdfasdf") //nolint:errcheck Expect(fs.FileExists("foobarTarget")).To(Equal(true)) err := fs.Symlink("foobarTarget", "foobarSymlink") @@ -482,7 +482,7 @@ var _ = Describe("FakeFileSystem", func() { Context("when there is an error", func() { It("return the error", func() { - fs.WriteFileString("foobarTarget", "asdfasdf") + fs.WriteFileString("foobarTarget", "asdfasdf") //nolint:errcheck Expect(fs.FileExists("foobarTarget")).To(Equal(true)) err := fs.Symlink("foobarTarget", "foobarSymlink") @@ -499,7 +499,7 @@ var _ = Describe("FakeFileSystem", func() { Describe("RegisterReadFileError", func() { It("errors when specified path is read", func() { - fs.WriteFileString("/some/path", "asdfasdf") + fs.WriteFileString("/some/path", "asdfasdf") //nolint:errcheck fs.RegisterReadFileError("/some/path", errors.New("read error")) @@ -510,7 +510,7 @@ var _ = Describe("FakeFileSystem", func() { Describe("UnregisterReadFileError", func() { It("does not throw an error", func() { - fs.WriteFileString("/some/path", "asdfasdf") + fs.WriteFileString("/some/path", "asdfasdf") //nolint:errcheck fs.RegisterReadFileError("/some/path", errors.New("read error")) fs.UnregisterReadFileError("/some/path") @@ -521,7 +521,7 @@ var _ = Describe("FakeFileSystem", func() { Context("When UnregisterReadFileError is called without registering an error", func() { It("should not panic or throw an error", func() { - fs.WriteFileString("/some/path", "asdfasdf") + fs.WriteFileString("/some/path", "asdfasdf") //nolint:errcheck fs.UnregisterReadFileError("/some/path") @@ -533,7 +533,7 @@ var _ = Describe("FakeFileSystem", func() { Describe("ReadFileWithOpts", func() { It("reads the file", func() { - fs.WriteFileQuietly("foo", []byte("hello")) + fs.WriteFileQuietly("foo", []byte("hello")) //nolint:errcheck writtenContent, err := fs.ReadFileWithOpts("foo", boshsys.ReadOpts{}) Expect(err).ToNot(HaveOccurred()) @@ -541,9 +541,9 @@ var _ = Describe("FakeFileSystem", func() { }) It("Records the number of times the method was called", func() { - fs.WriteFileQuietly("foo", []byte("hello")) - fs.ReadFileWithOpts("foo", boshsys.ReadOpts{}) - fs.ReadFileWithOpts("foo", boshsys.ReadOpts{Quiet: true}) + fs.WriteFileQuietly("foo", []byte("hello")) //nolint:errcheck + fs.ReadFileWithOpts("foo", boshsys.ReadOpts{}) //nolint:errcheck + fs.ReadFileWithOpts("foo", boshsys.ReadOpts{Quiet: true}) //nolint:errcheck Expect(fs.ReadFileWithOptsCallCount).To(Equal(2)) }) @@ -551,7 +551,7 @@ var _ = Describe("FakeFileSystem", func() { Describe("WriteFileQuietly", func() { It("Writes the file", func() { - fs.WriteFileQuietly("foo", []byte("hello")) + fs.WriteFileQuietly("foo", []byte("hello")) //nolint:errcheck writtenContent, err := fs.ReadFileString("foo") Expect(err).ToNot(HaveOccurred()) @@ -559,8 +559,8 @@ var _ = Describe("FakeFileSystem", func() { }) It("Records the number of times the method was called", func() { - fs.WriteFileQuietly("foo", []byte("hello")) - fs.WriteFileQuietly("bar", []byte("hello")) + fs.WriteFileQuietly("foo", []byte("hello")) //nolint:errcheck + fs.WriteFileQuietly("bar", []byte("hello")) //nolint:errcheck Expect(fs.WriteFileQuietlyCallCount).To(Equal(2)) }) @@ -607,7 +607,7 @@ var _ = Describe("FakeFileSystem", func() { Describe("WriteFile", func() { It("Writes the file", func() { - fs.WriteFile("foo", []byte("hello")) + fs.WriteFile("foo", []byte("hello")) //nolint:errcheck writtenContent, err := fs.ReadFileString("foo") Expect(err).ToNot(HaveOccurred()) @@ -615,8 +615,8 @@ var _ = Describe("FakeFileSystem", func() { }) It("Records the number of times the method was called", func() { - fs.WriteFile("foo", []byte("hello")) - fs.WriteFile("bar", []byte("hello")) + fs.WriteFile("foo", []byte("hello")) //nolint:errcheck + fs.WriteFile("bar", []byte("hello")) //nolint:errcheck Expect(fs.WriteFileCallCount).To(Equal(2)) }) diff --git a/system/os_file_system.go b/system/os_file_system.go index 6c9b08ad..4b127ddd 100644 --- a/system/os_file_system.go +++ b/system/os_file_system.go @@ -2,15 +2,13 @@ package system import ( "bytes" + "errors" "io" - "io/ioutil" "os" "os/exec" "path/filepath" "strings" - "errors" - "github.com/bmatcuk/doublestar" fsWrapper "github.com/charlievieth/fs" bosherr "github.com/cloudfoundry/bosh-utils/errors" @@ -170,7 +168,7 @@ func (fs *osFileSystem) ConvergeFileContents(path string, content []byte, opts . } defer file.Close() - src, err := ioutil.ReadAll(file) + src, err := io.ReadAll(file) if err != nil { return true, bosherr.WrapErrorf(err, "Reading file %s", path) } @@ -216,7 +214,7 @@ func (fs *osFileSystem) ReadFileWithOpts(path string, opts ReadOpts) (content [] defer file.Close() - content, err = ioutil.ReadAll(file) + content, err = io.ReadAll(file) if err != nil { err = bosherr.WrapErrorf(err, "Reading file content %s", path) return @@ -245,7 +243,7 @@ func (fs *osFileSystem) FileExists(path string) bool { func (fs *osFileSystem) Rename(oldPath, newPath string) (err error) { fs.logger.Debug(fs.logTag, "Renaming %s to %s", oldPath, newPath) - fs.RemoveAll(newPath) + fs.RemoveAll(newPath) //nolint:errcheck return fsWrapper.Rename(oldPath, newPath) } @@ -254,16 +252,16 @@ func (fs *osFileSystem) Symlink(oldPath, newPath string) error { source, target, err := fs.symlinkPaths(oldPath, newPath) if err != nil { - bosherr.WrapErrorf(err, "Getting absolute paths for target and path links: %s %s", oldPath, newPath) + bosherr.WrapErrorf(err, "Getting absolute paths for target and path links: %s %s", oldPath, newPath) //nolint:errcheck } if fi, err := fs.Lstat(target); err == nil { if fi.Mode()&os.ModeSymlink != 0 { // Symlink - new, err := fs.Readlink(target) + targetPath, err := fs.Readlink(target) if err != nil { return bosherr.WrapErrorf(err, "Reading link for %s", target) } - if filepath.Clean(source) == filepath.Clean(new) { + if filepath.Clean(source) == filepath.Clean(targetPath) { return nil } } @@ -274,7 +272,7 @@ func (fs *osFileSystem) Symlink(oldPath, newPath string) error { containingDir := filepath.Dir(target) if !fs.FileExists(containingDir) { - fs.MkdirAll(containingDir, os.FileMode(0700)) + fs.MkdirAll(containingDir, os.FileMode(0700)) //nolint:errcheck } return fsWrapper.Symlink(source, target) @@ -376,7 +374,7 @@ func (fs *osFileSystem) TempFile(prefix string) (file File, err error) { if fs.tempRoot == "" && fs.requiresTempRoot { return nil, errors.New("Set a temp directory root with ChangeTempRoot before making temp files") } - return ioutil.TempFile(fs.tempRoot, prefix) + return os.CreateTemp(fs.tempRoot, prefix) } func (fs *osFileSystem) TempDir(prefix string) (path string, err error) { @@ -384,7 +382,7 @@ func (fs *osFileSystem) TempDir(prefix string) (path string, err error) { if fs.tempRoot == "" && fs.requiresTempRoot { return "", errors.New("Set a temp directory root with ChangeTempRoot before making temp directories") } - return ioutil.TempDir(fs.tempRoot, prefix) + return os.MkdirTemp(fs.tempRoot, prefix) } func (fs *osFileSystem) ChangeTempRoot(tempRootPath string) error { @@ -416,7 +414,7 @@ func (fs *osFileSystem) Walk(root string, walkFunc filepath.WalkFunc) error { return filepath.Walk(root, walkFunc) } -func (fs *osFileSystem) runCommand(cmd string) (string, error) { +func (fs *osFileSystem) runCommand(cmd string) (string, error) { //nolint:unused var stdout bytes.Buffer shCmd := exec.Command("sh", "-c", cmd) shCmd.Stdout = &stdout diff --git a/system/os_file_system_test.go b/system/os_file_system_test.go index ee515c50..7d402e12 100644 --- a/system/os_file_system_test.go +++ b/system/os_file_system_test.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "os/exec" osuser "os/user" @@ -36,7 +35,7 @@ func readFile(file *os.File) string { return "" } - return string(buf.Bytes()) + return buf.String() } var _ = Describe("OS FileSystem", func() { @@ -44,12 +43,12 @@ var _ = Describe("OS FileSystem", func() { BeforeEach(func() { var err error - TempDir, err = ioutil.TempDir("", "bosh-utils-") + TempDir, err = os.MkdirTemp("", "bosh-utils-") Expect(err).ToNot(HaveOccurred()) }) AfterEach(func() { - os.RemoveAll(TempDir) + os.RemoveAll(TempDir) //nolint:errcheck }) It("home dir", func() { @@ -167,7 +166,7 @@ var _ = Describe("OS FileSystem", func() { err = os.Chmod(compPath, os.FileMode(0666)) Expect(err).ToNot(HaveOccurred()) - fileStat, err := os.Stat(testPath) + fileStat, err := os.Stat(testPath) //nolint:ineffassign,staticcheck compStat, err := os.Stat(compPath) Expect(err).ToNot(HaveOccurred()) Expect(fileStat.Mode()).To(Equal(compStat.Mode())) @@ -178,7 +177,7 @@ var _ = Describe("OS FileSystem", func() { err = os.Chmod(compPath, os.FileMode(0644)) Expect(err).ToNot(HaveOccurred()) - fileStat, err = os.Stat(testPath) + fileStat, err = os.Stat(testPath) //nolint:ineffassign,staticcheck compStat, err = os.Stat(compPath) Expect(err).ToNot(HaveOccurred()) Expect(fileStat.Mode()).To(Equal(compStat.Mode())) @@ -193,8 +192,8 @@ var _ = Describe("OS FileSystem", func() { Expect(err).ToNot(HaveOccurred()) - file.Write([]byte("testing new file")) - file.Close() + file.Write([]byte("testing new file")) //nolint:errcheck + file.Close() //nolint:errcheck createdFile, err := os.Open(testPath) Expect(err).ToNot(HaveOccurred()) @@ -245,21 +244,21 @@ var _ = Describe("OS FileSystem", func() { Expect(err).ToNot(HaveOccurred()) Expect(written).To(BeTrue()) - file.Close() + file.Close() //nolint:errcheck file, err = os.Open(testPath) Expect(err).ToNot(HaveOccurred()) Expect(readFile(file)).To(Equal("second write")) - file.Close() - file, err = os.Open(testPath) - defer file.Close() + file.Close() //nolint:errcheck + file, err = os.Open(testPath) //nolint:ineffassign,staticcheck + defer file.Close() //nolint:staticcheck written, err = osFs.ConvergeFileContents(testPath, []byte("second write")) Expect(err).ToNot(HaveOccurred()) Expect(written).To(BeFalse()) Expect(readFile(file)).To(Equal("second write")) - file.Close() + file.Close() //nolint:errcheck }) It("does create file if dry run option is set", func() { @@ -300,7 +299,7 @@ var _ = Describe("OS FileSystem", func() { Expect(err).ToNot(HaveOccurred()) Expect(written).To(BeTrue()) - file.Close() + file.Close() //nolint:errcheck file, err = os.Open(testPath) Expect(err).ToNot(HaveOccurred()) Expect(readFile(file)).To(Equal("initial write")) @@ -310,11 +309,11 @@ var _ = Describe("OS FileSystem", func() { Expect(err).ToNot(HaveOccurred()) Expect(written).To(BeTrue()) - file.Close() + file.Close() //nolint:errcheck file, err = os.Open(testPath) Expect(err).ToNot(HaveOccurred()) Expect(readFile(file)).To(Equal("initial write")) - file.Close() + file.Close() //nolint:errcheck }) }) @@ -325,7 +324,7 @@ var _ = Describe("OS FileSystem", func() { f, err := os.OpenFile(testPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(0200)) Expect(err).ToNot(HaveOccurred()) - f.Close() + f.Close() //nolint:errcheck defer os.Remove(testPath) err = osFs.WriteFile(testPath, []byte("test")) @@ -403,7 +402,7 @@ var _ = Describe("OS FileSystem", func() { osFs := NewOsFileSystem(logger) testPath := filepath.Join(TempDir, "ReadFileTestFile") - osFs.WriteFileQuietly(testPath, []byte("some contents")) + osFs.WriteFileQuietly(testPath, []byte("some contents")) //nolint:errcheck defer os.Remove(testPath) beforeCount := logger.DebugCallCount() @@ -423,7 +422,7 @@ var _ = Describe("OS FileSystem", func() { osFs := NewOsFileSystem(logger) testPath := filepath.Join(TempDir, "ReadFileTestFile") - osFs.WriteFileQuietly(testPath, []byte("some contents")) + osFs.WriteFileQuietly(testPath, []byte("some contents")) //nolint:errcheck defer os.Remove(testPath) beforeCount := logger.DebugCallCount() @@ -445,7 +444,7 @@ var _ = Describe("OS FileSystem", func() { Expect(osFs.FileExists(testPath)).To(BeFalse()) - osFs.WriteFileString(testPath, "initial write") + osFs.WriteFileString(testPath, "initial write") //nolint:errcheck defer os.Remove(testPath) Expect(osFs.FileExists(testPath)).To(BeTrue()) @@ -458,10 +457,10 @@ var _ = Describe("OS FileSystem", func() { oldFilePath := filepath.Join(oldPath, "test.txt") newPath := filepath.Join(tempDir, "new") - os.Mkdir(oldPath, os.ModePerm) + os.Mkdir(oldPath, os.ModePerm) //nolint:errcheck f, err := os.Create(oldFilePath) Expect(err).ToNot(HaveOccurred()) - f.Close() + f.Close() //nolint:errcheck err = osFs.Rename(oldPath, newPath) Expect(err).ToNot(HaveOccurred()) @@ -478,11 +477,11 @@ var _ = Describe("OS FileSystem", func() { osFs := createOsFs() filePath := filepath.Join(TempDir, "SymlinkTestFile") containingDir := filepath.Join(TempDir, "SubDir") - os.Remove(containingDir) + os.Remove(containingDir) //nolint:errcheck symlinkPath := filepath.Join(containingDir, "SymlinkTestSymlink") - osFs.WriteFileString(filePath, "some content") - osFs.Symlink(filePath, symlinkPath) + osFs.WriteFileString(filePath, "some content") //nolint:errcheck + osFs.Symlink(filePath, symlinkPath) //nolint:errcheck symlinkStats, err := os.Lstat(symlinkPath) Expect(err).ToNot(HaveOccurred()) @@ -498,9 +497,9 @@ var _ = Describe("OS FileSystem", func() { symlinkPath := filepath.Join(TempDir, "SymlinkTestIdempotent1Symlink") osFs := createOsFs() - osFs.WriteFileString(filePath, "some content") + osFs.WriteFileString(filePath, "some content") //nolint:errcheck - osFs.Symlink(filePath, symlinkPath) + osFs.Symlink(filePath, symlinkPath) //nolint:errcheck firstSymlinkStats, err := os.Lstat(symlinkPath) Expect(err).ToNot(HaveOccurred()) @@ -519,8 +518,8 @@ var _ = Describe("OS FileSystem", func() { otherFilePath := filepath.Join(TempDir, "SymlinkTestIdempotent1OtherFile") symlinkPath := filepath.Join(TempDir, "SymlinkTestIdempotent1Symlink") - osFs.WriteFileString(filePath, "some content") - osFs.WriteFileString(otherFilePath, "other content") + osFs.WriteFileString(filePath, "some content") //nolint:errcheck + osFs.WriteFileString(otherFilePath, "other content") //nolint:errcheck err := osFs.Symlink(otherFilePath, symlinkPath) Expect(err).ToNot(HaveOccurred()) @@ -542,8 +541,8 @@ var _ = Describe("OS FileSystem", func() { filePath := filepath.Join(TempDir, "SymlinkTestIdempotent1File") symlinkPath := filepath.Join(TempDir, "SymlinkTestIdempotent1Symlink") - osFs.WriteFileString(filePath, "some content") - osFs.WriteFileString(symlinkPath, "some other content") + osFs.WriteFileString(filePath, "some content") //nolint:errcheck + osFs.WriteFileString(symlinkPath, "some other content") //nolint:errcheck err := osFs.Symlink(filePath, symlinkPath) Expect(err).ToNot(HaveOccurred()) @@ -563,13 +562,14 @@ var _ = Describe("OS FileSystem", func() { fileB := filepath.Join(TempDir, "file_b") symlinkPath := filepath.Join(TempDir, "symlink") - osFs.WriteFileString(fileA, "file a") - osFs.WriteFileString(fileB, "file b") + osFs.WriteFileString(fileA, "file a") //nolint:errcheck + osFs.WriteFileString(fileB, "file b") //nolint:errcheck err := osFs.Symlink(fileA, symlinkPath) Expect(err).ToNot(HaveOccurred()) - os.Remove(fileA) // creates a broken symlink + // creates a broken symlink + os.Remove(fileA) //nolint:errcheck err = osFs.Symlink(fileB, symlinkPath) Expect(err).ToNot(HaveOccurred()) @@ -604,7 +604,7 @@ var _ = Describe("OS FileSystem", func() { Expect(err).To(Succeed()) Expect(s).To(Equal(Content)) - names, err := ioutil.ReadDir(targetDir) + names, err := os.ReadDir(targetDir) Expect(err).To(Succeed()) Expect(names).To(HaveLen(1)) Expect(names[0].Name()).To(Equal("file.txt")) @@ -634,7 +634,7 @@ var _ = Describe("OS FileSystem", func() { containingDir := filepath.Join(TempDir, "SubDir") symlinkPath := filepath.Join(containingDir, "SymlinkTestSymlink") - osFs.WriteFileString(targetPath, "some content") + osFs.WriteFileString(targetPath, "some content") //nolint:errcheck defer os.Remove(targetPath) err := osFs.Symlink(targetPath, symlinkPath) @@ -667,9 +667,9 @@ var _ = Describe("OS FileSystem", func() { }) AfterEach(func() { - os.Remove(symlinkPath) - os.Remove(targetPath) - os.Remove(containingDir) + os.Remove(symlinkPath) //nolint:errcheck + os.Remove(targetPath) //nolint:errcheck + os.Remove(containingDir) //nolint:errcheck }) Context("when the link does not exist", func() { @@ -759,12 +759,12 @@ var _ = Describe("OS FileSystem", func() { }) AfterEach(func() { - os.Remove(TempDir) + os.Remove(TempDir) //nolint:errcheck }) Context("a temp root is set", func() { BeforeEach(func() { - osFs.ChangeTempRoot(TempDir) + osFs.ChangeTempRoot(TempDir) //nolint:errcheck }) It("creates temp files under that root", func() { @@ -807,7 +807,7 @@ var _ = Describe("OS FileSystem", func() { Expect(err).ToNot(HaveOccurred()) defer os.Remove(dstFile.Name()) - err = osFs.CopyFile(srcPath, dstFile.Name()) + err = osFs.CopyFile(srcPath, dstFile.Name()) //nolint:ineffassign,staticcheck fooContent, err := osFs.ReadFileString(dstFile.Name()) Expect(err).ToNot(HaveOccurred()) @@ -869,7 +869,7 @@ var _ = Describe("OS FileSystem", func() { srcPath := "test_assets/test_copy_dir_entries" dstPath, err := osFs.TempDir("CopyDirTestDir") Expect(err).ToNot(HaveOccurred()) - defer osFs.RemoveAll(dstPath) + defer osFs.RemoveAll(dstPath) //nolint:errcheck err = osFs.CopyDir(srcPath, dstPath) Expect(err).ToNot(HaveOccurred()) @@ -899,7 +899,7 @@ var _ = Describe("OS FileSystem", func() { srcPath := "test_assets/test_copy_dir_entries" dstPath, err := osFs.TempDir("CopyDirTestDir") Expect(err).ToNot(HaveOccurred()) - defer osFs.RemoveAll(dstPath) + defer osFs.RemoveAll(dstPath) //nolint:errcheck err = osFs.CopyDir(srcPath, dstPath) Expect(err).ToNot(HaveOccurred()) @@ -946,7 +946,7 @@ var _ = Describe("OS FileSystem", func() { dstPath := dstFile.Name() defer os.Remove(dstPath) - dstFile.Close() + dstFile.Close() //nolint:errcheck err = osFs.RemoveAll(dstFile.Name()) Expect(err).ToNot(HaveOccurred()) diff --git a/system/os_file_system_unix_test.go b/system/os_file_system_unix_test.go index 54b393ef..d4456a71 100644 --- a/system/os_file_system_unix_test.go +++ b/system/os_file_system_unix_test.go @@ -6,12 +6,11 @@ package system_test import ( "os" "path/filepath" + "runtime" + "syscall" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "runtime" - "syscall" ) var _ = Describe("OS FileSystem", func() { @@ -116,7 +115,7 @@ var _ = Describe("OS FileSystem", func() { dstPath, err := osFs.TempDir("CopyDirTestDest") Expect(err).ToNot(HaveOccurred()) - defer osFs.RemoveAll(dstPath) + defer osFs.RemoveAll(dstPath) //nolint:errcheck err = osFs.CopyDir(srcPath, dstPath) Expect(err).ToNot(HaveOccurred()) diff --git a/system/os_file_system_windows_test.go b/system/os_file_system_windows_test.go index 7c588852..4859389e 100644 --- a/system/os_file_system_windows_test.go +++ b/system/os_file_system_windows_test.go @@ -9,8 +9,6 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - "io/ioutil" - fsWrapper "github.com/charlievieth/fs" ) @@ -40,7 +38,7 @@ var _ = Describe("Windows Specific tests", func() { dstPath, err := osFs.TempDir("CopyDirTestDest") Expect(err).ToNot(HaveOccurred()) - defer osFs.RemoveAll(dstPath) + defer osFs.RemoveAll(dstPath) //nolint:errcheck err = osFs.CopyDir(srcPath, dstPath) Expect(err).ToNot(HaveOccurred()) @@ -57,10 +55,10 @@ var _ = Describe("Windows Specific tests", func() { rootPath, longPath := randLongPath() err := fsWrapper.MkdirAll(longPath, 0755) - defer fsWrapper.RemoveAll(rootPath) + defer fsWrapper.RemoveAll(rootPath) //nolint:errcheck Expect(err).ToNot(HaveOccurred()) - dstFile, err := ioutil.TempFile(`\\?\`+longPath, "") + dstFile, err := os.CreateTemp(`\\?\`+longPath, "") Expect(err).ToNot(HaveOccurred()) dstPath := path.Join(longPath, filepath.Base(dstFile.Name())) @@ -81,8 +79,8 @@ var _ = Describe("Windows Specific tests", func() { // Alert future developers that a previously unimplemented // function in the os package is now implemented on Windows. It("fails if os features are implemented in Windows", func() { - Expect(os.Chown("", 0, 0)).To(Equal(&os.PathError{"chown", "", syscall.EWINDOWS}), "os.Chown") - Expect(os.Lchown("", 0, 0)).To(Equal(&os.PathError{"lchown", "", syscall.EWINDOWS}), "os.Lchown") + Expect(os.Chown("", 0, 0)).To(Equal(&os.PathError{"chown", "", syscall.EWINDOWS}), "os.Chown") //nolint:govet + Expect(os.Lchown("", 0, 0)).To(Equal(&os.PathError{"lchown", "", syscall.EWINDOWS}), "os.Lchown") //nolint:govet Expect(os.Getuid()).To(Equal(-1), "os.Getuid") Expect(os.Geteuid()).To(Equal(-1), "os.Geteuid") diff --git a/system/os_long_path_test.go b/system/os_long_path_test.go index a37d8c49..fa16920f 100644 --- a/system/os_long_path_test.go +++ b/system/os_long_path_test.go @@ -2,7 +2,6 @@ package system_test import ( "bytes" - "io/ioutil" "os" "path/filepath" "strings" @@ -45,15 +44,15 @@ var _ = Describe("Long Paths", func() { AfterEach(func() { // don't check for error! - fs.RemoveAll(rootPath) - fs.Remove(LongPath) + fs.RemoveAll(rootPath) //nolint:errcheck + fs.Remove(LongPath) //nolint:errcheck }) // TODO: make sure we can cleanup before running tests It("the fs package can cleanup long paths and dirs", func() { f, err := fs.Create(LongPath) Expect(err).To(Succeed()) - f.Close() + f.Close() //nolint:errcheck Expect(fs.Remove(LongPath)).To(Succeed()) Expect(fs.MkdirAll(LongDir, 0755)).To(Succeed()) @@ -74,7 +73,7 @@ var _ = Describe("Long Paths", func() { It("can create and delete a file with a long path", func() { f, err := osFs.OpenFile(LongPath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644) Expect(err).To(Succeed()) - f.Close() + f.Close() //nolint:errcheck Expect(osFs.RemoveAll(LongPath)).To(Succeed()) }) @@ -126,7 +125,7 @@ var _ = Describe("Long Paths", func() { for newPath == LongPath { newPath = filepath.Join(os.TempDir(), randSeq(LONG_PATH_LENGTH)) } - defer fs.Remove(newPath) + defer fs.Remove(newPath) //nolint:errcheck Expect(osFs.WriteFileString(LongPath, "abc")).To(Succeed()) Expect(osFs.Rename(LongPath, newPath)).To(Succeed()) @@ -138,7 +137,7 @@ var _ = Describe("Long Paths", func() { for newPath == LongPath { newPath = filepath.Join(os.TempDir(), randSeq(LONG_PATH_LENGTH)) } - defer fs.Remove(newPath) + defer fs.Remove(newPath) //nolint:errcheck Expect(osFs.WriteFileString(LongPath, "abc")).To(Succeed()) Expect(osFs.Symlink(LongPath, newPath)).To(Succeed()) @@ -157,7 +156,7 @@ var _ = Describe("Long Paths", func() { for newPath == LongPath { newPath = filepath.Join(os.TempDir(), randSeq(LONG_PATH_LENGTH)) } - defer fs.Remove(newPath) + defer fs.Remove(newPath) //nolint:errcheck Expect(osFs.WriteFileString(LongPath, content)).To(Succeed()) Expect(osFs.CopyFile(LongPath, newPath)).To(Succeed()) @@ -174,7 +173,7 @@ var _ = Describe("Long Paths", func() { lastFilePath := filepath.Join(LongDir, "a.txt") Expect(osFs.WriteFileString(lastFilePath, content)).To(Succeed()) - newRoot, err := ioutil.TempDir("", "") + newRoot, err := os.MkdirTemp("", "") Expect(err).To(Succeed()) // expFilePath should contain the contents of lastFilePath. diff --git a/system/system_suite_test.go b/system/system_suite_test.go index b128c270..f53736e3 100644 --- a/system/system_suite_test.go +++ b/system/system_suite_test.go @@ -2,17 +2,16 @@ package system_test import ( "bytes" - "io/ioutil" "math/rand" + "os" "path/filepath" "runtime" + "testing" "time" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" - - "testing" ) const Windows = runtime.GOOS == "windows" @@ -44,7 +43,7 @@ var _ = AfterSuite(func() { func randSeq(n int) string { const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - rand.Seed(time.Now().UnixNano()) + rand.Seed(time.Now().UnixNano()) //nolint:staticcheck b := make([]byte, n) for i := range b { b[i] = letters[rand.Intn(len(letters))] @@ -55,7 +54,7 @@ func randSeq(n int) string { // returns a long directory path rooted at a temp directory root. // To cleanup delete the root directory. func randLongPath() (root, path string) { - tmpdir, err := ioutil.TempDir("", "") + tmpdir, err := os.MkdirTemp("", "") Expect(err).To(Succeed()) volume := tmpdir + string(filepath.Separator) buf := bytes.NewBufferString(volume)