From 6ef118a662a4a9531c2d8161d6daaa87efe9ccf0 Mon Sep 17 00:00:00 2001 From: Christoph Mewes Date: Fri, 6 May 2022 11:18:00 +0200 Subject: [PATCH] do not use io/ioutil anymore --- .golangci.yml | 4 +++ examples/scratch-env/main.go | 3 +-- pkg/client/config/config_test.go | 5 ++-- pkg/config/config.go | 4 +-- pkg/envtest/crd.go | 25 ++++++++++------- pkg/envtest/webhook.go | 27 +++++++++++-------- .../testing/controlplane/apiserver.go | 9 +++---- pkg/internal/testing/controlplane/auth.go | 4 +-- .../testing/controlplane/kubectl_test.go | 4 +-- pkg/internal/testing/process/process.go | 3 +-- pkg/internal/testing/process/process_test.go | 3 +-- pkg/leaderelection/leader_election.go | 3 +-- pkg/manager/manager_test.go | 6 ++--- pkg/webhook/admission/http.go | 3 +-- pkg/webhook/authentication/http.go | 3 +-- pkg/webhook/conversion/conversion_test.go | 4 +-- pkg/webhook/server.go | 3 +-- pkg/webhook/server_test.go | 8 +++--- 18 files changed, 63 insertions(+), 58 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 68be34b063..20d2ce33b9 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -62,6 +62,10 @@ linters-settings: go: "1.18" stylecheck: go: "1.18" + depguard: + include-go-root: true + packages: + - io/ioutil # https://go.dev/doc/go1.16#ioutil issues: max-same-issues: 0 diff --git a/examples/scratch-env/main.go b/examples/scratch-env/main.go index 6be4d127c2..13b8e03feb 100644 --- a/examples/scratch-env/main.go +++ b/examples/scratch-env/main.go @@ -18,7 +18,6 @@ package main import ( goflag "flag" - "io/ioutil" "os" flag "github.com/spf13/pflag" @@ -83,7 +82,7 @@ func runMain() int { } // TODO(directxman12): add support for writing to a new context in an existing file - kubeconfigFile, err := ioutil.TempFile("", "scratch-env-kubeconfig-") + kubeconfigFile, err := os.CreateTemp("", "scratch-env-kubeconfig-") if err != nil { log.Error(err, "unable to create kubeconfig file, continuing on without it") return 1 diff --git a/pkg/client/config/config_test.go b/pkg/client/config/config_test.go index ed9761e50f..a1f04d9e6e 100644 --- a/pkg/client/config/config_test.go +++ b/pkg/client/config/config_test.go @@ -17,7 +17,6 @@ limitations under the License. package config import ( - "io/ioutil" "os" "path/filepath" "strings" @@ -45,7 +44,7 @@ var _ = Describe("Config", func() { BeforeEach(func() { // create temporary directory for test case var err error - dir, err = ioutil.TempDir("", "cr-test") + dir, err = os.MkdirTemp("", "cr-test") Expect(err).NotTo(HaveOccurred()) // override $HOME/.kube/config @@ -192,7 +191,7 @@ func setConfigs(tc testCase, dir string) { func createFiles(files map[string]string, dir string) error { for path, data := range files { - if err := ioutil.WriteFile(filepath.Join(dir, path), []byte(data), 0644); err != nil { //nolint:gosec + if err := os.WriteFile(filepath.Join(dir, path), []byte(data), 0644); err != nil { //nolint:gosec return err } } diff --git a/pkg/config/config.go b/pkg/config/config.go index f23b02df00..517b172e5b 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -18,7 +18,7 @@ package config import ( "fmt" - ioutil "io/ioutil" + "os" "sync" "k8s.io/apimachinery/pkg/runtime" @@ -96,7 +96,7 @@ func (d *DeferredFileLoader) loadFile() { return } - content, err := ioutil.ReadFile(d.path) + content, err := os.ReadFile(d.path) if err != nil { d.err = fmt.Errorf("could not read file at %s", d.path) return diff --git a/pkg/envtest/crd.go b/pkg/envtest/crd.go index 27e08475ec..540904bbd9 100644 --- a/pkg/envtest/crd.go +++ b/pkg/envtest/crd.go @@ -22,7 +22,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "path/filepath" "time" @@ -281,7 +280,7 @@ func renderCRDs(options *CRDInstallOptions) ([]*apiextensionsv1.CustomResourceDe var ( err error info os.FileInfo - files []os.FileInfo + files []string ) type GVKN struct { @@ -303,9 +302,15 @@ func renderCRDs(options *CRDInstallOptions) ([]*apiextensionsv1.CustomResourceDe } if !info.IsDir() { - filePath, files = filepath.Dir(path), []os.FileInfo{info} - } else if files, err = ioutil.ReadDir(path); err != nil { - return nil, err + filePath, files = filepath.Dir(path), []string{info.Name()} + } else { + entries, err := os.ReadDir(path) + if err != nil { + return nil, err + } + for _, e := range entries { + files = append(files, e.Name()) + } } log.V(1).Info("reading CRDs from path", "path", path) @@ -389,7 +394,7 @@ func modifyConversionWebhooks(crds []*apiextensionsv1.CustomResourceDefinition, } // readCRDs reads the CRDs from files and Unmarshals them into structs. -func readCRDs(basePath string, files []os.FileInfo) ([]*apiextensionsv1.CustomResourceDefinition, error) { +func readCRDs(basePath string, files []string) ([]*apiextensionsv1.CustomResourceDefinition, error) { var crds []*apiextensionsv1.CustomResourceDefinition // White list the file extensions that may contain CRDs @@ -397,12 +402,12 @@ func readCRDs(basePath string, files []os.FileInfo) ([]*apiextensionsv1.CustomRe for _, file := range files { // Only parse allowlisted file types - if !crdExts.Has(filepath.Ext(file.Name())) { + if !crdExts.Has(filepath.Ext(file)) { continue } // Unmarshal CRDs from file into structs - docs, err := readDocuments(filepath.Join(basePath, file.Name())) + docs, err := readDocuments(filepath.Join(basePath, file)) if err != nil { return nil, err } @@ -419,14 +424,14 @@ func readCRDs(basePath string, files []os.FileInfo) ([]*apiextensionsv1.CustomRe crds = append(crds, crd) } - log.V(1).Info("read CRDs from file", "file", file.Name()) + log.V(1).Info("read CRDs from file", "file", file) } return crds, nil } // readDocuments reads documents from file. func readDocuments(fp string) ([][]byte, error) { - b, err := ioutil.ReadFile(fp) + b, err := os.ReadFile(fp) if err != nil { return nil, err } diff --git a/pkg/envtest/webhook.go b/pkg/envtest/webhook.go index 8552d3ba61..f5e6a93cd1 100644 --- a/pkg/envtest/webhook.go +++ b/pkg/envtest/webhook.go @@ -16,7 +16,6 @@ package envtest import ( "context" "fmt" - "io/ioutil" "net" "os" "path/filepath" @@ -266,7 +265,7 @@ func (o *WebhookInstallOptions) setupCA() error { return fmt.Errorf("unable to set up webhook serving certs: %v", err) } - localServingCertsDir, err := ioutil.TempDir("", "envtest-serving-certs-") + localServingCertsDir, err := os.MkdirTemp("", "envtest-serving-certs-") o.LocalServingCertDir = localServingCertsDir if err != nil { return fmt.Errorf("unable to create directory for webhook serving certs: %v", err) @@ -277,10 +276,10 @@ func (o *WebhookInstallOptions) setupCA() error { return fmt.Errorf("unable to marshal webhook serving certs: %v", err) } - if err := ioutil.WriteFile(filepath.Join(localServingCertsDir, "tls.crt"), certData, 0640); err != nil { //nolint:gosec + if err := os.WriteFile(filepath.Join(localServingCertsDir, "tls.crt"), certData, 0640); err != nil { //nolint:gosec return fmt.Errorf("unable to write webhook serving cert to disk: %v", err) } - if err := ioutil.WriteFile(filepath.Join(localServingCertsDir, "tls.key"), keyData, 0640); err != nil { //nolint:gosec + if err := os.WriteFile(filepath.Join(localServingCertsDir, "tls.key"), keyData, 0640); err != nil { //nolint:gosec return fmt.Errorf("unable to write webhook serving key to disk: %v", err) } @@ -359,7 +358,7 @@ func parseWebhook(options *WebhookInstallOptions) error { // returns slice of mutating and validating webhook configurations. func readWebhooks(path string) ([]*admissionv1.MutatingWebhookConfiguration, []*admissionv1.ValidatingWebhookConfiguration, error) { // Get the webhook files - var files []os.FileInfo + var files []string var err error log.V(1).Info("reading Webhooks from path", "path", path) info, err := os.Stat(path) @@ -367,9 +366,15 @@ func readWebhooks(path string) ([]*admissionv1.MutatingWebhookConfiguration, []* return nil, nil, err } if !info.IsDir() { - path, files = filepath.Dir(path), []os.FileInfo{info} - } else if files, err = ioutil.ReadDir(path); err != nil { - return nil, nil, err + path, files = filepath.Dir(path), []string{info.Name()} + } else { + entries, err := os.ReadDir(path) + if err != nil { + return nil, nil, err + } + for _, e := range entries { + files = append(files, e.Name()) + } } // file extensions that may contain Webhooks @@ -379,12 +384,12 @@ func readWebhooks(path string) ([]*admissionv1.MutatingWebhookConfiguration, []* var valHooks []*admissionv1.ValidatingWebhookConfiguration for _, file := range files { // Only parse allowlisted file types - if !resourceExtensions.Has(filepath.Ext(file.Name())) { + if !resourceExtensions.Has(filepath.Ext(file)) { continue } // Unmarshal Webhooks from file into structs - docs, err := readDocuments(filepath.Join(path, file.Name())) + docs, err := readDocuments(filepath.Join(path, file)) if err != nil { return nil, nil, err } @@ -422,7 +427,7 @@ func readWebhooks(path string) ([]*admissionv1.MutatingWebhookConfiguration, []* } } - log.V(1).Info("read webhooks from file", "file", file.Name()) + log.V(1).Info("read webhooks from file", "file", file) } return mutHooks, valHooks, nil } diff --git a/pkg/internal/testing/controlplane/apiserver.go b/pkg/internal/testing/controlplane/apiserver.go index d6a71dc951..c9a1a232ea 100644 --- a/pkg/internal/testing/controlplane/apiserver.go +++ b/pkg/internal/testing/controlplane/apiserver.go @@ -19,7 +19,6 @@ package controlplane import ( "fmt" "io" - "io/ioutil" "net/url" "os" "path/filepath" @@ -385,10 +384,10 @@ func (s *APIServer) populateAPIServerCerts() error { return err } - if err := ioutil.WriteFile(filepath.Join(s.CertDir, "apiserver.crt"), certData, 0640); err != nil { //nolint:gosec + if err := os.WriteFile(filepath.Join(s.CertDir, "apiserver.crt"), certData, 0640); err != nil { //nolint:gosec return err } - if err := ioutil.WriteFile(filepath.Join(s.CertDir, "apiserver.key"), keyData, 0640); err != nil { //nolint:gosec + if err := os.WriteFile(filepath.Join(s.CertDir, "apiserver.key"), keyData, 0640); err != nil { //nolint:gosec return err } @@ -405,10 +404,10 @@ func (s *APIServer) populateAPIServerCerts() error { return err } - if err := ioutil.WriteFile(filepath.Join(s.CertDir, saCertFile), saCert, 0640); err != nil { //nolint:gosec + if err := os.WriteFile(filepath.Join(s.CertDir, saCertFile), saCert, 0640); err != nil { //nolint:gosec return err } - return ioutil.WriteFile(filepath.Join(s.CertDir, saKeyFile), saKey, 0640) //nolint:gosec + return os.WriteFile(filepath.Join(s.CertDir, saKeyFile), saKey, 0640) //nolint:gosec } // Stop stops this process gracefully, waits for its termination, and cleans up diff --git a/pkg/internal/testing/controlplane/auth.go b/pkg/internal/testing/controlplane/auth.go index b2cd4e5e04..16c86a712c 100644 --- a/pkg/internal/testing/controlplane/auth.go +++ b/pkg/internal/testing/controlplane/auth.go @@ -18,7 +18,7 @@ package controlplane import ( "fmt" - "io/ioutil" + "os" "path/filepath" "k8s.io/client-go/rest" @@ -128,7 +128,7 @@ func (c *CertAuthn) Start() error { return fmt.Errorf("start called before configure") } caCrt := c.ca.CA.CertBytes() - if err := ioutil.WriteFile(c.caCrtPath(), caCrt, 0640); err != nil { //nolint:gosec + if err := os.WriteFile(c.caCrtPath(), caCrt, 0640); err != nil { //nolint:gosec return fmt.Errorf("unable to save the client certificate CA to %s: %w", c.caCrtPath(), err) } diff --git a/pkg/internal/testing/controlplane/kubectl_test.go b/pkg/internal/testing/controlplane/kubectl_test.go index d7105b29f2..c09695eecb 100644 --- a/pkg/internal/testing/controlplane/kubectl_test.go +++ b/pkg/internal/testing/controlplane/kubectl_test.go @@ -17,7 +17,7 @@ limitations under the License. package controlplane_test import ( - "io/ioutil" + "io" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -36,7 +36,7 @@ var _ = Describe("Kubectl", func() { stdout, stderr, err := k.Run(args...) Expect(err).NotTo(HaveOccurred()) Expect(stdout).To(ContainSubstring("something")) - bytes, err := ioutil.ReadAll(stderr) + bytes, err := io.ReadAll(stderr) Expect(err).NotTo(HaveOccurred()) Expect(bytes).To(BeEmpty()) }) diff --git a/pkg/internal/testing/process/process.go b/pkg/internal/testing/process/process.go index 531021bb2f..c721ba01af 100644 --- a/pkg/internal/testing/process/process.go +++ b/pkg/internal/testing/process/process.go @@ -20,7 +20,6 @@ import ( "crypto/tls" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -109,7 +108,7 @@ func (ps *State) Init(name string) error { } if ps.Dir == "" { - newDir, err := ioutil.TempDir("", "k8s_test_framework_") + newDir, err := os.MkdirTemp("", "k8s_test_framework_") if err != nil { return err } diff --git a/pkg/internal/testing/process/process_test.go b/pkg/internal/testing/process/process_test.go index 446d06707c..4ea6ae7263 100644 --- a/pkg/internal/testing/process/process_test.go +++ b/pkg/internal/testing/process/process_test.go @@ -18,7 +18,6 @@ package process_test import ( "bytes" - "io/ioutil" "net" "net/http" "net/url" @@ -297,7 +296,7 @@ var _ = Describe("Stop method", func() { var err error Expect(processState.Start(nil, nil)).To(Succeed()) - processState.Dir, err = ioutil.TempDir("", "k8s_test_framework_") + processState.Dir, err = os.MkdirTemp("", "k8s_test_framework_") Expect(err).NotTo(HaveOccurred()) processState.DirNeedsCleaning = true processState.StopTimeout = 400 * time.Millisecond diff --git a/pkg/leaderelection/leader_election.go b/pkg/leaderelection/leader_election.go index 6e74d10d49..ee4fcf4cbe 100644 --- a/pkg/leaderelection/leader_election.go +++ b/pkg/leaderelection/leader_election.go @@ -19,7 +19,6 @@ package leaderelection import ( "errors" "fmt" - "io/ioutil" "os" "k8s.io/apimachinery/pkg/util/uuid" @@ -120,7 +119,7 @@ func getInClusterNamespace() (string, error) { } // Load the namespace file and return its content - namespace, err := ioutil.ReadFile(inClusterNamespacePath) + namespace, err := os.ReadFile(inClusterNamespacePath) if err != nil { return "", fmt.Errorf("error reading namespace file: %w", err) } diff --git a/pkg/manager/manager_test.go b/pkg/manager/manager_test.go index 2d78872579..58a3cc3f5a 100644 --- a/pkg/manager/manager_test.go +++ b/pkg/manager/manager_test.go @@ -20,7 +20,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "io" "net" "net/http" "path" @@ -1186,7 +1186,7 @@ var _ = Describe("manger.Manager", func() { defer resp.Body.Close() Expect(resp.StatusCode).To(Equal(200)) - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) Expect(err).NotTo(HaveOccurred()) Expect(string(data)).To(ContainSubstring("%s\n%s\n%s\n", `# HELP test_one test metric for testing`, @@ -1229,7 +1229,7 @@ var _ = Describe("manger.Manager", func() { defer resp.Body.Close() Expect(resp.StatusCode).To(Equal(http.StatusOK)) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) Expect(err).NotTo(HaveOccurred()) Expect(string(body)).To(Equal("Some debug info")) }) diff --git a/pkg/webhook/admission/http.go b/pkg/webhook/admission/http.go index 3fa8872ff2..f640104786 100644 --- a/pkg/webhook/admission/http.go +++ b/pkg/webhook/admission/http.go @@ -21,7 +21,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" v1 "k8s.io/api/admission/v1" @@ -60,7 +59,7 @@ func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { } defer r.Body.Close() - if body, err = ioutil.ReadAll(r.Body); err != nil { + if body, err = io.ReadAll(r.Body); err != nil { wh.log.Error(err, "unable to read the body from the incoming request") reviewResponse = Errored(http.StatusBadRequest, err) wh.writeResponse(w, reviewResponse) diff --git a/pkg/webhook/authentication/http.go b/pkg/webhook/authentication/http.go index 19f2f9e51c..59832e8a07 100644 --- a/pkg/webhook/authentication/http.go +++ b/pkg/webhook/authentication/http.go @@ -21,7 +21,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" authenticationv1 "k8s.io/api/authentication/v1" @@ -60,7 +59,7 @@ func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { } defer r.Body.Close() - if body, err = ioutil.ReadAll(r.Body); err != nil { + if body, err = io.ReadAll(r.Body); err != nil { wh.log.Error(err, "unable to read the body from the incoming request") reviewResponse = Errored(err) wh.writeResponse(w, reviewResponse) diff --git a/pkg/webhook/conversion/conversion_test.go b/pkg/webhook/conversion/conversion_test.go index 26a6587654..2dd5e2ae0e 100644 --- a/pkg/webhook/conversion/conversion_test.go +++ b/pkg/webhook/conversion/conversion_test.go @@ -19,7 +19,7 @@ package conversion import ( "bytes" "encoding/json" - "io/ioutil" + "io" "net/http" "net/http/httptest" @@ -70,7 +70,7 @@ var _ = Describe("Conversion Webhook", func() { convReview := &apix.ConversionReview{} req := &http.Request{ - Body: ioutil.NopCloser(bytes.NewReader(payload.Bytes())), + Body: io.NopCloser(bytes.NewReader(payload.Bytes())), } webhook.ServeHTTP(respRecorder, req) Expect(json.NewDecoder(respRecorder.Result().Body).Decode(convReview)).To(Succeed()) diff --git a/pkg/webhook/server.go b/pkg/webhook/server.go index 364d0f902e..fbbb237705 100644 --- a/pkg/webhook/server.go +++ b/pkg/webhook/server.go @@ -21,7 +21,6 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "net" "net/http" "os" @@ -241,7 +240,7 @@ func (s *Server) Start(ctx context.Context) error { // load CA to verify client certificate if s.ClientCAName != "" { certPool := x509.NewCertPool() - clientCABytes, err := ioutil.ReadFile(filepath.Join(s.CertDir, s.ClientCAName)) + clientCABytes, err := os.ReadFile(filepath.Join(s.CertDir, s.ClientCAName)) if err != nil { return fmt.Errorf("failed to read client CA cert: %v", err) } diff --git a/pkg/webhook/server_test.go b/pkg/webhook/server_test.go index 03323eede8..2ed986e405 100644 --- a/pkg/webhook/server_test.go +++ b/pkg/webhook/server_test.go @@ -19,7 +19,7 @@ package webhook_test import ( "context" "fmt" - "io/ioutil" + "io" "net" "net/http" @@ -136,7 +136,7 @@ var _ = Describe("Webhook Server", func() { resp, err := client.Get(fmt.Sprintf("https://%s/somepath", testHostPort)) Expect(err).NotTo(HaveOccurred()) defer resp.Body.Close() - return ioutil.ReadAll(resp.Body) + return io.ReadAll(resp.Body) }).Should(Equal([]byte("gadzooks!"))) Expect(server.StartedChecker()(nil)).To(Succeed()) @@ -176,7 +176,7 @@ var _ = Describe("Webhook Server", func() { Expect(err).NotTo(HaveOccurred()) defer resp.Body.Close() - Expect(ioutil.ReadAll(resp.Body)).To(Equal([]byte("gadzooks!"))) + Expect(io.ReadAll(resp.Body)).To(Equal([]byte("gadzooks!"))) }) It("should inject dependencies, if an inject func has been provided already", func() { @@ -201,7 +201,7 @@ var _ = Describe("Webhook Server", func() { resp, err := client.Get(fmt.Sprintf("https://%s/somepath", testHostPort)) Expect(err).NotTo(HaveOccurred()) defer resp.Body.Close() - return ioutil.ReadAll(resp.Body) + return io.ReadAll(resp.Body) }).Should(Equal([]byte("gadzooks!"))) ctxCancel()