chore: Refactor use of deprecated io/ioutil package (#1285)

This commit is contained in:
David Simansky 2022-09-27 15:28:15 +02:00 committed by GitHub
parent c86cc0f5f7
commit e0bbcc2d08
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 51 additions and 62 deletions

View File

@ -9,7 +9,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"os" "os"
@ -177,7 +176,7 @@ func TestClient_New_NonemptyAborts(t *testing.T) {
// Write a visible file which should cause an abort // Write a visible file which should cause an abort
visibleFile := filepath.Join(root, "file.txt") visibleFile := filepath.Join(root, "file.txt")
if err := ioutil.WriteFile(visibleFile, []byte{}, 0644); err != nil { if err := os.WriteFile(visibleFile, []byte{}, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -201,7 +200,7 @@ func TestClient_New_HiddenFilesIgnored(t *testing.T) {
// Create a hidden file that should be ignored. // Create a hidden file that should be ignored.
hiddenFile := filepath.Join(root, ".envrc") hiddenFile := filepath.Join(root, ".envrc")
if err := ioutil.WriteFile(hiddenFile, []byte{}, 0644); err != nil { if err := os.WriteFile(hiddenFile, []byte{}, 0644); err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -1,7 +1,7 @@
package cmd package cmd
import ( import (
"io/ioutil" "os"
"testing" "testing"
fn "knative.dev/kn-plugin-func" fn "knative.dev/kn-plugin-func"
@ -63,7 +63,7 @@ annotations: {}
labels: [] labels: []
created: 2021-01-01T00:00:00+00:00 created: 2021-01-01T00:00:00+00:00
` `
if err := ioutil.WriteFile("func.yaml", []byte(funcYaml), 0600); err != nil { if err := os.WriteFile("func.yaml", []byte(funcYaml), 0600); err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -3,7 +3,6 @@ package cmd
import ( import (
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"strings" "strings"
@ -241,7 +240,7 @@ func newInvokeConfig(newClient ClientFactory) (cfg invokeConfig, err error) {
// If file was passed, read it in as data // If file was passed, read it in as data
if cfg.File != "" { if cfg.File != "" {
b, err := ioutil.ReadFile(cfg.File) b, err := os.ReadFile(cfg.File)
if err != nil { if err != nil {
return cfg, err return cfg, err
} }

View File

@ -2,7 +2,6 @@ package config
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
@ -79,7 +78,7 @@ func (c Config) Save(path string) (err error) {
if bb, err = yaml.Marshal(&c); err != nil { if bb, err = yaml.Marshal(&c); err != nil {
return return
} }
return ioutil.WriteFile(path, bb, os.ModePerm) return os.WriteFile(path, bb, os.ModePerm)
} }
// Path is derived in the following order, from lowest // Path is derived in the following order, from lowest

View File

@ -5,7 +5,6 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -299,7 +298,7 @@ func (c *credentialsProvider) getCredentials(ctx context.Context, image string)
var errNoCredentialHelperConfigured = errors.New("no credential helper configure") var errNoCredentialHelperConfigured = errors.New("no credential helper configure")
func getCredentialHelperFromConfig(confFilePath string) (string, error) { func getCredentialHelperFromConfig(confFilePath string) (string, error) {
data, err := ioutil.ReadFile(confFilePath) data, err := os.ReadFile(confFilePath)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -321,7 +320,7 @@ func setCredentialHelperToConfig(confFilePath, helper string) error {
configData := make(map[string]interface{}) configData := make(map[string]interface{})
if data, err := ioutil.ReadFile(confFilePath); err == nil { if data, err := os.ReadFile(confFilePath); err == nil {
err = json.Unmarshal(data, &configData) err = json.Unmarshal(data, &configData)
if err != nil { if err != nil {
return err return err
@ -335,7 +334,7 @@ func setCredentialHelperToConfig(confFilePath, helper string) error {
return err return err
} }
err = ioutil.WriteFile(confFilePath, data, 0600) err = os.WriteFile(confFilePath, data, 0600)
if err != nil { if err != nil {
return err return err
} }
@ -399,7 +398,7 @@ func listCredentialHelpers() []string {
helpers := make(map[string]bool) helpers := make(map[string]bool)
for _, p := range paths { for _, p := range paths {
fss, err := ioutil.ReadDir(p) fss, err := os.ReadDir(p)
if err != nil { if err != nil {
continue continue
} }

View File

@ -15,7 +15,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"math/big" "math/big"
"net" "net"
"net/http" "net/http"
@ -566,7 +565,7 @@ func withPopulatedDockerAuthConfig(t *testing.T) {
}` }`
configJSON = fmt.Sprintf(configJSON, base64.StdEncoding.EncodeToString([]byte(dockerIoUser+":"+dockerIoUserPwd))) configJSON = fmt.Sprintf(configJSON, base64.StdEncoding.EncodeToString([]byte(dockerIoUser+":"+dockerIoUserPwd)))
err = ioutil.WriteFile(dockerConfigPath, []byte(configJSON), 0600) err = os.WriteFile(dockerConfigPath, []byte(configJSON), 0600)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -595,7 +594,7 @@ func withPopulatedFuncAuthConfig(t *testing.T) {
base64.StdEncoding.EncodeToString([]byte(dockerIoUser+":"+dockerIoUserPwd)), base64.StdEncoding.EncodeToString([]byte(dockerIoUser+":"+dockerIoUserPwd)),
base64.StdEncoding.EncodeToString([]byte(quayIoUser+":"+quayIoUserPwd))) base64.StdEncoding.EncodeToString([]byte(quayIoUser+":"+quayIoUserPwd)))
err = ioutil.WriteFile(authConfig, []byte(authJSON), 0600) err = os.WriteFile(authConfig, []byte(authJSON), 0600)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -669,7 +668,7 @@ func handlerForCredHelper(t *testing.T, credHelper credentials.Helper) http.Hand
var serverURL string var serverURL string
if uri == "get" || uri == "erase" { if uri == "get" || uri == "erase" {
data, err := ioutil.ReadAll(request.Body) data, err := io.ReadAll(request.Body)
if err != nil { if err != nil {
writer.WriteHeader(http.StatusInternalServerError) writer.WriteHeader(http.StatusInternalServerError)
return return

View File

@ -10,7 +10,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"os" "os"
@ -338,7 +337,7 @@ func withCleanHome(t *testing.T) func() {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
homeName = "USERPROFILE" homeName = "USERPROFILE"
} }
tmpDir, err := ioutil.TempDir("", "tmpHome") tmpDir, err := os.MkdirTemp("", "tmpHome")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -4,7 +4,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"html/template" "html/template"
"io/ioutil"
"os" "os"
"regexp" "regexp"
"strings" "strings"
@ -113,7 +112,7 @@ func writeMarkdown(c *cobra.Command, name string, opts TemplateOptions) error {
re := regexp.MustCompile(`[^\S\r\n]+\n`) re := regexp.MustCompile(`[^\S\r\n]+\n`)
data := re.ReplaceAll(out.Bytes(), []byte{'\n'}) // trim white spaces before EOL data := re.ReplaceAll(out.Bytes(), []byte{'\n'}) // trim white spaces before EOL
if err := ioutil.WriteFile(targetDir+"/"+name+".md", data, 0666); err != nil { if err := os.WriteFile(targetDir+"/"+name+".md", data, 0666); err != nil {
return err return err
} }
return nil return nil

View File

@ -5,8 +5,8 @@ import (
"crypto/md5" "crypto/md5"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io"
"io/fs" "io/fs"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -124,12 +124,12 @@ func TestFileSystems(t *testing.T) {
return err return err
} }
localFileContent, err := ioutil.ReadFile(localFilePath) localFileContent, err := os.ReadFile(localFilePath)
if err != nil { if err != nil {
return err return err
} }
embeddedFileContent, err := ioutil.ReadAll(embeddedFile) embeddedFileContent, err := io.ReadAll(embeddedFile)
if err != nil { if err != nil {
return err return err
} }

View File

@ -3,7 +3,6 @@ package function
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
@ -494,7 +493,7 @@ var contentiousFiles = []string{
// contentiousFilesIn the given directory // contentiousFilesIn the given directory
func contentiousFilesIn(dir string) (contentious []string, err error) { func contentiousFilesIn(dir string) (contentious []string, err error) {
files, err := ioutil.ReadDir(dir) files, err := os.ReadDir(dir)
for _, file := range files { for _, file := range files {
for _, name := range contentiousFiles { for _, name := range contentiousFiles {
if file.Name() == name { if file.Name() == name {
@ -508,7 +507,7 @@ func contentiousFilesIn(dir string) (contentious []string, err error) {
// effectivelyEmpty directories are those which have no visible files // effectivelyEmpty directories are those which have no visible files
func isEffectivelyEmpty(dir string) (bool, error) { func isEffectivelyEmpty(dir string) (bool, error) {
// Check for any non-hidden files // Check for any non-hidden files
files, err := ioutil.ReadDir(dir) files, err := os.ReadDir(dir)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -531,7 +530,7 @@ func hasInitializedFunction(path string) (bool, error) {
} }
return false, err // invalid path or access error return false, err // invalid path or access error
} }
bb, err := ioutil.ReadFile(filename) bb, err := os.ReadFile(filename)
if err != nil { if err != nil {
return false, err return false, err
} }

View File

@ -22,10 +22,10 @@ func (v Volume) String() string {
// Returns array of error messages, empty if no errors are found // Returns array of error messages, empty if no errors are found
// //
// Allowed settings: // Allowed settings:
// - secret: example-secret # mount Secret as Volume // - secret: example-secret # mount Secret as Volume
// path: /etc/secret-volume // path: /etc/secret-volume
// - configMap: example-configMap # mount ConfigMap as Volume // - configMap: example-configMap # mount ConfigMap as Volume
// path: /etc/configMap-volume // path: /etc/configMap-volume
func validateVolumes(volumes []Volume) (errors []string) { func validateVolumes(volumes []Volume) (errors []string) {
for i, vol := range volumes { for i, vol := range volumes {

View File

@ -98,8 +98,9 @@ func invoke(ctx context.Context, c *Client, f Function, target string, m InvokeM
// 'remote': remote environment; first available instance (error if none) // 'remote': remote environment; first available instance (error if none)
// '<environment>': A valid alternate target which contains instances. // '<environment>': A valid alternate target which contains instances.
// '<url>': An explicit URL // '<url>': An explicit URL
// '': Default if no target is passed is to first use local, then remote. // ”: Default if no target is passed is to first use local, then remote.
// errors if neither are available. //
// errors if neither are available.
func invocationRoute(ctx context.Context, c *Client, f Function, target string) (string, error) { func invocationRoute(ctx context.Context, c *Client, f Function, target string) (string, error) {
// TODO: this function has code-smell; will de-smellify it in next pass. // TODO: this function has code-smell; will de-smellify it in next pass.
if target == EnvironmentLocal { if target == EnvironmentLocal {

View File

@ -4,7 +4,6 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"net/url" "net/url"
"os" "os"
"path" "path"
@ -492,7 +491,7 @@ func (r *Repository) Write(path string) (err error) {
clone *git.Repository clone *git.Repository
wt *git.Worktree wt *git.Worktree
) )
if tempDir, err = ioutil.TempDir("", "func"); err != nil { if tempDir, err = os.MkdirTemp("", "func"); err != nil {
return return
} }
if clone, err = git.PlainClone(tempDir, false, // not bare if clone, err = git.PlainClone(tempDir, false, // not bare

View File

@ -7,7 +7,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"net" "net"
"net/http" "net/http"
@ -318,7 +317,7 @@ func TestBuildContextUpload(t *testing.T) {
switch hdr.Name { switch hdr.Name {
case ".": case ".":
case "Dockerfile": case "Dockerfile":
bs, err := ioutil.ReadAll(tr) bs, err := io.ReadAll(tr)
if err != nil { if err != nil {
return types.ImageBuildResponse{}, err return types.ImageBuildResponse{}, err
} }
@ -326,7 +325,7 @@ func TestBuildContextUpload(t *testing.T) {
return types.ImageBuildResponse{}, errors.New("bad content for Dockerfile") return types.ImageBuildResponse{}, errors.New("bad content for Dockerfile")
} }
case "a.txt": case "a.txt":
bs, err := ioutil.ReadAll(tr) bs, err := io.ReadAll(tr)
if err != nil { if err != nil {
return types.ImageBuildResponse{}, err return types.ImageBuildResponse{}, err
} }
@ -346,11 +345,11 @@ func TestBuildContextUpload(t *testing.T) {
impl := &mockImpl{ impl := &mockImpl{
BuildFn: func(config *api.Config) (*api.Result, error) { BuildFn: func(config *api.Config) (*api.Result, error) {
err := ioutil.WriteFile(config.AsDockerfile, dockerfileContent, 0644) err := os.WriteFile(config.AsDockerfile, dockerfileContent, 0644)
if err != nil { if err != nil {
return nil, err return nil, err
} }
err = ioutil.WriteFile(filepath.Join(filepath.Dir(config.AsDockerfile), "a.txt"), atxtContent, 0644) err = os.WriteFile(filepath.Join(filepath.Dir(config.AsDockerfile), "a.txt"), atxtContent, 0644)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -3,7 +3,7 @@ package main
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"io/ioutil" "os"
"github.com/alecthomas/jsonschema" "github.com/alecthomas/jsonschema"
@ -37,5 +37,5 @@ func generateFuncYamlSchema() error {
} }
// write schema to the file // write schema to the file
return ioutil.WriteFile("schema/func_yaml-schema.json", indentedSchema.Bytes(), 0644) return os.WriteFile("schema/func_yaml-schema.json", indentedSchema.Bytes(), 0644)
} }

View File

@ -8,7 +8,6 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"net" "net"
urlPkg "net/url" urlPkg "net/url"
"os" "os"
@ -355,7 +354,7 @@ func NewSSHClientConfig(url *urlPkg.URL, credentialsConfig Config) (*ssh.ClientC
} }
func publicKey(path string, passphrase []byte, passPhraseCallback PassPhraseCallback) (ssh.Signer, error) { func publicKey(path string, passphrase []byte, passPhraseCallback PassPhraseCallback) (ssh.Signer, error) {
key, err := ioutil.ReadFile(path) key, err := os.ReadFile(path)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to read key file: %w", err) return nil, fmt.Errorf("failed to read key file: %w", err)
} }

View File

@ -2,7 +2,7 @@ package e2e
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
@ -31,7 +31,7 @@ func (s SimpleTestEvent) pushTo(url string, t *testing.T) (body string, statusCo
} }
t.Logf("event POST %v -> %v", url, resp.Status) t.Logf("event POST %v -> %v", url, resp.Status)
defer resp.Body.Close() defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body) b, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return "", resp.StatusCode, fmt.Errorf("Error reading response body: %v", err.Error()) return "", resp.StatusCode, fmt.Errorf("Error reading response body: %v", err.Error())
} }

View File

@ -2,7 +2,7 @@ package e2e
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
@ -48,7 +48,7 @@ func (f FunctionHttpResponsivenessValidator) Validate(t *testing.T, project Func
defer resp.Body.Close() defer resp.Body.Close()
t.Logf("%v %v -> %v", method, url, resp.Status) t.Logf("%v %v -> %v", method, url, resp.Status)
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
t.Fatalf("Error reading response body: %v", err.Error()) t.Fatalf("Error reading response body: %v", err.Error())
} }

View File

@ -2,8 +2,6 @@ package e2e
import ( import (
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -45,14 +43,12 @@ func Update(t *testing.T, knFunc *TestShellCmdRunner, project *FunctionTestProje
project.IsNewRevision = true project.IsNewRevision = true
} }
//
// projectUpdater offers methods to update the project source content by the // projectUpdater offers methods to update the project source content by the
// source provided on update_templates folder // source provided on update_templates folder
// The strategy used consists in // The strategy used consists in
// 1. Create a temporary project folder with some files from original test folder (such as func.yaml, pom.xml) // 1. Create a temporary project folder with some files from original test folder (such as func.yaml, pom.xml)
// 2. Copy recursivelly all files from ./update_template/<runtime>/<template>/** to the temporary project folder // 2. Copy recursivelly all files from ./update_template/<runtime>/<template>/** to the temporary project folder
// 3. Replace current project folder by the temporary one (rm -rf <project folder> && mv <tmp folder> <project folder> // 3. Replace current project folder by the temporary one (rm -rf <project folder> && mv <tmp folder> <project folder>
//
type projectUpdater struct { type projectUpdater struct {
retainList []string // List of files to retain from original test project retainList []string // List of files to retain from original test project
} }
@ -133,12 +129,16 @@ func (p projectUpdater) UpdateFolderContent(templatePath string, project *Functi
// walkThru recursive visit files in the filesystem and invokes fn for each of them // walkThru recursive visit files in the filesystem and invokes fn for each of them
// it can be replaced in future by filepath.WalkDir when project moves to 1.16+) // it can be replaced in future by filepath.WalkDir when project moves to 1.16+)
func (p projectUpdater) walkThru(dir string, fn func(path string, f os.FileInfo) error) error { func (p projectUpdater) walkThru(dir string, fn func(path string, f os.FileInfo) error) error {
files, err := ioutil.ReadDir(dir) files, err := os.ReadDir(dir)
if err != nil { if err != nil {
return err return err
} }
for _, file := range files { for _, file := range files {
err := fn(dir, file) fileInfo, err := file.Info()
if err != nil {
return err
}
err = fn(dir, fileInfo)
if err != nil { if err != nil {
return err return err
} }

View File

@ -17,7 +17,6 @@ package testing
import ( import (
"fmt" "fmt"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"net/http/cgi" "net/http/cgi"
@ -32,7 +31,8 @@ import (
// Using the given path, create it as a new directory and return a deferrable // Using the given path, create it as a new directory and return a deferrable
// which will remove it. // which will remove it.
// usage: // usage:
// defer using(t, "testdata/example.com/someExampleTest")() //
// defer using(t, "testdata/example.com/someExampleTest")()
func Using(t *testing.T, root string) func() { func Using(t *testing.T, root string) func() {
t.Helper() t.Helper()
mkdir(t, root) mkdir(t, root)
@ -103,7 +103,7 @@ func tempdir(t *testing.T) string {
// NOTE: Not using t.TempDir() because it is sometimes helpful during // NOTE: Not using t.TempDir() because it is sometimes helpful during
// debugging to skip running the returned deferred cleanup function // debugging to skip running the returned deferred cleanup function
// and manually inspect the contents of the test's temp directory. // and manually inspect the contents of the test's temp directory.
d, err := ioutil.TempDir("", "dir") d, err := os.MkdirTemp("", "dir")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -132,7 +132,6 @@ func cd(t *testing.T, dir string) {
// TestRepoURI starts serving HTTP git server with GIT_PROJECT_ROOT=$(pwd)/testdata // TestRepoURI starts serving HTTP git server with GIT_PROJECT_ROOT=$(pwd)/testdata
// and returns URL for project named `name` under the git root. // and returns URL for project named `name` under the git root.
// //
//
// For example TestRepoURI("my-repo", t) returns string that could look like: // For example TestRepoURI("my-repo", t) returns string that could look like:
// http://localhost:4242/my-repo.git // http://localhost:4242/my-repo.git
func TestRepoURI(name string, t *testing.T) string { func TestRepoURI(name string, t *testing.T) string {
@ -158,7 +157,7 @@ func WithExecutable(t *testing.T, name, goSrc string) {
goSrcPath := filepath.Join(binDir, fmt.Sprintf("%s.go", name)) goSrcPath := filepath.Join(binDir, fmt.Sprintf("%s.go", name))
err = ioutil.WriteFile(goSrcPath, err = os.WriteFile(goSrcPath,
[]byte(goSrc), []byte(goSrc),
0400) 0400)
if err != nil { if err != nil {
@ -181,7 +180,7 @@ go.exe run GO_SCRIPT_PATH %*
runnerScriptPath := filepath.Join(binDir, runnerScriptName) runnerScriptPath := filepath.Join(binDir, runnerScriptName)
runnerScriptSrc = strings.ReplaceAll(runnerScriptSrc, "GO_SCRIPT_PATH", goSrcPath) runnerScriptSrc = strings.ReplaceAll(runnerScriptSrc, "GO_SCRIPT_PATH", goSrcPath)
err = ioutil.WriteFile(runnerScriptPath, []byte(runnerScriptSrc), 0700) err = os.WriteFile(runnerScriptPath, []byte(runnerScriptSrc), 0700)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }