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"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
@ -177,7 +176,7 @@ func TestClient_New_NonemptyAborts(t *testing.T) {
// Write a visible file which should cause an abort
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)
}
@ -201,7 +200,7 @@ func TestClient_New_HiddenFilesIgnored(t *testing.T) {
// Create a hidden file that should be ignored.
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)
}

View File

@ -1,7 +1,7 @@
package cmd
import (
"io/ioutil"
"os"
"testing"
fn "knative.dev/kn-plugin-func"
@ -63,7 +63,7 @@ annotations: {}
labels: []
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)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,7 +4,6 @@ import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"os"
"regexp"
"strings"
@ -113,7 +112,7 @@ func writeMarkdown(c *cobra.Command, name string, opts TemplateOptions) error {
re := regexp.MustCompile(`[^\S\r\n]+\n`)
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 nil

View File

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

View File

@ -3,7 +3,6 @@ package function
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
@ -494,7 +493,7 @@ var contentiousFiles = []string{
// contentiousFilesIn the given directory
func contentiousFilesIn(dir string) (contentious []string, err error) {
files, err := ioutil.ReadDir(dir)
files, err := os.ReadDir(dir)
for _, file := range files {
for _, name := range contentiousFiles {
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
func isEffectivelyEmpty(dir string) (bool, error) {
// Check for any non-hidden files
files, err := ioutil.ReadDir(dir)
files, err := os.ReadDir(dir)
if err != nil {
return false, err
}
@ -531,7 +530,7 @@ func hasInitializedFunction(path string) (bool, error) {
}
return false, err // invalid path or access error
}
bb, err := ioutil.ReadFile(filename)
bb, err := os.ReadFile(filename)
if err != nil {
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
//
// Allowed settings:
// - secret: example-secret # mount Secret as Volume
// path: /etc/secret-volume
// - configMap: example-configMap # mount ConfigMap as Volume
// path: /etc/configMap-volume
// - secret: example-secret # mount Secret as Volume
// path: /etc/secret-volume
// - configMap: example-configMap # mount ConfigMap as Volume
// path: /etc/configMap-volume
func validateVolumes(volumes []Volume) (errors []string) {
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)
// '<environment>': A valid alternate target which contains instances.
// '<url>': An explicit URL
// '': Default if no target is passed is to first use local, then remote.
// errors if neither are available.
// ”: Default if no target is passed is to first use local, then remote.
//
// errors if neither are available.
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.
if target == EnvironmentLocal {

View File

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

View File

@ -7,7 +7,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
@ -318,7 +317,7 @@ func TestBuildContextUpload(t *testing.T) {
switch hdr.Name {
case ".":
case "Dockerfile":
bs, err := ioutil.ReadAll(tr)
bs, err := io.ReadAll(tr)
if err != nil {
return types.ImageBuildResponse{}, err
}
@ -326,7 +325,7 @@ func TestBuildContextUpload(t *testing.T) {
return types.ImageBuildResponse{}, errors.New("bad content for Dockerfile")
}
case "a.txt":
bs, err := ioutil.ReadAll(tr)
bs, err := io.ReadAll(tr)
if err != nil {
return types.ImageBuildResponse{}, err
}
@ -346,11 +345,11 @@ func TestBuildContextUpload(t *testing.T) {
impl := &mockImpl{
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 {
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 {
return nil, err
}

View File

@ -3,7 +3,7 @@ package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"os"
"github.com/alecthomas/jsonschema"
@ -37,5 +37,5 @@ func generateFuncYamlSchema() error {
}
// 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"
"errors"
"fmt"
"io/ioutil"
"net"
urlPkg "net/url"
"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) {
key, err := ioutil.ReadFile(path)
key, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read key file: %w", err)
}

View File

@ -2,7 +2,7 @@ package e2e
import (
"fmt"
"io/ioutil"
"io"
"net/http"
"strings"
"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)
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
if err != nil {
return "", resp.StatusCode, fmt.Errorf("Error reading response body: %v", err.Error())
}

View File

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

View File

@ -2,8 +2,6 @@ package e2e
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -45,14 +43,12 @@ func Update(t *testing.T, knFunc *TestShellCmdRunner, project *FunctionTestProje
project.IsNewRevision = true
}
//
// projectUpdater offers methods to update the project source content by the
// source provided on update_templates folder
// The strategy used consists in
// 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
// 3. Replace current project folder by the temporary one (rm -rf <project folder> && mv <tmp folder> <project folder>
//
type projectUpdater struct {
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
// 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 {
files, err := ioutil.ReadDir(dir)
files, err := os.ReadDir(dir)
if err != nil {
return err
}
for _, file := range files {
err := fn(dir, file)
fileInfo, err := file.Info()
if err != nil {
return err
}
err = fn(dir, fileInfo)
if err != nil {
return err
}

View File

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