Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🌱 do not use io/ioutil anymore #1888

Merged
merged 1 commit into from
May 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,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
Expand Down
3 changes: 1 addition & 2 deletions examples/scratch-env/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package main

import (
goflag "flag"
"io/ioutil"
"os"

flag "github.com/spf13/pflag"
Expand Down Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions pkg/client/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ limitations under the License.
package config

import (
"io/ioutil"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ package config

import (
"fmt"
ioutil "io/ioutil"
"os"
"sync"

"k8s.io/apimachinery/pkg/runtime"
Expand Down Expand Up @@ -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
Expand Down
25 changes: 15 additions & 10 deletions pkg/envtest/crd.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"time"
Expand Down Expand Up @@ -282,7 +281,7 @@ func renderCRDs(options *CRDInstallOptions) ([]*apiextensionsv1.CustomResourceDe
var (
err error
info os.FileInfo
files []os.FileInfo
files []string
)

type GVKN struct {
Expand All @@ -304,9 +303,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)
Expand Down Expand Up @@ -390,20 +395,20 @@ 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
crdExts := sets.NewString(".json", ".yaml", ".yml")

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
}
Expand All @@ -420,14 +425,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
}
Expand Down
27 changes: 16 additions & 11 deletions pkg/envtest/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ package envtest
import (
"context"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
Expand Down Expand Up @@ -266,7 +265,7 @@ func (o *WebhookInstallOptions) setupCA() error {
return fmt.Errorf("unable to set up webhook serving certs: %w", 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: %w", err)
Expand All @@ -277,10 +276,10 @@ func (o *WebhookInstallOptions) setupCA() error {
return fmt.Errorf("unable to marshal webhook serving certs: %w", 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: %w", 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: %w", err)
}

Expand Down Expand Up @@ -359,17 +358,23 @@ 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)
if err != nil {
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
Expand All @@ -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
}
Expand Down Expand Up @@ -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
}
9 changes: 4 additions & 5 deletions pkg/internal/testing/controlplane/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ package controlplane
import (
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"path/filepath"
Expand Down Expand Up @@ -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
}

Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pkg/internal/testing/controlplane/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ package controlplane

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"

"k8s.io/client-go/rest"
Expand Down Expand Up @@ -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)
}

Expand Down
4 changes: 2 additions & 2 deletions pkg/internal/testing/controlplane/kubectl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ limitations under the License.
package controlplane_test

import (
"io/ioutil"
"io"

. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
Expand All @@ -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())
})
Expand Down
3 changes: 1 addition & 2 deletions pkg/internal/testing/process/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
Expand Down Expand Up @@ -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
}
Expand Down
3 changes: 1 addition & 2 deletions pkg/internal/testing/process/process_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package process_test

import (
"bytes"
"io/ioutil"
"net"
"net/http"
"net/url"
Expand Down Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions pkg/leaderelection/leader_election.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ package leaderelection
import (
"errors"
"fmt"
"io/ioutil"
"os"

"k8s.io/apimachinery/pkg/util/uuid"
Expand Down Expand Up @@ -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)
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/manager/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"path"
Expand Down Expand Up @@ -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`,
Expand Down Expand Up @@ -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"))
})
Expand Down
3 changes: 1 addition & 2 deletions pkg/webhook/admission/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"

v1 "k8s.io/api/admission/v1"
Expand Down Expand Up @@ -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)
Expand Down
Loading