do not use ioutil (#9206)

This commit is contained in:
Jacob Gadikian
2022-08-11 01:35:14 +07:00
committed by GitHub
parent 152a2fa5c9
commit a6dde14ec4
59 changed files with 165 additions and 200 deletions

View File

@@ -2,7 +2,7 @@ package kvstore
import (
"fmt"
"io/ioutil"
"os"
"sort"
"testing"
@@ -71,7 +71,7 @@ func TestKVStoreKV(t *testing.T) {
}
func TestPersistentKVStoreKV(t *testing.T) {
dir, err := ioutil.TempDir("/tmp", "abci-kvstore-test") // TODO
dir, err := os.MkdirTemp("/tmp", "abci-kvstore-test") // TODO
if err != nil {
t.Fatal(err)
}
@@ -87,7 +87,7 @@ func TestPersistentKVStoreKV(t *testing.T) {
}
func TestPersistentKVStoreInfo(t *testing.T) {
dir, err := ioutil.TempDir("/tmp", "abci-kvstore-test") // TODO
dir, err := os.MkdirTemp("/tmp", "abci-kvstore-test") // TODO
if err != nil {
t.Fatal(err)
}
@@ -119,7 +119,7 @@ func TestPersistentKVStoreInfo(t *testing.T) {
// add a validator, remove a validator, update a validator
func TestValUpdates(t *testing.T) {
dir, err := ioutil.TempDir("/tmp", "abci-kvstore-test") // TODO
dir, err := os.MkdirTemp("/tmp", "abci-kvstore-test") // TODO
if err != nil {
t.Fatal(err)
}

View File

@@ -3,7 +3,6 @@ package debug
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
@@ -82,7 +81,7 @@ func dumpCmdHandler(_ *cobra.Command, args []string) error {
func dumpDebugData(outDir string, conf *cfg.Config, rpc *rpchttp.HTTP) {
start := time.Now().UTC()
tmpDir, err := ioutil.TempDir(outDir, "tendermint_debug_tmp")
tmpDir, err := os.MkdirTemp(outDir, "tendermint_debug_tmp")
if err != nil {
logger.Error("failed to create temporary directory", "dir", tmpDir, "error", err)
return

View File

@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
@@ -111,5 +110,5 @@ func writeStateJSONToFile(state interface{}, dir, filename string) error {
return fmt.Errorf("failed to encode state dump: %w", err)
}
return ioutil.WriteFile(path.Join(dir, filename), stateJSON, os.ModePerm)
return os.WriteFile(path.Join(dir, filename), stateJSON, os.ModePerm)
}

View File

@@ -3,7 +3,6 @@ package debug
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
@@ -56,7 +55,7 @@ func killCmdHandler(cmd *cobra.Command, args []string) error {
// Create a temporary directory which will contain all the state dumps and
// relevant files and directories that will be compressed into a file.
tmpDir, err := ioutil.TempDir(os.TempDir(), "tendermint_debug_tmp")
tmpDir, err := os.MkdirTemp(os.TempDir(), "tendermint_debug_tmp")
if err != nil {
return fmt.Errorf("failed to create temporary directory: %w", err)
}

View File

@@ -3,7 +3,7 @@ package debug
import (
"context"
"fmt"
"io/ioutil"
"io"
"net/http"
"os"
"path"
@@ -73,10 +73,10 @@ func dumpProfile(dir, addr, profile string, debug int) error {
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read %s profile response body: %w", profile, err)
}
return ioutil.WriteFile(path.Join(dir, fmt.Sprintf("%s.out", profile)), body, os.ModePerm)
return os.WriteFile(path.Join(dir, fmt.Sprintf("%s.out", profile)), body, os.ModePerm)
}

View File

@@ -2,7 +2,6 @@ package commands
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
@@ -168,5 +167,5 @@ func WriteConfigVals(dir string, vals map[string]string) error {
data += fmt.Sprintf("%s = \"%s\"\n", k, v)
}
cfile := filepath.Join(dir, "config.toml")
return ioutil.WriteFile(cfile, []byte(data), 0600)
return os.WriteFile(cfile, []byte(data), 0600)
}

View File

@@ -3,7 +3,7 @@ package config
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"text/template"
@@ -535,7 +535,7 @@ func ResetTestRoot(testName string) *Config {
func ResetTestRootWithChainID(testName string, chainID string) *Config {
// create a unique, concurrency-safe test directory under os.TempDir()
rootDir, err := ioutil.TempDir("", fmt.Sprintf("%s-%s_", chainID, testName))
rootDir, err := os.MkdirTemp("", fmt.Sprintf("%s-%s_", chainID, testName))
if err != nil {
panic(err)
}

View File

@@ -1,7 +1,6 @@
package config
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
@@ -23,7 +22,7 @@ func TestEnsureRoot(t *testing.T) {
require := require.New(t)
// setup temp dir for test
tmpDir, err := ioutil.TempDir("", "config-test")
tmpDir, err := os.MkdirTemp("", "config-test")
require.Nil(err)
defer os.RemoveAll(tmpDir)
@@ -31,7 +30,7 @@ func TestEnsureRoot(t *testing.T) {
EnsureRoot(tmpDir)
// make sure config is set properly
data, err := ioutil.ReadFile(filepath.Join(tmpDir, defaultConfigFilePath))
data, err := os.ReadFile(filepath.Join(tmpDir, defaultConfigFilePath))
require.Nil(err)
if !checkConfig(string(data)) {
@@ -52,7 +51,7 @@ func TestEnsureTestRoot(t *testing.T) {
rootDir := cfg.RootDir
// make sure config is set properly
data, err := ioutil.ReadFile(filepath.Join(rootDir, defaultConfigFilePath))
data, err := os.ReadFile(filepath.Join(rootDir, defaultConfigFilePath))
require.Nil(err)
if !checkConfig(string(data)) {

View File

@@ -4,7 +4,6 @@ import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
@@ -767,11 +766,11 @@ func randConsensusNetWithPeers(
if i < nValidators {
privVal = privVals[i]
} else {
tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
if err != nil {
panic(err)
}
tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
if err != nil {
panic(err)
}
@@ -887,7 +886,7 @@ func (m *mockTicker) Chan() <-chan timeoutInfo {
func (*mockTicker) SetLogger(log.Logger) {}
func newPersistentKVStore() abci.Application {
dir, err := ioutil.TempDir("", "persistent-kvstore")
dir, err := os.MkdirTemp("", "persistent-kvstore")
if err != nil {
panic(err)
}

View File

@@ -5,7 +5,6 @@ import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
@@ -78,7 +77,7 @@ func startNewStateAndWaitForBlock(t *testing.T, consensusReplayConfig *cfg.Confi
)
cs.SetLogger(logger)
bytes, _ := ioutil.ReadFile(cs.config.WalFile())
bytes, _ := os.ReadFile(cs.config.WalFile())
t.Logf("====== WAL: \n\r%X\n", bytes)
err := cs.Start()
@@ -634,7 +633,7 @@ func TestMockProxyApp(t *testing.T) {
}
func tempWALWithData(data []byte) string {
walFile, err := ioutil.TempFile("", "wal")
walFile, err := os.CreateTemp("", "wal")
if err != nil {
panic(fmt.Sprintf("failed to create temp WAL file: %v", err))
}
@@ -1059,7 +1058,7 @@ func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.Commit, error) {
// if its not the first one, we have a full block
if thisBlockParts != nil {
var pbb = new(tmproto.Block)
bz, err := ioutil.ReadAll(thisBlockParts.GetReader())
bz, err := io.ReadAll(thisBlockParts.GetReader())
if err != nil {
panic(err)
}
@@ -1098,7 +1097,7 @@ func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.Commit, error) {
}
}
// grab the last block too
bz, err := ioutil.ReadAll(thisBlockParts.GetReader())
bz, err := io.ReadAll(thisBlockParts.GetReader())
if err != nil {
panic(err)
}

View File

@@ -3,7 +3,6 @@ package consensus
import (
"bytes"
"crypto/rand"
"io/ioutil"
"os"
"path/filepath"
@@ -27,7 +26,7 @@ const (
)
func TestWALTruncate(t *testing.T) {
walDir, err := ioutil.TempDir("", "wal")
walDir, err := os.MkdirTemp("", "wal")
require.NoError(t, err)
defer os.RemoveAll(walDir)
@@ -109,7 +108,7 @@ func TestWALEncoderDecoder(t *testing.T) {
}
func TestWALWrite(t *testing.T) {
walDir, err := ioutil.TempDir("", "wal")
walDir, err := os.MkdirTemp("", "wal")
require.NoError(t, err)
defer os.RemoveAll(walDir)
walFile := filepath.Join(walDir, "wal")
@@ -177,7 +176,7 @@ func TestWALSearchForEndHeight(t *testing.T) {
}
func TestWALPeriodicSync(t *testing.T) {
walDir, err := ioutil.TempDir("", "wal")
walDir, err := os.MkdirTemp("", "wal")
require.NoError(t, err)
defer os.RemoveAll(walDir)

View File

@@ -3,7 +3,7 @@ package armor
import (
"bytes"
"fmt"
"io/ioutil"
"io"
"golang.org/x/crypto/openpgp/armor" // nolint: staticcheck
)
@@ -31,7 +31,7 @@ func DecodeArmor(armorStr string) (blockType string, headers map[string]string,
if err != nil {
return "", nil, nil, err
}
data, err = ioutil.ReadAll(block.Body)
data, err = io.ReadAll(block.Body)
if err != nil {
return "", nil, nil, err
}

View File

@@ -1,7 +1,6 @@
package autofile
import (
"io/ioutil"
"os"
"path/filepath"
"syscall"
@@ -24,7 +23,7 @@ func TestSIGHUP(t *testing.T) {
})
// First, create a temporary directory and move into it
dir, err := ioutil.TempDir("", "sighup_test")
dir, err := os.MkdirTemp("", "sighup_test")
require.NoError(t, err)
t.Cleanup(func() {
os.RemoveAll(dir)
@@ -49,7 +48,7 @@ func TestSIGHUP(t *testing.T) {
require.NoError(t, err)
// Move into a different temporary directory
otherDir, err := ioutil.TempDir("", "sighup_test_other")
otherDir, err := os.MkdirTemp("", "sighup_test_other")
require.NoError(t, err)
defer os.RemoveAll(otherDir)
err = os.Chdir(otherDir)
@@ -79,7 +78,7 @@ func TestSIGHUP(t *testing.T) {
}
// The current directory should be empty
files, err := ioutil.ReadDir(".")
files, err := os.ReadDir(".")
require.NoError(t, err)
assert.Empty(t, files)
}
@@ -87,7 +86,7 @@ func TestSIGHUP(t *testing.T) {
// // Manually modify file permissions, close, and reopen using autofile:
// // We expect the file permissions to be changed back to the intended perms.
// func TestOpenAutoFilePerms(t *testing.T) {
// file, err := ioutil.TempFile("", "permission_test")
// file, err := os.CreateTemp("", "permission_test")
// require.NoError(t, err)
// err = file.Close()
// require.NoError(t, err)
@@ -113,7 +112,7 @@ func TestSIGHUP(t *testing.T) {
func TestAutoFileSize(t *testing.T) {
// First, create an AutoFile writing to a tempfile dir
f, err := ioutil.TempFile("", "sighup_test")
f, err := os.CreateTemp("", "sighup_test")
require.NoError(t, err)
err = f.Close()
require.NoError(t, err)

View File

@@ -2,7 +2,6 @@ package autofile
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"testing"
@@ -122,7 +121,7 @@ func TestRotateFile(t *testing.T) {
}
}()
dir, err := ioutil.TempDir("", "rotate_test")
dir, err := os.MkdirTemp("", "rotate_test")
require.NoError(t, err)
defer os.RemoveAll(dir)
err = os.Chdir(dir)
@@ -151,21 +150,21 @@ func TestRotateFile(t *testing.T) {
require.NoError(t, err)
// Read g.Head.Path+"000"
body1, err := ioutil.ReadFile(g.Head.Path + ".000")
body1, err := os.ReadFile(g.Head.Path + ".000")
assert.NoError(t, err, "Failed to read first rolled file")
if string(body1) != "Line 1\nLine 2\nLine 3\n" {
t.Errorf("got unexpected contents: [%v]", string(body1))
}
// Read g.Head.Path
body2, err := ioutil.ReadFile(g.Head.Path)
body2, err := os.ReadFile(g.Head.Path)
assert.NoError(t, err, "Failed to read first rolled file")
if string(body2) != "Line 4\nLine 5\nLine 6\n" {
t.Errorf("got unexpected contents: [%v]", string(body2))
}
// Make sure there are no files in the current, temporary directory
files, err := ioutil.ReadDir(".")
files, err := os.ReadDir(".")
require.NoError(t, err)
assert.Empty(t, files)

View File

@@ -4,7 +4,6 @@ import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
@@ -19,7 +18,7 @@ func WriteConfigVals(dir string, vals map[string]string) error {
data += fmt.Sprintf("%s = \"%s\"\n", k, v)
}
cfile := filepath.Join(dir, "config.toml")
return ioutil.WriteFile(cfile, []byte(data), 0600)
return os.WriteFile(cfile, []byte(data), 0600)
}
// RunWithArgs executes the given command with the specified command line args

View File

@@ -2,7 +2,7 @@ package cli
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"testing"
@@ -55,7 +55,7 @@ func TestSetupEnv(t *testing.T) {
}
func tempDir() string {
cdir, err := ioutil.TempDir("", "test-cli")
cdir, err := os.MkdirTemp("", "test-cli")
if err != nil {
panic(err)
}

View File

@@ -2,7 +2,7 @@ package log_test
import (
"bytes"
"io/ioutil"
"io"
"strings"
"testing"
@@ -90,11 +90,11 @@ func TestError(t *testing.T) {
}
func BenchmarkTMLoggerSimple(b *testing.B) {
benchmarkRunner(b, log.NewTMLogger(ioutil.Discard), baseInfoMessage)
benchmarkRunner(b, log.NewTMLogger(io.Discard), baseInfoMessage)
}
func BenchmarkTMLoggerContextual(b *testing.B) {
benchmarkRunner(b, log.NewTMLogger(ioutil.Discard), withInfoMessage)
benchmarkRunner(b, log.NewTMLogger(io.Discard), withInfoMessage)
}
func benchmarkRunner(b *testing.B, logger log.Logger, f func(log.Logger)) {

View File

@@ -3,7 +3,7 @@ package log_test
import (
"bytes"
"errors"
"io/ioutil"
"io"
"math"
"regexp"
"testing"
@@ -62,16 +62,16 @@ func TestTMFmtLogger(t *testing.T) {
}
func BenchmarkTMFmtLoggerSimple(b *testing.B) {
benchmarkRunnerKitlog(b, log.NewTMFmtLogger(ioutil.Discard), baseMessage)
benchmarkRunnerKitlog(b, log.NewTMFmtLogger(io.Discard), baseMessage)
}
func BenchmarkTMFmtLoggerContextual(b *testing.B) {
benchmarkRunnerKitlog(b, log.NewTMFmtLogger(ioutil.Discard), withMessage)
benchmarkRunnerKitlog(b, log.NewTMFmtLogger(io.Discard), withMessage)
}
func TestTMFmtLoggerConcurrency(t *testing.T) {
t.Parallel()
testConcurrency(t, log.NewTMFmtLogger(ioutil.Discard), 10000)
testConcurrency(t, log.NewTMFmtLogger(io.Discard), 10000)
}
func benchmarkRunnerKitlog(b *testing.B, logger kitlog.Logger, f func(kitlog.Logger)) {

View File

@@ -4,7 +4,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/signal"
"syscall"
@@ -62,11 +61,11 @@ func FileExists(filePath string) bool {
}
func ReadFile(filePath string) ([]byte, error) {
return ioutil.ReadFile(filePath)
return os.ReadFile(filePath)
}
func MustReadFile(filePath string) []byte {
fileBytes, err := ioutil.ReadFile(filePath)
fileBytes, err := os.ReadFile(filePath)
if err != nil {
Exit(fmt.Sprintf("MustReadFile failed: %v", err))
return nil
@@ -75,7 +74,7 @@ func MustReadFile(filePath string) []byte {
}
func WriteFile(filePath string, contents []byte, mode os.FileMode) error {
return ioutil.WriteFile(filePath, contents, mode)
return os.WriteFile(filePath, contents, mode)
}
func MustWriteFile(filePath string, contents []byte, mode os.FileMode) {

View File

@@ -3,7 +3,6 @@ package os
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
@@ -12,7 +11,7 @@ import (
)
func TestCopyFile(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "example")
tmpfile, err := os.CreateTemp("", "example")
if err != nil {
t.Fatal(err)
}
@@ -29,7 +28,7 @@ func TestCopyFile(t *testing.T) {
if _, err := os.Stat(copyfile); os.IsNotExist(err) {
t.Fatal("copy should exist")
}
data, err := ioutil.ReadFile(copyfile)
data, err := os.ReadFile(copyfile)
if err != nil {
t.Fatal(err)
}
@@ -40,7 +39,7 @@ func TestCopyFile(t *testing.T) {
}
func TestEnsureDir(t *testing.T) {
tmp, err := ioutil.TempDir("", "ensure-dir")
tmp, err := os.MkdirTemp("", "ensure-dir")
require.NoError(t, err)
defer os.RemoveAll(tmp)
@@ -54,7 +53,7 @@ func TestEnsureDir(t *testing.T) {
require.NoError(t, err)
// Should fail on file.
err = ioutil.WriteFile(filepath.Join(tmp, "file"), []byte{}, 0644)
err = os.WriteFile(filepath.Join(tmp, "file"), []byte{}, 0644)
require.NoError(t, err)
err = EnsureDir(filepath.Join(tmp, "file"), 0755)
require.Error(t, err)
@@ -76,7 +75,7 @@ func TestEnsureDir(t *testing.T) {
// the origin is positively a non-directory and that it is ready for copying.
// See https://github.com/tendermint/tendermint/issues/6427
func TestTrickedTruncation(t *testing.T) {
tmpDir, err := ioutil.TempDir(os.TempDir(), "pwn_truncate")
tmpDir, err := os.MkdirTemp(os.TempDir(), "pwn_truncate")
if err != nil {
t.Fatal(err)
}
@@ -84,12 +83,12 @@ func TestTrickedTruncation(t *testing.T) {
originalWALPath := filepath.Join(tmpDir, "wal")
originalWALContent := []byte("I AM BECOME DEATH, DESTROYER OF ALL WORLDS!")
if err := ioutil.WriteFile(originalWALPath, originalWALContent, 0755); err != nil {
if err := os.WriteFile(originalWALPath, originalWALContent, 0755); err != nil {
t.Fatal(err)
}
// 1. Sanity check.
readWAL, err := ioutil.ReadFile(originalWALPath)
readWAL, err := os.ReadFile(originalWALPath)
if err != nil {
t.Fatal(err)
}
@@ -104,7 +103,7 @@ func TestTrickedTruncation(t *testing.T) {
}
// 3. Check the WAL's content
reReadWAL, err := ioutil.ReadFile(originalWALPath)
reReadWAL, err := os.ReadFile(originalWALPath)
if err != nil {
t.Fatal(err)
}

View File

@@ -5,7 +5,6 @@ package tempfile
import (
"bytes"
"fmt"
"io/ioutil"
"os"
testing "testing"
@@ -21,13 +20,13 @@ func TestWriteFileAtomic(t *testing.T) {
perm os.FileMode = 0600
)
f, err := ioutil.TempFile("/tmp", "write-atomic-test-")
f, err := os.CreateTemp("/tmp", "write-atomic-test-")
if err != nil {
t.Fatal(err)
}
defer os.Remove(f.Name())
if err = ioutil.WriteFile(f.Name(), old, 0600); err != nil {
if err = os.WriteFile(f.Name(), old, 0600); err != nil {
t.Fatal(err)
}
@@ -35,7 +34,7 @@ func TestWriteFileAtomic(t *testing.T) {
t.Fatal(err)
}
rData, err := ioutil.ReadFile(f.Name())
rData, err := os.ReadFile(f.Name())
if err != nil {
t.Fatal(err)
}
@@ -80,11 +79,11 @@ func TestWriteFileAtomicDuplicateFile(t *testing.T) {
err = WriteFileAtomic(fileToWrite, []byte(expectedString), 0777)
require.NoError(t, err)
// Check that the first atomic file was untouched
firstAtomicFileBytes, err := ioutil.ReadFile(fname)
firstAtomicFileBytes, err := os.ReadFile(fname)
require.NoError(t, err, "Error reading first atomic file")
require.Equal(t, []byte(testString), firstAtomicFileBytes, "First atomic file was overwritten")
// Check that the resultant file is correct
resultantFileBytes, err := ioutil.ReadFile(fileToWrite)
resultantFileBytes, err := os.ReadFile(fileToWrite)
require.NoError(t, err, "Error reading resultant file")
require.Equal(t, []byte(expectedString), resultantFileBytes, "Written file had incorrect bytes")
@@ -131,14 +130,14 @@ func TestWriteFileAtomicManyDuplicates(t *testing.T) {
for i := 0; i < atomicWriteFileMaxNumConflicts+2; i++ {
fileRand := randWriteFileSuffix()
fname := "/tmp/" + atomicWriteFilePrefix + fileRand
firstAtomicFileBytes, err := ioutil.ReadFile(fname)
firstAtomicFileBytes, err := os.ReadFile(fname)
require.Nil(t, err, "Error reading first atomic file")
require.Equal(t, []byte(fmt.Sprintf(testString, i)), firstAtomicFileBytes,
"atomic write file %d was overwritten", i)
}
// Check that the resultant file is correct
resultantFileBytes, err := ioutil.ReadFile(fileToWrite)
resultantFileBytes, err := os.ReadFile(fileToWrite)
require.Nil(t, err, "Error reading resultant file")
require.Equal(t, []byte(expectedString), resultantFileBytes, "Written file had incorrect bytes")
}

View File

@@ -3,7 +3,6 @@ package light_test
import (
"context"
"fmt"
"io/ioutil"
stdlog "log"
"os"
"testing"
@@ -25,7 +24,7 @@ func ExampleClient_Update() {
// give Tendermint time to generate some blocks
time.Sleep(5 * time.Second)
dbDir, err := ioutil.TempDir("", "light-client-example")
dbDir, err := os.MkdirTemp("", "light-client-example")
if err != nil {
stdlog.Fatal(err)
}
@@ -93,7 +92,7 @@ func ExampleClient_VerifyLightBlockAtHeight() {
// give Tendermint time to generate some blocks
time.Sleep(5 * time.Second)
dbDir, err := ioutil.TempDir("", "light-client-example")
dbDir, err := os.MkdirTemp("", "light-client-example")
if err != nil {
stdlog.Fatal(err)
}

View File

@@ -4,7 +4,7 @@ import (
"bytes"
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
@@ -70,7 +70,7 @@ func LoadOrGenNodeKey(filePath string) (*NodeKey, error) {
// LoadNodeKey loads NodeKey located in filePath.
func LoadNodeKey(filePath string) (*NodeKey, error) {
jsonBytes, err := ioutil.ReadFile(filePath)
jsonBytes, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
@@ -88,7 +88,7 @@ func (nodeKey *NodeKey) SaveAs(filePath string) error {
if err != nil {
return err
}
err = ioutil.WriteFile(filePath, jsonBytes, 0600)
err = os.WriteFile(filePath, jsonBytes, 0600)
if err != nil {
return err
}

View File

@@ -3,7 +3,6 @@ package pex
import (
"encoding/hex"
"fmt"
"io/ioutil"
"math"
"net"
"os"
@@ -718,7 +717,7 @@ func assertMOldAndNNewAddrsInSelection(t *testing.T, m, n int, addrs []*p2p.NetA
}
func createTempFileName(prefix string) string {
f, err := ioutil.TempFile("", prefix)
f, err := os.CreateTemp("", prefix)
if err != nil {
panic(err)
}

View File

@@ -3,7 +3,6 @@ package pex
import (
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
@@ -73,7 +72,7 @@ func TestPEXReactorRunning(t *testing.T) {
switches := make([]*p2p.Switch, N)
// directory to store address books
dir, err := ioutil.TempDir("", "pex_reactor")
dir, err := os.MkdirTemp("", "pex_reactor")
require.Nil(t, err)
defer os.RemoveAll(dir)
@@ -208,7 +207,7 @@ func TestPEXReactorAddrsMessageAbuse(t *testing.T) {
func TestCheckSeeds(t *testing.T) {
// directory to store address books
dir, err := ioutil.TempDir("", "pex_reactor")
dir, err := os.MkdirTemp("", "pex_reactor")
require.Nil(t, err)
defer os.RemoveAll(dir)
@@ -247,7 +246,7 @@ func TestCheckSeeds(t *testing.T) {
func TestPEXReactorUsesSeedsIfNeeded(t *testing.T) {
// directory to store address books
dir, err := ioutil.TempDir("", "pex_reactor")
dir, err := os.MkdirTemp("", "pex_reactor")
require.Nil(t, err)
defer os.RemoveAll(dir)
@@ -267,7 +266,7 @@ func TestPEXReactorUsesSeedsIfNeeded(t *testing.T) {
func TestConnectionSpeedForPeerReceivedFromSeed(t *testing.T) {
// directory to store address books
dir, err := ioutil.TempDir("", "pex_reactor")
dir, err := os.MkdirTemp("", "pex_reactor")
require.Nil(t, err)
defer os.RemoveAll(dir)
@@ -296,7 +295,7 @@ func TestConnectionSpeedForPeerReceivedFromSeed(t *testing.T) {
func TestPEXReactorSeedMode(t *testing.T) {
// directory to store address books
dir, err := ioutil.TempDir("", "pex_reactor")
dir, err := os.MkdirTemp("", "pex_reactor")
require.Nil(t, err)
defer os.RemoveAll(dir)
@@ -335,7 +334,7 @@ func TestPEXReactorSeedMode(t *testing.T) {
func TestPEXReactorDoesNotDisconnectFromPersistentPeerInSeedMode(t *testing.T) {
// directory to store address books
dir, err := ioutil.TempDir("", "pex_reactor")
dir, err := os.MkdirTemp("", "pex_reactor")
require.Nil(t, err)
defer os.RemoveAll(dir)
@@ -373,7 +372,7 @@ func TestPEXReactorDoesNotDisconnectFromPersistentPeerInSeedMode(t *testing.T) {
func TestPEXReactorDialsPeerUpToMaxAttemptsInSeedMode(t *testing.T) {
// directory to store address books
dir, err := ioutil.TempDir("", "pex_reactor")
dir, err := os.MkdirTemp("", "pex_reactor")
require.Nil(t, err)
defer os.RemoveAll(dir)
@@ -409,7 +408,7 @@ func TestPEXReactorSeedModeFlushStop(t *testing.T) {
switches := make([]*p2p.Switch, N)
// directory to store address books
dir, err := ioutil.TempDir("", "pex_reactor")
dir, err := os.MkdirTemp("", "pex_reactor")
require.Nil(t, err)
defer os.RemoveAll(dir)
@@ -646,7 +645,7 @@ func testCreatePeerWithSeed(dir string, id int, seed *p2p.Switch) *p2p.Switch {
func createReactor(conf *ReactorConfig) (r *Reactor, book AddrBook) {
// directory to store address book
dir, err := ioutil.TempDir("", "pex_reactor")
dir, err := os.MkdirTemp("", "pex_reactor")
if err != nil {
panic(err)
}

View File

@@ -4,7 +4,7 @@ import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"net/http/httptest"
@@ -400,7 +400,7 @@ func TestSwitchStopPeerForError(t *testing.T) {
resp, err := http.Get(s.URL)
require.NoError(t, err)
defer resp.Body.Close()
buf, _ := ioutil.ReadAll(resp.Body)
buf, _ := io.ReadAll(resp.Body)
return string(buf)
}

View File

@@ -5,7 +5,6 @@ package trust
import (
"fmt"
"io/ioutil"
"os"
"testing"
@@ -17,7 +16,7 @@ import (
)
func TestTrustMetricStoreSaveLoad(t *testing.T) {
dir, err := ioutil.TempDir("", "trust_test")
dir, err := os.MkdirTemp("", "trust_test")
require.NoError(t, err)
defer os.Remove(dir)

View File

@@ -10,7 +10,7 @@ import (
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"strconv"
@@ -312,7 +312,7 @@ func (n *upnpNAT) getExternalIPAddress() (info statusInfo, err error) {
return
}
var envelope Envelope
data, err := ioutil.ReadAll(response.Body)
data, err := io.ReadAll(response.Body)
if err != nil {
return
}
@@ -374,7 +374,7 @@ func (n *upnpNAT) AddPortMapping(
// TODO: check response to see if the port was forwarded
// log.Println(message, response)
// JAE:
// body, err := ioutil.ReadAll(response.Body)
// body, err := io.ReadAll(response.Body)
// fmt.Println(string(body), err)
mappedExternalPort = externalPort
_ = response

View File

@@ -4,7 +4,7 @@ import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"time"
"github.com/gogo/protobuf/proto"
@@ -188,7 +188,7 @@ func LoadFilePVEmptyState(keyFilePath, stateFilePath string) *FilePV {
// If loadState is true, we load from the stateFilePath. Otherwise, we use an empty LastSignState.
func loadFilePV(keyFilePath, stateFilePath string, loadState bool) *FilePV {
keyJSONBytes, err := ioutil.ReadFile(keyFilePath)
keyJSONBytes, err := os.ReadFile(keyFilePath)
if err != nil {
tmos.Exit(err.Error())
}
@@ -206,7 +206,7 @@ func loadFilePV(keyFilePath, stateFilePath string, loadState bool) *FilePV {
pvState := FilePVLastSignState{}
if loadState {
stateJSONBytes, err := ioutil.ReadFile(stateFilePath)
stateJSONBytes, err := os.ReadFile(stateFilePath)
if err != nil {
tmos.Exit(err.Error())
}

View File

@@ -3,7 +3,6 @@ package privval
import (
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"testing"
"time"
@@ -23,9 +22,9 @@ import (
func TestGenLoadValidator(t *testing.T) {
assert := assert.New(t)
tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
require.Nil(t, err)
tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
require.Nil(t, err)
privVal := GenFilePV(tempKeyFile.Name(), tempStateFile.Name())
@@ -41,9 +40,9 @@ func TestGenLoadValidator(t *testing.T) {
}
func TestResetValidator(t *testing.T) {
tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
require.Nil(t, err)
tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
require.Nil(t, err)
privVal := GenFilePV(tempKeyFile.Name(), tempStateFile.Name())
@@ -72,9 +71,9 @@ func TestResetValidator(t *testing.T) {
func TestLoadOrGenValidator(t *testing.T) {
assert := assert.New(t)
tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
require.Nil(t, err)
tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
require.Nil(t, err)
tempKeyFilePath := tempKeyFile.Name()
@@ -159,9 +158,9 @@ func TestUnmarshalValidatorKey(t *testing.T) {
func TestSignVote(t *testing.T) {
assert := assert.New(t)
tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
require.Nil(t, err)
tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
require.Nil(t, err)
privVal := GenFilePV(tempKeyFile.Name(), tempStateFile.Name())
@@ -212,9 +211,9 @@ func TestSignVote(t *testing.T) {
func TestSignProposal(t *testing.T) {
assert := assert.New(t)
tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
require.Nil(t, err)
tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
require.Nil(t, err)
privVal := GenFilePV(tempKeyFile.Name(), tempStateFile.Name())
@@ -260,9 +259,9 @@ func TestSignProposal(t *testing.T) {
}
func TestDifferByTimestamp(t *testing.T) {
tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
require.Nil(t, err)
tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
require.Nil(t, err)
privVal := GenFilePV(tempKeyFile.Name(), tempStateFile.Name())

View File

@@ -1,7 +1,6 @@
package privval
import (
"io/ioutil"
"net"
"os"
"testing"
@@ -29,7 +28,7 @@ type listenerTestCase struct {
// testUnixAddr will attempt to obtain a platform-independent temporary file
// name for a Unix socket
func testUnixAddr() (string, error) {
f, err := ioutil.TempFile("", "tendermint-privval-test-*")
f, err := os.CreateTemp("", "tendermint-privval-test-*")
if err != nil {
return "", err
}

View File

@@ -1,7 +1,6 @@
package client_test
import (
"io/ioutil"
"os"
"testing"
@@ -14,7 +13,7 @@ var node *nm.Node
func TestMain(m *testing.M) {
// start a tendermint node (and kvstore) in the background to test against
dir, err := ioutil.TempDir("/tmp", "rpc-client-test")
dir, err := os.MkdirTemp("/tmp", "rpc-client-test")
if err != nil {
panic(err)
}

View File

@@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"net/url"
@@ -217,7 +217,7 @@ func (c *Client) Call(
defer httpResponse.Body.Close()
responseBytes, err := ioutil.ReadAll(httpResponse.Body)
responseBytes, err := io.ReadAll(httpResponse.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
@@ -265,7 +265,7 @@ func (c *Client) sendBatch(ctx context.Context, requests []*jsonRPCBufferedReque
defer httpResponse.Body.Close()
responseBytes, err := ioutil.ReadAll(httpResponse.Body)
responseBytes, err := io.ReadAll(httpResponse.Body)
if err != nil {
return nil, fmt.Errorf("read response body: %w", err)
}

View File

@@ -1,7 +1,7 @@
package client
import (
"io/ioutil"
"io"
"log"
"net/http"
"net/http/httptest"
@@ -21,7 +21,7 @@ func TestHTTPClientMakeHTTPDialer(t *testing.T) {
defer tsTLS.Close()
// This silences a TLS handshake error, caused by the dialer just immediately
// disconnecting, which we can just ignore.
tsTLS.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
tsTLS.Config.ErrorLog = log.New(io.Discard, "", 0)
for _, testURL := range []string{ts.URL, tsTLS.URL} {
u, err := newParsedURL(testURL)

View File

@@ -3,7 +3,7 @@ package client
import (
"context"
"fmt"
"io/ioutil"
"io"
"net/http"
"strings"
@@ -76,7 +76,7 @@ func (c *URIClient) Call(ctx context.Context, method string,
}
defer resp.Body.Close()
responseBytes, err := ioutil.ReadAll(resp.Body)
responseBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response body: %w", err)
}

View File

@@ -4,7 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"reflect"
"sort"
@@ -19,7 +19,7 @@ import (
// jsonrpc calls grab the given method's function info and runs reflect.Call
func makeJSONRPCHandler(funcMap map[string]*RPCFunc, logger log.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
b, err := io.ReadAll(r.Body)
if err != nil {
res := types.RPCInvalidRequestError(nil,
fmt.Errorf("error reading request body: %w", err),

View File

@@ -3,7 +3,7 @@ package server
import (
"bytes"
"encoding/json"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"strings"
@@ -66,7 +66,7 @@ func TestRPCParams(t *testing.T) {
defer res.Body.Close()
// Always expecting back a JSONRPCResponse
assert.NotZero(t, res.StatusCode, "#%d: should always return code", i)
blob, err := ioutil.ReadAll(res.Body)
blob, err := io.ReadAll(res.Body)
if err != nil {
t.Errorf("#%d: err reading body: %v", i, err)
continue
@@ -113,7 +113,7 @@ func TestJSONRPCID(t *testing.T) {
res := rec.Result()
// Always expecting back a JSONRPCResponse
assert.NotZero(t, res.StatusCode, "#%d: should always return code", i)
blob, err := ioutil.ReadAll(res.Body)
blob, err := io.ReadAll(res.Body)
if err != nil {
t.Errorf("#%d: err reading body: %v", i, err)
continue
@@ -143,7 +143,7 @@ func TestRPCNotification(t *testing.T) {
// Always expecting back a JSONRPCResponse
require.True(t, statusOK(res.StatusCode), "should always return 2XX")
blob, err := ioutil.ReadAll(res.Body)
blob, err := io.ReadAll(res.Body)
res.Body.Close()
require.Nil(t, err, "reading from the body should not give back an error")
require.Equal(t, len(blob), 0, "a notification SHOULD NOT be responded to by the server")
@@ -179,7 +179,7 @@ func TestRPCNotificationInBatch(t *testing.T) {
res := rec.Result()
// Always expecting back a JSONRPCResponse
assert.True(t, statusOK(res.StatusCode), "#%d: should always return 2XX", i)
blob, err := ioutil.ReadAll(res.Body)
blob, err := io.ReadAll(res.Body)
if err != nil {
t.Errorf("#%d: err reading body: %v", i, err)
continue

View File

@@ -4,7 +4,7 @@ import (
"crypto/tls"
"errors"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"net/http/httptest"
@@ -102,7 +102,7 @@ func TestServeTLS(t *testing.T) {
defer res.Body.Close()
assert.Equal(t, http.StatusOK, res.StatusCode)
body, err := ioutil.ReadAll(res.Body)
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
assert.Equal(t, []byte("some body"), body)
}
@@ -115,7 +115,7 @@ func TestWriteRPCResponseHTTP(t *testing.T) {
err := WriteRPCResponseHTTP(w, types.NewRPCSuccessResponse(id, &sampleResult{"hello"}))
require.NoError(t, err)
resp := w.Result()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
@@ -135,7 +135,7 @@ func TestWriteRPCResponseHTTP(t *testing.T) {
types.NewRPCSuccessResponse(id, &sampleResult{"world"}))
require.NoError(t, err)
resp = w.Result()
body, err = ioutil.ReadAll(resp.Body)
body, err = io.ReadAll(resp.Body)
_ = resp.Body.Close()
require.NoError(t, err)
@@ -167,7 +167,7 @@ func TestWriteRPCResponseHTTPError(t *testing.T) {
types.RPCInternalError(types.JSONRPCIntID(-1), errors.New("foo")))
require.NoError(t, err)
resp := w.Result()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
require.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)

View File

@@ -6,7 +6,6 @@ import (
"go/parser"
"go/token"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
@@ -38,7 +37,7 @@ func TestSimpleTemplate(t *testing.T) {
}
func TestFromData(t *testing.T) {
infos, err := ioutil.ReadDir(testDataDir)
infos, err := os.ReadDir(testDataDir)
if err != nil {
t.Fatalf("unable to open file %v", err)
}
@@ -67,12 +66,12 @@ func TestFromData(t *testing.T) {
if _, err := parser.ParseFile(token.NewFileSet(), outFile, nil, parser.AllErrors); err != nil {
t.Fatalf("unable to parse generated file %s: %v", outFile, err)
}
bNew, err := ioutil.ReadFile(outFile)
bNew, err := os.ReadFile(outFile)
if err != nil {
t.Fatalf("unable to read generated file %s: %v", outFile, err)
}
goldenFile := path.Join(dirName, "metrics.gen.go")
bOld, err := ioutil.ReadFile(goldenFile)
bOld, err := os.ReadFile(goldenFile)
if err != nil {
t.Fatalf("unable to read file %s: %v", goldenFile, err)
}

View File

@@ -5,7 +5,6 @@ import (
"database/sql"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
@@ -227,7 +226,7 @@ func newTestBlockHeader() types.EventDataNewBlockHeader {
// readSchema loads the indexing database schema file
func readSchema() ([]*schema.Migration, error) {
const filename = "schema.sql"
contents, err := ioutil.ReadFile(filename)
contents, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read sql file from '%s': %w", filename, err)
}

View File

@@ -4,7 +4,7 @@ import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"time"
"github.com/gogo/protobuf/proto"
@@ -303,7 +303,7 @@ func MakeGenesisStateFromFile(genDocFile string) (State, error) {
// MakeGenesisDocFromFile reads and unmarshals genesis doc from the given file.
func MakeGenesisDocFromFile(genDocFile string) (*types.GenesisDoc, error) {
genDocJSON, err := ioutil.ReadFile(genDocFile)
genDocJSON, err := os.ReadFile(genDocFile)
if err != nil {
return nil, fmt.Errorf("couldn't read GenesisDoc file: %v", err)
}

View File

@@ -4,7 +4,7 @@ import (
"context"
"crypto/rand"
"fmt"
"io/ioutil"
"os"
"testing"
dbm "github.com/tendermint/tm-db"
@@ -15,7 +15,7 @@ import (
)
func BenchmarkTxSearch(b *testing.B) {
dbDir, err := ioutil.TempDir("", "benchmark_tx_search_test")
dbDir, err := os.MkdirTemp("", "benchmark_tx_search_test")
if err != nil {
b.Errorf("failed to create temporary directory: %s", err)
}

View File

@@ -3,7 +3,6 @@ package kv
import (
"context"
"fmt"
"io/ioutil"
"os"
"testing"
@@ -329,7 +328,7 @@ func txResultWithEvents(events []abci.Event) *abci.TxResult {
}
func benchmarkTxIndex(txsCount int64, b *testing.B) {
dir, err := ioutil.TempDir("", "tx_index_db")
dir, err := os.MkdirTemp("", "tx_index_db")
require.NoError(b, err)
defer os.RemoveAll(dir)

View File

@@ -3,7 +3,6 @@ package statesync
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
@@ -42,7 +41,7 @@ type chunkQueue struct {
// newChunkQueue creates a new chunk queue for a snapshot, using a temp dir for storage.
// Callers must call Close() when done.
func newChunkQueue(snapshot *snapshot, tempDir string) (*chunkQueue, error) {
dir, err := ioutil.TempDir(tempDir, "tm-statesync")
dir, err := os.MkdirTemp(tempDir, "tm-statesync")
if err != nil {
return nil, fmt.Errorf("unable to create temp dir for state sync chunks: %w", err)
}
@@ -84,7 +83,7 @@ func (q *chunkQueue) Add(chunk *chunk) (bool, error) {
}
path := filepath.Join(q.dir, strconv.FormatUint(uint64(chunk.Index), 10))
err := ioutil.WriteFile(path, chunk.Chunk, 0600)
err := os.WriteFile(path, chunk.Chunk, 0600)
if err != nil {
return false, fmt.Errorf("failed to save chunk %v to file %v: %w", chunk.Index, path, err)
}
@@ -209,7 +208,7 @@ func (q *chunkQueue) load(index uint32) (*chunk, error) {
if !ok {
return nil, nil
}
body, err := ioutil.ReadFile(path)
body, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to load chunk %v: %w", index, err)
}

View File

@@ -1,7 +1,6 @@
package statesync
import (
"io/ioutil"
"os"
"testing"
@@ -36,20 +35,20 @@ func TestNewChunkQueue_TempDir(t *testing.T) {
Hash: []byte{7},
Metadata: nil,
}
dir, err := ioutil.TempDir("", "newchunkqueue")
dir, err := os.MkdirTemp("", "newchunkqueue")
require.NoError(t, err)
defer os.RemoveAll(dir)
queue, err := newChunkQueue(snapshot, dir)
require.NoError(t, err)
files, err := ioutil.ReadDir(dir)
files, err := os.ReadDir(dir)
require.NoError(t, err)
assert.Len(t, files, 1)
err = queue.Close()
require.NoError(t, err)
files, err = ioutil.ReadDir(dir)
files, err = os.ReadDir(dir)
require.NoError(t, err)
assert.Len(t, files, 0)
}

View File

@@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math"
"os"
"path/filepath"
@@ -45,7 +44,7 @@ func (s *SnapshotStore) loadMetadata() error {
file := filepath.Join(s.dir, "metadata.json")
metadata := []abci.Snapshot{}
bz, err := ioutil.ReadFile(file)
bz, err := os.ReadFile(file)
switch {
case errors.Is(err, os.ErrNotExist):
case err != nil:
@@ -72,7 +71,7 @@ func (s *SnapshotStore) saveMetadata() error {
// save the file to a new file and move it to make saving atomic.
newFile := filepath.Join(s.dir, "metadata.json.new")
file := filepath.Join(s.dir, "metadata.json")
err = ioutil.WriteFile(newFile, bz, 0644) // nolint: gosec
err = os.WriteFile(newFile, bz, 0644) // nolint: gosec
if err != nil {
return err
}
@@ -93,7 +92,7 @@ func (s *SnapshotStore) Create(state *State) (abci.Snapshot, error) {
Hash: hashItems(state.Values),
Chunks: byteChunks(bz),
}
err = ioutil.WriteFile(filepath.Join(s.dir, fmt.Sprintf("%v.json", state.Height)), bz, 0644)
err = os.WriteFile(filepath.Join(s.dir, fmt.Sprintf("%v.json", state.Height)), bz, 0644)
if err != nil {
return abci.Snapshot{}, err
}
@@ -122,7 +121,7 @@ func (s *SnapshotStore) LoadChunk(height uint64, format uint32, chunk uint32) ([
defer s.RUnlock()
for _, snapshot := range s.metadata {
if snapshot.Height == height && snapshot.Format == format {
bz, err := ioutil.ReadFile(filepath.Join(s.dir, fmt.Sprintf("%v.json", height)))
bz, err := os.ReadFile(filepath.Join(s.dir, fmt.Sprintf("%v.json", height)))
if err != nil {
return nil, err
}

View File

@@ -6,7 +6,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
@@ -52,11 +51,11 @@ func NewState(dir string, persistInterval uint64) (*State, error) {
// load loads state from disk. It does not take out a lock, since it is called
// during construction.
func (s *State) load() error {
bz, err := ioutil.ReadFile(s.currentFile)
bz, err := os.ReadFile(s.currentFile)
if err != nil {
// if the current state doesn't exist then we try recover from the previous state
if errors.Is(err, os.ErrNotExist) {
bz, err = ioutil.ReadFile(s.previousFile)
bz, err = os.ReadFile(s.previousFile)
if err != nil {
return fmt.Errorf("failed to read both current and previous state (%q): %w",
s.previousFile, err)
@@ -82,7 +81,7 @@ func (s *State) save() error {
// We write the state to a separate file and move it to the destination, to
// make it atomic.
newFile := fmt.Sprintf("%v.new", s.currentFile)
err = ioutil.WriteFile(newFile, bz, 0644)
err = os.WriteFile(newFile, bz, 0644)
if err != nil {
return fmt.Errorf("failed to write state to %q: %w", s.currentFile, err)
}
@@ -160,7 +159,7 @@ func (s *State) Commit() (uint64, []byte, error) {
}
func (s *State) Rollback() error {
bz, err := ioutil.ReadFile(s.previousFile)
bz, err := os.ReadFile(s.previousFile)
if err != nil {
return fmt.Errorf("failed to read state from %q: %w", s.previousFile, err)
}

View File

@@ -7,7 +7,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
@@ -53,7 +52,7 @@ func Setup(testnet *e2e.Testnet) error {
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(testnet.Dir, "docker-compose.yml"), compose, 0644)
err = os.WriteFile(filepath.Join(testnet.Dir, "docker-compose.yml"), compose, 0644)
if err != nil {
return err
}
@@ -92,7 +91,7 @@ func Setup(testnet *e2e.Testnet) error {
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(nodeDir, "config", "app.toml"), appCfg, 0644)
err = os.WriteFile(filepath.Join(nodeDir, "config", "app.toml"), appCfg, 0644)
if err != nil {
return err
}
@@ -388,11 +387,11 @@ func UpdateConfigStateSync(node *e2e.Node, height int64, hash []byte) error {
// FIXME Apparently there's no function to simply load a config file without
// involving the entire Viper apparatus, so we'll just resort to regexps.
bz, err := ioutil.ReadFile(cfgPath)
bz, err := os.ReadFile(cfgPath)
if err != nil {
return err
}
bz = regexp.MustCompile(`(?m)^trust_height =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust_height = %v`, height)))
bz = regexp.MustCompile(`(?m)^trust_hash =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust_hash = "%X"`, hash)))
return ioutil.WriteFile(cfgPath, bz, 0644)
return os.WriteFile(cfgPath, bz, 0644)
}

View File

@@ -1,7 +1,7 @@
package v0_test
import (
"io/ioutil"
"io"
"os"
"path/filepath"
"testing"
@@ -25,7 +25,7 @@ func TestMempoolTestdataCases(t *testing.T) {
}()
f, err := os.Open(filepath.Join(testdataCasesDir, entry.Name()))
require.NoError(t, err)
input, err := ioutil.ReadAll(f)
input, err := io.ReadAll(f)
require.NoError(t, err)
mempoolv0.Fuzz(input)
})

View File

@@ -1,7 +1,7 @@
package v1_test
import (
"io/ioutil"
"io"
"os"
"path/filepath"
"testing"
@@ -25,7 +25,7 @@ func TestMempoolTestdataCases(t *testing.T) {
}()
f, err := os.Open(filepath.Join(testdataCasesDir, entry.Name()))
require.NoError(t, err)
input, err := ioutil.ReadAll(f)
input, err := io.ReadAll(f)
require.NoError(t, err)
mempoolv1.Fuzz(input)
})

View File

@@ -5,7 +5,6 @@ import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"os"
@@ -49,7 +48,7 @@ func initCorpus(baseDir string) {
log.Fatalf("can't marshal %v: %v", addr, err)
}
if err := ioutil.WriteFile(filename, bz, 0644); err != nil {
if err := os.WriteFile(filename, bz, 0644); err != nil {
log.Fatalf("can't write %v to %q: %v", addr, filename, err)
}

View File

@@ -4,7 +4,6 @@ package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
@@ -73,7 +72,7 @@ func initCorpus(rootDir string) {
filename := filepath.Join(rootDir, "corpus", fmt.Sprintf("%d", n))
if err := ioutil.WriteFile(filename, bz, 0644); err != nil {
if err := os.WriteFile(filename, bz, 0644); err != nil {
log.Fatalf("can't write %X to %q: %v", bz, filename, err)
}

View File

@@ -4,7 +4,6 @@ package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
@@ -39,7 +38,7 @@ func initCorpus(baseDir string) {
for i, datum := range data {
filename := filepath.Join(corpusDir, fmt.Sprintf("%d", i))
if err := ioutil.WriteFile(filename, []byte(datum), 0644); err != nil {
if err := os.WriteFile(filename, []byte(datum), 0644); err != nil {
log.Fatalf("can't write %v to %q: %v", datum, filename, err)
}

View File

@@ -3,7 +3,7 @@ package handler
import (
"bytes"
"encoding/json"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
@@ -29,7 +29,7 @@ func Fuzz(data []byte) int {
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
res := rec.Result()
blob, err := ioutil.ReadAll(res.Body)
blob, err := io.ReadAll(res.Body)
if err != nil {
panic(err)
}

View File

@@ -2,7 +2,6 @@ package internal
import (
"fmt"
"io/ioutil"
"os"
"testing"
"time"
@@ -187,7 +186,7 @@ func cleanup(cfg TestHarnessConfig) {
}
func makeTempFile(name, content string) string {
tempFile, err := ioutil.TempFile("", fmt.Sprintf("%s-*", name))
tempFile, err := os.CreateTemp("", fmt.Sprintf("%s-*", name))
if err != nil {
panic(err)
}

View File

@@ -3,7 +3,6 @@ package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
@@ -136,7 +135,7 @@ func extractKey(tmhome, outputPath string) {
stateFile := filepath.Join(internal.ExpandPath(tmhome), "data", "priv_validator_state.json")
fpv := privval.LoadFilePV(keyFile, stateFile)
pkb := []byte(fpv.Key.PrivKey.(ed25519.PrivKey))
if err := ioutil.WriteFile(internal.ExpandPath(outputPath), pkb[:32], 0600); err != nil {
if err := os.WriteFile(internal.ExpandPath(outputPath), pkb[:32], 0600); err != nil {
logger.Info("Failed to write private key", "output", outputPath, "err", err)
os.Exit(1)
}

View File

@@ -5,7 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"time"
"github.com/tendermint/tendermint/crypto"
@@ -126,7 +126,7 @@ func GenesisDocFromJSON(jsonBlob []byte) (*GenesisDoc, error) {
// GenesisDocFromFile reads JSON data from a file and unmarshalls it into a GenesisDoc.
func GenesisDocFromFile(genDocFile string) (*GenesisDoc, error) {
jsonBlob, err := ioutil.ReadFile(genDocFile)
jsonBlob, err := os.ReadFile(genDocFile)
if err != nil {
return nil, fmt.Errorf("couldn't read GenesisDoc file: %w", err)
}

View File

@@ -1,7 +1,6 @@
package types
import (
"io/ioutil"
"os"
"testing"
@@ -122,7 +121,7 @@ func TestGenesisGood(t *testing.T) {
}
func TestGenesisSaveAs(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "genesis")
tmpfile, err := os.CreateTemp("", "genesis")
require.NoError(t, err)
defer os.Remove(tmpfile.Name())

View File

@@ -1,7 +1,7 @@
package types
import (
"io/ioutil"
"io"
"testing"
"github.com/stretchr/testify/assert"
@@ -57,7 +57,7 @@ func TestBasicPartSet(t *testing.T) {
// Reconstruct data, assert that they are equal.
data2Reader := partSet2.GetReader()
data2, err := ioutil.ReadAll(data2Reader)
data2, err := io.ReadAll(data2Reader)
require.NoError(t, err)
assert.Equal(t, data, data2)