refactor: move from io/ioutil to io and os packages (#1096)

The io/ioutil package has been deprecated as of Go 1.16, see
https://golang.org/doc/go1.16#ioutil. This commit replaces the existing
io/ioutil functions with their new definitions in io and os packages.

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
This commit is contained in:
Eng Zer Jun 2021-11-18 06:31:42 +08:00 коммит произвёл GitHub
Родитель cd438069f5
Коммит e812bc82b8
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
25 изменённых файлов: 50 добавлений и 59 удалений

Просмотреть файл

@ -5,7 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"os"
@ -86,7 +86,7 @@ func (m *Multitenancy) DetermineSnatFeatureOnHost(snatFile, nmAgentSupportedApis
// Check if we've already retrieved NMAgent version and determined whether to disable snat on host
if jsonFile, retrieveSnatConfigErr = os.Open(snatFile); retrieveSnatConfigErr == nil {
bytes, _ := ioutil.ReadAll(jsonFile)
bytes, _ := io.ReadAll(jsonFile)
jsonFile.Close()
if retrieveSnatConfigErr = json.Unmarshal(bytes, &snatConfig); retrieveSnatConfigErr != nil {
log.Errorf("[cni-net] failed to unmarshal to snatConfig with error %v",
@ -110,7 +110,7 @@ func (m *Multitenancy) DetermineSnatFeatureOnHost(snatFile, nmAgentSupportedApis
if resp.StatusCode == http.StatusOK {
var bodyBytes []byte
// if the list of APIs (strings) contains the nmAgentSnatSupportAPI we will disable snat on host
if bodyBytes, retrieveSnatConfigErr = ioutil.ReadAll(resp.Body); retrieveSnatConfigErr == nil {
if bodyBytes, retrieveSnatConfigErr = io.ReadAll(resp.Body); retrieveSnatConfigErr == nil {
bodyStr := string(bodyBytes)
if !strings.Contains(bodyStr, nmAgentSnatAndDnsSupportAPI) {
snatConfig.EnableSnatForDns = true

Просмотреть файл

@ -6,7 +6,7 @@ package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"os"
"reflect"
"time"
@ -78,7 +78,7 @@ func validateConfig(jsonBytes []byte) error {
func getCmdArgsFromEnv() (string, *skel.CmdArgs, error) {
log.Printf("Going to read from stdin")
stdinData, err := ioutil.ReadAll(os.Stdin)
stdinData, err := io.ReadAll(os.Stdin)
if err != nil {
return "", nil, fmt.Errorf("error reading from stdin: %v", err)
}

Просмотреть файл

@ -4,7 +4,6 @@
package cnm
import (
"io/ioutil"
"net/http"
"net/url"
"os"
@ -90,7 +89,7 @@ func (plugin *Plugin) EnableDiscovery() error {
// Write the listener URL to the spec file.
fileName := path + plugin.Name + ".spec"
url := plugin.Listener.URL.String()
err := ioutil.WriteFile(fileName, []byte(url), 0o644)
err := os.WriteFile(fileName, []byte(url), 0o644)
return err
}

Просмотреть файл

@ -6,7 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"net/url"
@ -55,7 +55,7 @@ type mockdo struct {
func (m *mockdo) Do(req *http.Request) (*http.Response, error) {
byteArray, _ := json.Marshal(m.objToReturn)
body := ioutil.NopCloser(bytes.NewReader(byteArray))
body := io.NopCloser(bytes.NewReader(byteArray))
return &http.Response{
StatusCode: m.httpStatusCodeToReturn,
@ -146,8 +146,8 @@ func TestMain(m *testing.M) {
res *http.Response
)
tmpFileState, err := ioutil.TempFile(os.TempDir(), "cns-*.json")
tmpLogDir, err := ioutil.TempDir("", "cns-")
tmpFileState, err := os.CreateTemp(os.TempDir(), "cns-*.json")
tmpLogDir, err := os.MkdirTemp("", "cns-")
fmt.Printf("logdir: %+v", tmpLogDir)
if err != nil {

Просмотреть файл

@ -3,7 +3,6 @@ package configuration
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
@ -93,7 +92,7 @@ func ReadConfig() (*CNSConfig, error) {
}
func readConfigFromFile(f string) (*CNSConfig, error) {
content, err := ioutil.ReadFile(f)
content, err := os.ReadFile(f)
if err != nil {
return nil, errors.Wrapf(err, "failed to read config file %s", f)
}

Просмотреть файл

@ -9,7 +9,6 @@ import (
"errors"
"fmt"
"go/types"
"io/ioutil"
"net"
"os"
"os/exec"
@ -112,7 +111,7 @@ func DeleteLoopbackAdapter(adapterName string) error {
// This function gets the flattened network configuration (compliant with azure cni) in byte array format
func getNetworkConfig(configFilePath string) ([]byte, error) {
content, err := ioutil.ReadFile(configFilePath)
content, err := os.ReadFile(configFilePath)
if err != nil {
return nil, err
}

Просмотреть файл

@ -8,7 +8,7 @@ import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"os"
@ -169,7 +169,7 @@ func StartProcess(path string, args []string) error {
// GetHostMetadata - retrieve VM metadata from wireserver
func GetHostMetadata(fileName string) (Metadata, error) {
content, err := ioutil.ReadFile(fileName)
content, err := os.ReadFile(fileName)
if err == nil {
var metadata Metadata
if err = json.Unmarshal(content, &metadata); err == nil {
@ -225,7 +225,7 @@ func SaveHostMetadata(metadata Metadata, fileName string) error {
return fmt.Errorf("[Telemetry] marshal data failed with err %+v", err)
}
if err = ioutil.WriteFile(fileName, dataBytes, 0o644); err != nil {
if err = os.WriteFile(fileName, dataBytes, 0o644); err != nil {
log.Printf("[Telemetry] Writing metadata to file failed: %v", err)
}
@ -257,7 +257,7 @@ func GetAzureCloud(url string) (string, error) {
return "", fmt.Errorf("Bad http status:%v", resp.Status)
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}

Просмотреть файл

@ -6,8 +6,8 @@ package ipam
import (
"encoding/json"
"errors"
"io/ioutil"
"net"
"os"
"runtime"
"strings"
@ -123,7 +123,7 @@ func (source *fileIpamSource) refresh() error {
}
func getSDNInterfaces(fileLocation string) (*NetworkInterfaces, error) {
data, err := ioutil.ReadFile(fileLocation)
data, err := os.ReadFile(fileLocation)
if err != nil {
return nil, err
}

Просмотреть файл

@ -5,7 +5,6 @@ package log
import (
"fmt"
"io/ioutil"
"os"
"strings"
"testing"
@ -65,7 +64,7 @@ func TestPid(t *testing.T) {
fn := l.GetLogDirectory() + logName + ".log"
defer os.Remove(fn)
logBytes, err := ioutil.ReadFile(fn)
logBytes, err := os.ReadFile(fn)
if err != nil {
t.Fatalf("Failed to read log, %v", err)
}

Просмотреть файл

@ -2,7 +2,7 @@ package main
import (
"bytes"
"io/ioutil"
"io"
"testing"
"github.com/stretchr/testify/require"
@ -51,7 +51,7 @@ func testCommand(t *testing.T, tests []*testCases) {
require.NoError(t, err)
out, err := ioutil.ReadAll(b)
out, err := io.ReadAll(b)
require.NoError(t, err)
if tt.wantErr {
require.NotEmpty(t, out)

Просмотреть файл

@ -2,7 +2,7 @@ package server
import (
"encoding/json"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
@ -35,7 +35,7 @@ func TestGetNPMCacheHandler(t *testing.T) {
status, http.StatusOK)
}
byteArray, err := ioutil.ReadAll(rr.Body)
byteArray, err := io.ReadAll(rr.Body)
if err != nil {
t.Errorf("failed to read response's data : %w", err)
}

Просмотреть файл

@ -2,7 +2,7 @@ package controllers
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"testing"
@ -1116,7 +1116,7 @@ func TestTranslateEgress(t *testing.T) {
func readPolicyYaml(policyYaml string) (*networkingv1.NetworkPolicy, error) {
decode := scheme.Codecs.UniversalDeserializer().Decode
policyYamlLocation := filepath.Join(testPolicyDir, policyYaml)
b, err := ioutil.ReadFile(policyYamlLocation)
b, err := os.ReadFile(policyYamlLocation)
if err != nil {
return nil, err
}

Просмотреть файл

@ -5,9 +5,10 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"log"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
@ -31,7 +32,7 @@ type Converter struct {
// NpmCacheFromFile initialize NPM cache from file.
func (c *Converter) NpmCacheFromFile(npmCacheJSONFile string) error {
byteArray, err := ioutil.ReadFile(npmCacheJSONFile)
byteArray, err := os.ReadFile(npmCacheJSONFile)
if err != nil {
return fmt.Errorf("failed to read %s file : %w", npmCacheJSONFile, err)
}
@ -60,7 +61,7 @@ func (c *Converter) NpmCache() error {
return fmt.Errorf("failed to request NPM Cache : %w", err)
}
defer resp.Body.Close()
byteArray, err := ioutil.ReadAll(resp.Body)
byteArray, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response's data : %w", err)
}

Просмотреть файл

@ -3,7 +3,7 @@ package parse
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
NPMIPtable "github.com/Azure/azure-container-networking/npm/pkg/dataplane/iptables"
@ -44,7 +44,7 @@ func Iptables(tableName string) (*NPMIPtable.Table, error) {
// IptablesFile creates a Go object from specified iptable by reading from an iptables-save file.
func IptablesFile(tableName string, iptableSaveFile string) (*NPMIPtable.Table, error) {
iptableBuffer := bytes.NewBuffer(nil)
byteArray, err := ioutil.ReadFile(iptableSaveFile)
byteArray, err := os.ReadFile(iptableSaveFile)
if err != nil {
return nil, fmt.Errorf("%w", err)
}

Просмотреть файл

@ -6,7 +6,6 @@ package platform
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
@ -38,7 +37,7 @@ const (
// GetOSInfo returns OS version information.
func GetOSInfo() string {
info, err := ioutil.ReadFile("/proc/version")
info, err := os.ReadFile("/proc/version")
if err != nil {
return "unknown"
}

Просмотреть файл

@ -1,7 +1,6 @@
package processlock
import (
"io/ioutil"
"os"
"path/filepath"
"strconv"
@ -73,7 +72,7 @@ func TestFileLock(t *testing.T) {
require.NoError(t, err, "Calling Release lock again should not throw error for already released lock:%v", err)
// read lockfile contents to check if contents match with pid of current process
b, errRead := ioutil.ReadFile(tt.lockfileName)
b, errRead := os.ReadFile(tt.lockfileName)
require.NoError(t, errRead, "Got error reading lockfile:%v", errRead)
pidStr := string(b)
pid, _ := strconv.Atoi(pidStr)

Просмотреть файл

@ -7,7 +7,7 @@ import (
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
)
const (
@ -52,7 +52,7 @@ func (fcert *linuxTlsCertificateRetriever) GetPrivateKey() (crypto.PrivateKey, e
// ReadFile reads a from disk
func (fcert *linuxTlsCertificateRetriever) readFile() ([]byte, error) {
content, err := ioutil.ReadFile(fcert.settings.TLSCertificatePath)
content, err := os.ReadFile(fcert.settings.TLSCertificatePath)
if err != nil {
return nil, fmt.Errorf("Error reading file from path %s with error: %+v ", fcert.settings.TLSCertificatePath, err)
}

Просмотреть файл

@ -9,7 +9,6 @@ import (
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"math/big"
"os"
"testing"
@ -25,7 +24,7 @@ func TestPemConsumptionLinux(t *testing.T) {
currentDirectory, _ := os.Getwd()
pemLocation := fmt.Sprintf("%s/%s.Pem", currentDirectory, commonName)
ioutil.WriteFile(pemLocation, pemContent, 0o644)
os.WriteFile(pemLocation, pemContent, 0o644)
defer os.Remove(pemLocation)
config := TlsSettings{

Просмотреть файл

@ -7,7 +7,7 @@ import (
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/billgraziano/dpapi"
@ -55,7 +55,7 @@ func (wtls *windowsTlsCertificateRetriever) GetPrivateKey() (crypto.PrivateKey,
// ReadFile reads a from disk
func (wtls *windowsTlsCertificateRetriever) readFile() ([]byte, error) {
content, err := ioutil.ReadFile(wtls.settings.TLSCertificatePath)
content, err := os.ReadFile(wtls.settings.TLSCertificatePath)
if err != nil {
return nil, fmt.Errorf("Error reading file from path %s with error: %+v ", wtls.settings.TLSCertificatePath, err)
}

Просмотреть файл

@ -9,7 +9,6 @@ import (
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"math/big"
"os"
"testing"
@ -28,7 +27,7 @@ func TestPemConsumptionWindows(t *testing.T) {
pemLocation := fmt.Sprintf("%s/%s.Pem", currentDirectory, commonName)
encryptedPem, _ := dpapi.Encrypt(string(pemContent))
ioutil.WriteFile(pemLocation, []byte(encryptedPem), 0o644)
os.WriteFile(pemLocation, []byte(encryptedPem), 0o644)
defer os.Remove(pemLocation)
config := TlsSettings{

Просмотреть файл

@ -6,7 +6,7 @@ package store
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"os"
"path/filepath"
"sync"
@ -71,7 +71,7 @@ func (kvs *jsonFileStore) Read(key string, value interface{}) error {
}
defer file.Close()
b, err := ioutil.ReadAll(file)
b, err := io.ReadAll(file)
if err != nil {
return err
}
@ -133,7 +133,7 @@ func (kvs *jsonFileStore) flush() error {
dir = "."
}
f, err := ioutil.TempFile(dir, file)
f, err := os.CreateTemp(dir, file)
if err != nil {
return fmt.Errorf("cannot create temp file: %v", err)
}

Просмотреть файл

@ -7,7 +7,6 @@ import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
@ -323,7 +322,7 @@ func StartTelemetryService(path string, args []string) error {
func ReadConfigFile(filePath string) (TelemetryConfig, error) {
config := TelemetryConfig{}
b, err := ioutil.ReadFile(filePath)
b, err := os.ReadFile(filePath)
if err != nil {
log.Logf("[Telemetry] Failed to read telemetry config: %v", err)
return config, err

Просмотреть файл

@ -5,7 +5,7 @@ package k8s
import (
"context"
"fmt"
"io/ioutil"
"io"
"math/rand"
"net/http"
@ -74,7 +74,7 @@ func (p *PortForwarder) Forward(ctx context.Context, namespace, labelSelector st
dialer := spdy.NewDialer(p.upgrader, &http.Client{Transport: p.transport}, http.MethodPost, portForwardURL)
ports := []string{fmt.Sprintf("%d:%d", localPort, destPort)}
pf, err := portforward.New(dialer, ports, stopChan, readyChan, ioutil.Discard, ioutil.Discard)
pf, err := portforward.New(dialer, ports, stopChan, readyChan, io.Discard, io.Discard)
if err != nil {
return PortForwardStreamHandle{}, fmt.Errorf("could not create portforwarder: %v", err)
}

Просмотреть файл

@ -6,7 +6,7 @@ package installer
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"os"
"path/filepath"
@ -33,7 +33,7 @@ func LoadConfList(conflistpath string) (rawConflist, error) {
}
defer jsonFile.Close()
byteValue, err := ioutil.ReadAll(jsonFile)
byteValue, err := io.ReadAll(jsonFile)
if err != nil {
return conflist, err
}
@ -99,7 +99,7 @@ func ModifyConflists(conflistpath string, installerConf InstallerConfig, perm os
}
fmt.Printf("🚛 - Installing %v...\n", dstFile)
return ioutil.WriteFile(dstFile, filebytes, perm)
return os.WriteFile(dstFile, filebytes, perm)
}
func PrettyPrint(o interface{}) {

Просмотреть файл

@ -5,7 +5,6 @@ package installer
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
@ -62,12 +61,12 @@ func copyBinaries(filePaths []string, installerConf InstallerConfig, perm os.Fil
}
func copyFile(src string, dst string, perm os.FileMode) error {
data, err := ioutil.ReadFile(src)
data, err := os.ReadFile(src)
if err != nil {
return err
}
err = ioutil.WriteFile(dst, data, perm)
err = os.WriteFile(dst, data, perm)
if err != nil {
return err
}