refactor: move from io/ioutil to io and os package (#1245)

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-09-29 15:17:02 +08:00
committed by GitHub
parent 6bcb4af10f
commit bbcce9f7b7
13 changed files with 42 additions and 52 deletions

View File

@@ -6,7 +6,7 @@ package integration
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -495,7 +495,7 @@ func setup(t *testing.T, options setupOptions) (*cli.App, string, string) {
go func() { go func() {
// Setup CLI App // Setup CLI App
app := commands.NewApp(version) app := commands.NewApp(version)
app.Writer = ioutil.Discard app.Writer = io.Discard
osArgs := setupServer(addr, options.token, options.tokenHeader, cacheDir, options.cacheBackend) osArgs := setupServer(addr, options.token, options.tokenHeader, cacheDir, options.cacheBackend)
// Run Trivy server // Run Trivy server
@@ -508,7 +508,7 @@ func setup(t *testing.T, options setupOptions) (*cli.App, string, string) {
// Setup CLI App // Setup CLI App
app := commands.NewApp(version) app := commands.NewApp(version)
app.Writer = ioutil.Discard app.Writer = io.Discard
return app, addr, cacheDir return app, addr, cacheDir
} }
@@ -549,10 +549,10 @@ func setupClient(t *testing.T, c args, addr string, cacheDir string, golden stri
var err error var err error
var ignoreTmpDir string var ignoreTmpDir string
if len(c.IgnoreIDs) != 0 { if len(c.IgnoreIDs) != 0 {
ignoreTmpDir, err = ioutil.TempDir("", "ignore") ignoreTmpDir, err = os.MkdirTemp("", "ignore")
require.NoError(t, err, "failed to create a temp dir") require.NoError(t, err, "failed to create a temp dir")
trivyIgnore := filepath.Join(ignoreTmpDir, ".trivyignore") trivyIgnore := filepath.Join(ignoreTmpDir, ".trivyignore")
err = ioutil.WriteFile(trivyIgnore, []byte(strings.Join(c.IgnoreIDs, "\n")), 0444) err = os.WriteFile(trivyIgnore, []byte(strings.Join(c.IgnoreIDs, "\n")), 0444)
require.NoError(t, err, "failed to write .trivyignore") require.NoError(t, err, "failed to write .trivyignore")
osArgs = append(osArgs, []string{"--ignorefile", trivyIgnore}...) osArgs = append(osArgs, []string{"--ignorefile", trivyIgnore}...)
} }
@@ -568,7 +568,7 @@ func setupClient(t *testing.T, c args, addr string, cacheDir string, golden stri
if *update { if *update {
outputFile = golden outputFile = golden
} else { } else {
output, _ := ioutil.TempFile("", "integration") output, _ := os.CreateTemp("", "integration")
assert.Nil(t, output.Close()) assert.Nil(t, output.Close())
outputFile = output.Name() outputFile = output.Name()
} }
@@ -615,9 +615,9 @@ func setupRedis(t *testing.T, ctx context.Context) (testcontainers.Container, st
func compare(t *testing.T, wantFile, gotFile string) { func compare(t *testing.T, wantFile, gotFile string) {
t.Helper() t.Helper()
// Compare want and got // Compare want and got
want, err := ioutil.ReadFile(wantFile) want, err := os.ReadFile(wantFile)
assert.NoError(t, err) assert.NoError(t, err)
got, err := ioutil.ReadFile(gotFile) got, err := os.ReadFile(gotFile)
assert.NoError(t, err) assert.NoError(t, err)
if strings.HasSuffix(wantFile, ".json.golden") { if strings.HasSuffix(wantFile, ".json.golden") {

View File

@@ -6,7 +6,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/url" "net/url"
"os" "os"
@@ -78,7 +77,7 @@ func (d Docker) ReplicateImage(ctx context.Context, imageRef, imagePath string,
if err != nil { if err != nil {
return err return err
} }
if _, err = io.Copy(ioutil.Discard, resp.Body); err != nil { if _, err = io.Copy(io.Discard, resp.Body); err != nil {
return err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
@@ -110,7 +109,7 @@ func (d Docker) ReplicateImage(ctx context.Context, imageRef, imagePath string,
} }
defer pushOut.Close() defer pushOut.Close()
if _, err = io.Copy(ioutil.Discard, pushOut); err != nil { if _, err = io.Copy(io.Discard, pushOut); err != nil {
return err return err
} }
return nil return nil

View File

@@ -6,7 +6,6 @@ package integration
import ( import (
"context" "context"
"io" "io"
"io/ioutil"
"os" "os"
"strings" "strings"
"testing" "testing"
@@ -270,14 +269,14 @@ func TestRun_WithDockerEngine(t *testing.T) {
// load image into docker engine // load image into docker engine
res, err := cli.ImageLoad(ctx, testfile, true) res, err := cli.ImageLoad(ctx, testfile, true)
require.NoError(t, err, tc.name) require.NoError(t, err, tc.name)
io.Copy(ioutil.Discard, res.Body) io.Copy(io.Discard, res.Body)
// tag our image to something unique // tag our image to something unique
err = cli.ImageTag(ctx, tc.imageTag, tc.testfile) err = cli.ImageTag(ctx, tc.imageTag, tc.testfile)
require.NoError(t, err, tc.name) require.NoError(t, err, tc.name)
} }
of, err := ioutil.TempFile("", "integration-docker-engine-output-file-*") of, err := os.CreateTemp("", "integration-docker-engine-output-file-*")
require.NoError(t, err, tc.name) require.NoError(t, err, tc.name)
defer os.Remove(of.Name()) defer os.Remove(of.Name())
@@ -301,7 +300,7 @@ func TestRun_WithDockerEngine(t *testing.T) {
} }
if len(tc.ignoreIDs) != 0 { if len(tc.ignoreIDs) != 0 {
trivyIgnore := ".trivyignore" trivyIgnore := ".trivyignore"
err := ioutil.WriteFile(trivyIgnore, []byte(strings.Join(tc.ignoreIDs, "\n")), 0444) err := os.WriteFile(trivyIgnore, []byte(strings.Join(tc.ignoreIDs, "\n")), 0444)
assert.NoError(t, err, "failed to write .trivyignore") assert.NoError(t, err, "failed to write .trivyignore")
defer os.Remove(trivyIgnore) defer os.Remove(trivyIgnore)
} }
@@ -318,9 +317,9 @@ func TestRun_WithDockerEngine(t *testing.T) {
} }
// check for vulnerability output info // check for vulnerability output info
got, err := ioutil.ReadAll(of) got, err := io.ReadAll(of)
assert.NoError(t, err, tc.name) assert.NoError(t, err, tc.name)
want, err := ioutil.ReadFile(tc.expectedOutputFile) want, err := os.ReadFile(tc.expectedOutputFile)
assert.NoError(t, err, tc.name) assert.NoError(t, err, tc.name)
assert.JSONEq(t, string(want), string(got), tc.name) assert.JSONEq(t, string(want), string(got), tc.name)

View File

@@ -9,7 +9,7 @@ import (
"crypto/x509" "crypto/x509"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
@@ -236,7 +236,7 @@ func scan(t *testing.T, imageRef name.Reference, baseDir, goldenFile string, opt
if *update && goldenFile != "" { if *update && goldenFile != "" {
outputFile = goldenFile outputFile = goldenFile
} else { } else {
output, err := ioutil.TempFile("", "integration") output, err := os.CreateTemp("", "integration")
if err != nil { if err != nil {
return "", cleanup, err return "", cleanup, err
} }
@@ -256,7 +256,7 @@ func scan(t *testing.T, imageRef name.Reference, baseDir, goldenFile string, opt
// Setup CLI App // Setup CLI App
app := commands.NewApp("dev") app := commands.NewApp("dev")
app.Writer = ioutil.Discard app.Writer = io.Discard
osArgs := []string{"trivy", "--cache-dir", cacheDir, "--format", "json", "--skip-update", "--output", outputFile, imageRef.Name()} osArgs := []string{"trivy", "--cache-dir", cacheDir, "--format", "json", "--skip-update", "--output", outputFile, imageRef.Name()}
@@ -306,7 +306,7 @@ func unsetEnv() error {
func requestRegistryToken(imageRef name.Reference, baseDir string, opt registryOption) (string, error) { func requestRegistryToken(imageRef name.Reference, baseDir string, opt registryOption) (string, error) {
// Create a CA certificate pool and add cert.pem to it // Create a CA certificate pool and add cert.pem to it
caCert, err := ioutil.ReadFile(filepath.Join(baseDir, "data", "certs", "cert.pem")) caCert, err := os.ReadFile(filepath.Join(baseDir, "data", "certs", "cert.pem"))
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@@ -4,7 +4,7 @@
package integration package integration
import ( import (
"io/ioutil" "io"
"os" "os"
"strings" "strings"
"testing" "testing"
@@ -377,7 +377,7 @@ func TestRun_WithTar(t *testing.T) {
// Setup CLI App // Setup CLI App
app := commands.NewApp("dev") app := commands.NewApp("dev")
app.Writer = ioutil.Discard app.Writer = io.Discard
for _, c := range cases { for _, c := range cases {
t.Run(c.name, func(t *testing.T) { t.Run(c.name, func(t *testing.T) {
@@ -402,7 +402,7 @@ func TestRun_WithTar(t *testing.T) {
} }
if len(c.testArgs.IgnoreIDs) != 0 { if len(c.testArgs.IgnoreIDs) != 0 {
trivyIgnore := ".trivyignore" trivyIgnore := ".trivyignore"
err := ioutil.WriteFile(trivyIgnore, []byte(strings.Join(c.testArgs.IgnoreIDs, "\n")), 0444) err := os.WriteFile(trivyIgnore, []byte(strings.Join(c.testArgs.IgnoreIDs, "\n")), 0444)
assert.NoError(t, err, "failed to write .trivyignore") assert.NoError(t, err, "failed to write .trivyignore")
defer os.Remove(trivyIgnore) defer os.Remove(trivyIgnore)
} }
@@ -427,7 +427,7 @@ func TestRun_WithTar(t *testing.T) {
if *update { if *update {
outputFile = c.golden outputFile = c.golden
} else { } else {
output, _ := ioutil.TempFile("", "integration") output, _ := os.CreateTemp("", "integration")
assert.Nil(t, output.Close()) assert.Nil(t, output.Close())
defer os.Remove(output.Name()) defer os.Remove(output.Name())
outputFile = output.Name() outputFile = output.Name()
@@ -439,9 +439,9 @@ func TestRun_WithTar(t *testing.T) {
assert.Nil(t, app.Run(osArgs)) assert.Nil(t, app.Run(osArgs))
// Compare want and got // Compare want and got
want, err := ioutil.ReadFile(c.golden) want, err := os.ReadFile(c.golden)
assert.NoError(t, err) assert.NoError(t, err)
got, err := ioutil.ReadFile(outputFile) got, err := os.ReadFile(outputFile)
assert.NoError(t, err) assert.NoError(t, err)
assert.JSONEq(t, string(want), string(got)) assert.JSONEq(t, string(want), string(got))

View File

@@ -3,7 +3,6 @@ package commands
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -81,7 +80,7 @@ Vulnerability DB:
case tt.args.cacheDir != "": case tt.args.cacheDir != "":
cacheDir = tt.args.cacheDir cacheDir = tt.args.cacheDir
default: default:
cacheDir, _ = ioutil.TempDir("", "Test_showVersion-*") cacheDir, _ = os.MkdirTemp("", "Test_showVersion-*")
defer os.RemoveAll(cacheDir) defer os.RemoveAll(cacheDir)
} }

View File

@@ -4,7 +4,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"io/ioutil"
"os" "os"
"testing" "testing"
"time" "time"
@@ -246,7 +245,7 @@ func TestClient_Download(t *testing.T) {
fs := afero.NewMemMapFs() fs := afero.NewMemMapFs()
metadata := NewMetadata(fs, "/cache") metadata := NewMetadata(fs, "/cache")
dir, err := ioutil.TempDir("", "db") dir, err := os.MkdirTemp("", "db")
require.NoError(t, err, tc.name) require.NoError(t, err, tc.name)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
@@ -349,7 +348,7 @@ func TestClient_UpdateMetadata(t *testing.T) {
fs := afero.NewMemMapFs() fs := afero.NewMemMapFs()
metadata := NewMetadata(fs, "/cache") metadata := NewMetadata(fs, "/cache")
dir, err := ioutil.TempDir("", "db") dir, err := os.MkdirTemp("", "db")
require.NoError(t, err, tc.name) require.NoError(t, err, tc.name)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)

View File

@@ -4,7 +4,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@@ -122,7 +121,7 @@ func TestClient_DownloadDB(t *testing.T) {
{ {
input: 100, input: 100,
output: downloadAssetOutput{ output: downloadAssetOutput{
rc: ioutil.NopCloser(strings.NewReader("foo")), rc: io.NopCloser(strings.NewReader("foo")),
}, },
}, },
}, },
@@ -217,7 +216,7 @@ func TestClient_DownloadDB(t *testing.T) {
{ {
input: 300, input: 300,
output: downloadAssetOutput{ output: downloadAssetOutput{
rc: ioutil.NopCloser(strings.NewReader("foo")), rc: io.NopCloser(strings.NewReader("foo")),
}, },
}, },
}, },
@@ -268,7 +267,7 @@ func TestClient_DownloadDB(t *testing.T) {
{ {
input: 200, input: 200,
output: downloadAssetOutput{ output: downloadAssetOutput{
rc: ioutil.NopCloser(strings.NewReader("foo")), rc: io.NopCloser(strings.NewReader("foo")),
}, },
}, },
}, },

View File

@@ -6,7 +6,6 @@ import (
"fmt" "fmt"
"html" "html"
"io" "io"
"io/ioutil"
"os" "os"
"regexp" "regexp"
"strings" "strings"
@@ -31,7 +30,7 @@ type TemplateWriter struct {
// NewTemplateWriter is the factory method to return TemplateWriter object // NewTemplateWriter is the factory method to return TemplateWriter object
func NewTemplateWriter(output io.Writer, outputTemplate string) (*TemplateWriter, error) { func NewTemplateWriter(output io.Writer, outputTemplate string) (*TemplateWriter, error) {
if strings.HasPrefix(outputTemplate, "@") { if strings.HasPrefix(outputTemplate, "@") {
buf, err := ioutil.ReadFile(strings.TrimPrefix(outputTemplate, "@")) buf, err := os.ReadFile(strings.TrimPrefix(outputTemplate, "@"))
if err != nil { if err != nil {
return nil, xerrors.Errorf("error retrieving template from path: %w", err) return nil, xerrors.Errorf("error retrieving template from path: %w", err)
} }

View File

@@ -4,7 +4,6 @@ import (
"bufio" "bufio"
"context" "context"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"sort" "sort"
"strings" "strings"
@@ -262,7 +261,7 @@ func toSlice(uniqVulns map[string]types.DetectedVulnerability) []types.DetectedV
func applyPolicy(ctx context.Context, vulns []types.DetectedVulnerability, misconfs []types.DetectedMisconfiguration, func applyPolicy(ctx context.Context, vulns []types.DetectedVulnerability, misconfs []types.DetectedMisconfiguration,
policyFile string) ([]types.DetectedVulnerability, []types.DetectedMisconfiguration, error) { policyFile string) ([]types.DetectedVulnerability, []types.DetectedMisconfiguration, error) {
policy, err := ioutil.ReadFile(policyFile) policy, err := os.ReadFile(policyFile)
if err != nil { if err != nil {
return nil, nil, xerrors.Errorf("unable to read the policy file: %w", err) return nil, nil, xerrors.Errorf("unable to read the policy file: %w", err)
} }

View File

@@ -2,7 +2,6 @@ package server
import ( import (
"context" "context"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"sync" "sync"
@@ -140,7 +139,7 @@ func (w dbWorker) update(ctx context.Context, appVersion, cacheDir string,
} }
func (w dbWorker) hotUpdate(ctx context.Context, cacheDir string, dbUpdateWg, requestWg *sync.WaitGroup) error { func (w dbWorker) hotUpdate(ctx context.Context, cacheDir string, dbUpdateWg, requestWg *sync.WaitGroup) error {
tmpDir, err := ioutil.TempDir("", "db") tmpDir, err := os.MkdirTemp("", "db")
if err != nil { if err != nil {
return xerrors.Errorf("failed to create a temp dir: %w", err) return xerrors.Errorf("failed to create a temp dir: %w", err)
} }

View File

@@ -2,7 +2,6 @@ package server
import ( import (
"context" "context"
"io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
@@ -106,7 +105,7 @@ func Test_dbWorker_update(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
cacheDir, err := ioutil.TempDir("", "server-test") cacheDir, err := os.MkdirTemp("", "server-test")
require.NoError(t, err, tt.name) require.NoError(t, err, tt.name)
require.NoError(t, db.Init(cacheDir), tt.name) require.NoError(t, db.Init(cacheDir), tt.name)
@@ -121,13 +120,13 @@ func Test_dbWorker_update(t *testing.T) {
mockDBClient.On("Download", mock.Anything, mock.Anything, false).Run( mockDBClient.On("Download", mock.Anything, mock.Anything, false).Run(
func(args mock.Arguments) { func(args mock.Arguments) {
// fake download: copy testdata/new.db to tmpDir/db/trivy.db // fake download: copy testdata/new.db to tmpDir/db/trivy.db
content, err := ioutil.ReadFile("testdata/new.db") content, err := os.ReadFile("testdata/new.db")
require.NoError(t, err, tt.name) require.NoError(t, err, tt.name)
tmpDir := args.String(1) tmpDir := args.String(1)
dbPath := db.Path(tmpDir) dbPath := db.Path(tmpDir)
require.NoError(t, os.MkdirAll(filepath.Dir(dbPath), 0777), tt.name) require.NoError(t, os.MkdirAll(filepath.Dir(dbPath), 0777), tt.name)
err = ioutil.WriteFile(dbPath, content, 0444) err = os.WriteFile(dbPath, content, 0444)
require.NoError(t, err, tt.name) require.NoError(t, err, tt.name)
}).Return(tt.download.err) }).Return(tt.download.err)
} }

View File

@@ -2,7 +2,6 @@ package utils
import ( import (
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"reflect" "reflect"
@@ -25,14 +24,14 @@ func touch(t *testing.T, name string) {
} }
func write(t *testing.T, name string, content string) { func write(t *testing.T, name string, content string) {
err := ioutil.WriteFile(name, []byte(content), 0666) err := os.WriteFile(name, []byte(content), 0666)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
func TestFileWalk(t *testing.T) { func TestFileWalk(t *testing.T) {
td, err := ioutil.TempDir("", "walktest") td, err := os.MkdirTemp("", "walktest")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -62,7 +61,7 @@ func TestFileWalk(t *testing.T) {
sawFoo2 = true sawFoo2 = true
} }
if strings.HasSuffix(path, "foo3") { if strings.HasSuffix(path, "foo3") {
contentFoo3, err = ioutil.ReadAll(r) contentFoo3, err = io.ReadAll(r)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -163,7 +162,7 @@ func TestCopyFile(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
src := tt.args.src src := tt.args.src
if tt.args.src == "" { if tt.args.src == "" {
s, err := ioutil.TempFile("", "src") s, err := os.CreateTemp("", "src")
require.NoError(t, err, tt.name) require.NoError(t, err, tt.name)
_, err = s.Write(tt.content) _, err = s.Write(tt.content)
require.NoError(t, err, tt.name) require.NoError(t, err, tt.name)
@@ -172,7 +171,7 @@ func TestCopyFile(t *testing.T) {
dst := tt.args.dst dst := tt.args.dst
if tt.args.dst == "" { if tt.args.dst == "" {
d, err := ioutil.TempFile("", "dst") d, err := os.CreateTemp("", "dst")
require.NoError(t, err, tt.name) require.NoError(t, err, tt.name)
dst = d.Name() dst = d.Name()
require.NoError(t, d.Close(), tt.name) require.NoError(t, d.Close(), tt.name)