diff --git a/copy/copy.go b/copy/copy.go index b616e566c..644f82615 100644 --- a/copy/copy.go +++ b/copy/copy.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "reflect" "strings" @@ -199,7 +198,7 @@ func Image(ctx context.Context, policyContext *signature.PolicyContext, destRef, return nil, err } - reportWriter := ioutil.Discard + reportWriter := io.Discard if options.ReportWriter != nil { reportWriter = options.ReportWriter @@ -232,7 +231,7 @@ func Image(ctx context.Context, policyContext *signature.PolicyContext, destRef, // createProgressBar() will print a single line instead. progressOutput := reportWriter if !isTTY(reportWriter) { - progressOutput = ioutil.Discard + progressOutput = io.Discard } c := &copier{ @@ -1091,7 +1090,7 @@ func customPartialBlobDecorFunc(s decor.Statistics) string { } // createProgressBar creates a mpb.Bar in pool. Note that if the copier's reportWriter -// is ioutil.Discard, the progress bar's output will be discarded +// is io.Discard, the progress bar's output will be discarded // NOTE: Every progress bar created within a progress pool must either successfully // complete or be aborted, or pool.Wait() will hang. That is typically done // using "defer bar.Abort(false)", which must happen BEFORE pool.Wait() is called. @@ -1143,7 +1142,7 @@ func (c *copier) createProgressBar(pool *mpb.Progress, partial bool, info types. ), ) } - if c.progressOutput == ioutil.Discard { + if c.progressOutput == io.Discard { c.Printf("Copying %s %s\n", kind, info.Digest) } return bar @@ -1669,7 +1668,7 @@ func (c *copier) copyBlobFromStream(ctx context.Context, srcStream io.Reader, sr // sent there if we are not already at EOF. if getOriginalLayerCopyWriter != nil { logrus.Debugf("Consuming rest of the original blob to satisfy getOriginalLayerCopyWriter") - _, err := io.Copy(ioutil.Discard, originalLayerReader) + _, err := io.Copy(io.Discard, originalLayerReader) if err != nil { return types.BlobInfo{}, errors.Wrapf(err, "reading input blob %s", srcInfo.Digest) } diff --git a/copy/sign_test.go b/copy/sign_test.go index 1e9fc6738..5c93d25fa 100644 --- a/copy/sign_test.go +++ b/copy/sign_test.go @@ -2,7 +2,7 @@ package copy import ( "context" - "io/ioutil" + "io" "os" "testing" @@ -48,7 +48,7 @@ func TestCreateSignature(t *testing.T) { defer dirDest.Close() c := &copier{ dest: imagedestination.FromPublic(dirDest), - reportWriter: ioutil.Discard, + reportWriter: io.Discard, } _, err = c.createSignature(manifestBlob, testKeyFingerprint, "", nil) assert.Error(t, err) @@ -62,7 +62,7 @@ func TestCreateSignature(t *testing.T) { defer dockerDest.Close() c = &copier{ dest: imagedestination.FromPublic(dockerDest), - reportWriter: ioutil.Discard, + reportWriter: io.Discard, } // Signing with an unknown key fails diff --git a/directory/directory_dest.go b/directory/directory_dest.go index ea20e7c5e..3b135e68e 100644 --- a/directory/directory_dest.go +++ b/directory/directory_dest.go @@ -3,7 +3,6 @@ package directory import ( "context" "io" - "io/ioutil" "os" "path/filepath" "runtime" @@ -62,7 +61,7 @@ func newImageDestination(sys *types.SystemContext, ref dirReference) (types.Imag return nil, errors.Wrapf(err, "checking if path exists %q", d.ref.versionPath()) } if versionExists { - contents, err := ioutil.ReadFile(d.ref.versionPath()) + contents, err := os.ReadFile(d.ref.versionPath()) if err != nil { return nil, err } @@ -86,7 +85,7 @@ func newImageDestination(sys *types.SystemContext, ref dirReference) (types.Imag } } // create version file - err = ioutil.WriteFile(d.ref.versionPath(), []byte(version), 0644) + err = os.WriteFile(d.ref.versionPath(), []byte(version), 0644) if err != nil { return nil, errors.Wrapf(err, "creating version file %q", d.ref.versionPath()) } @@ -149,7 +148,7 @@ func (d *dirImageDestination) HasThreadSafePutBlob() bool { // to any other readers for download using the supplied digest. // If stream.Read() at any time, ESPECIALLY at end of input, returns an error, PutBlob MUST 1) fail, and 2) delete any data stored so far. func (d *dirImageDestination) PutBlob(ctx context.Context, stream io.Reader, inputInfo types.BlobInfo, cache types.BlobInfoCache, isConfig bool) (types.BlobInfo, error) { - blobFile, err := ioutil.TempFile(d.ref.path, "dir-put-blob") + blobFile, err := os.CreateTemp(d.ref.path, "dir-put-blob") if err != nil { return types.BlobInfo{}, err } @@ -232,7 +231,7 @@ func (d *dirImageDestination) TryReusingBlob(ctx context.Context, info types.Blo // If the destination is in principle available, refuses this manifest type (e.g. it does not recognize the schema), // but may accept a different manifest type, the returned error must be an ManifestTypeRejectedError. func (d *dirImageDestination) PutManifest(ctx context.Context, manifest []byte, instanceDigest *digest.Digest) error { - return ioutil.WriteFile(d.ref.manifestPath(instanceDigest), manifest, 0644) + return os.WriteFile(d.ref.manifestPath(instanceDigest), manifest, 0644) } // PutSignatures writes a set of signatures to the destination. @@ -240,7 +239,7 @@ func (d *dirImageDestination) PutManifest(ctx context.Context, manifest []byte, // (when the primary manifest is a manifest list); this should always be nil if the primary manifest is not a manifest list. func (d *dirImageDestination) PutSignatures(ctx context.Context, signatures [][]byte, instanceDigest *digest.Digest) error { for i, sig := range signatures { - if err := ioutil.WriteFile(d.ref.signaturePath(i, instanceDigest), sig, 0644); err != nil { + if err := os.WriteFile(d.ref.signaturePath(i, instanceDigest), sig, 0644); err != nil { return err } } @@ -272,7 +271,7 @@ func pathExists(path string) (bool, error) { // returns true if directory is empty func isDirEmpty(path string) (bool, error) { - files, err := ioutil.ReadDir(path) + files, err := os.ReadDir(path) if err != nil { return false, err } @@ -281,7 +280,7 @@ func isDirEmpty(path string) (bool, error) { // deletes the contents of a directory func removeDirContents(path string) error { - files, err := ioutil.ReadDir(path) + files, err := os.ReadDir(path) if err != nil { return err } diff --git a/directory/directory_src.go b/directory/directory_src.go index ad9129d40..8b509112a 100644 --- a/directory/directory_src.go +++ b/directory/directory_src.go @@ -3,7 +3,6 @@ package directory import ( "context" "io" - "io/ioutil" "os" "github.com/containers/image/v5/manifest" @@ -37,7 +36,7 @@ func (s *dirImageSource) Close() error { // If instanceDigest is not nil, it contains a digest of the specific manifest instance to retrieve (when the primary manifest is a manifest list); // this never happens if the primary manifest is not a manifest list (e.g. if the source never returns manifest lists). func (s *dirImageSource) GetManifest(ctx context.Context, instanceDigest *digest.Digest) ([]byte, string, error) { - m, err := ioutil.ReadFile(s.ref.manifestPath(instanceDigest)) + m, err := os.ReadFile(s.ref.manifestPath(instanceDigest)) if err != nil { return nil, "", err } @@ -71,7 +70,7 @@ func (s *dirImageSource) GetBlob(ctx context.Context, info types.BlobInfo, cache func (s *dirImageSource) GetSignatures(ctx context.Context, instanceDigest *digest.Digest) ([][]byte, error) { signatures := [][]byte{} for i := 0; ; i++ { - signature, err := ioutil.ReadFile(s.ref.signaturePath(i, instanceDigest)) + signature, err := os.ReadFile(s.ref.signaturePath(i, instanceDigest)) if err != nil { if os.IsNotExist(err) { break diff --git a/directory/directory_test.go b/directory/directory_test.go index ce5429a01..c49041b4b 100644 --- a/directory/directory_test.go +++ b/directory/directory_test.go @@ -3,7 +3,7 @@ package directory import ( "bytes" "context" - "io/ioutil" + "io" "os" "testing" @@ -92,7 +92,7 @@ func TestGetPutBlob(t *testing.T) { rc, size, err := src.GetBlob(context.Background(), types.BlobInfo{Digest: digest, Size: int64(len(expectedBlob))}, cache) assert.NoError(t, err) defer rc.Close() - b, err := ioutil.ReadAll(rc) + b, err := io.ReadAll(rc) assert.NoError(t, err) assert.Equal(t, expectedBlob, b) assert.Equal(t, int64(len(expectedBlob)), size) diff --git a/directory/directory_transport_test.go b/directory/directory_transport_test.go index 30b210ebe..0ef96c4f6 100644 --- a/directory/directory_transport_test.go +++ b/directory/directory_transport_test.go @@ -2,7 +2,6 @@ package directory import ( "context" - "io/ioutil" "os" "path/filepath" "testing" @@ -145,7 +144,7 @@ func TestReferenceNewImage(t *testing.T) { dest, err := ref.NewImageDestination(context.Background(), nil) require.NoError(t, err) defer dest.Close() - mFixture, err := ioutil.ReadFile("../manifest/fixtures/v2s1.manifest.json") + mFixture, err := os.ReadFile("../manifest/fixtures/v2s1.manifest.json") require.NoError(t, err) err = dest.PutManifest(context.Background(), mFixture, nil) assert.NoError(t, err) diff --git a/docker/archive/transport_test.go b/docker/archive/transport_test.go index 4c06bdc88..599368556 100644 --- a/docker/archive/transport_test.go +++ b/docker/archive/transport_test.go @@ -3,7 +3,6 @@ package archive import ( "context" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -271,7 +270,7 @@ func TestReferenceDeleteImage(t *testing.T) { for i, suffix := range []string{"", ":some-reference", ":@0"} { testFile := filepath.Join(tmpDir, fmt.Sprintf("file%d.tar", i)) - err := ioutil.WriteFile(testFile, []byte("nonempty"), 0644) + err := os.WriteFile(testFile, []byte("nonempty"), 0644) require.NoError(t, err, suffix) ref, err := ParseReference(testFile + suffix) diff --git a/docker/docker_client.go b/docker/docker_client.go index 9837235d8..d984db718 100644 --- a/docker/docker_client.go +++ b/docker/docker_client.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -654,7 +653,7 @@ func (c *dockerClient) getBearerTokenOAuth2(ctx context.Context, challenge chall params.Add("refresh_token", c.auth.IdentityToken) params.Add("client_id", "containers/image") - authReq.Body = ioutil.NopCloser(bytes.NewBufferString(params.Encode())) + authReq.Body = io.NopCloser(bytes.NewBufferString(params.Encode())) authReq.Header.Add("User-Agent", c.userAgent) authReq.Header.Add("Content-Type", "application/x-www-form-urlencoded") logrus.Debugf("%s %s", authReq.Method, authReq.URL.Redacted()) diff --git a/docker/docker_image_dest.go b/docker/docker_image_dest.go index e3275aa45..d02100cf8 100644 --- a/docker/docker_image_dest.go +++ b/docker/docker_image_dest.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -592,7 +591,7 @@ func (d *dockerImageDestination) putOneSignature(url *url.URL, signature []byte) if err != nil { return err } - err = ioutil.WriteFile(url.Path, signature, 0644) + err = os.WriteFile(url.Path, signature, 0644) if err != nil { return err } diff --git a/docker/docker_image_src.go b/docker/docker_image_src.go index c08e5538a..c8e176f90 100644 --- a/docker/docker_image_src.go +++ b/docker/docker_image_src.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "mime" "mime/multipart" "net/http" @@ -308,7 +307,7 @@ func splitHTTP200ResponseToPartial(streams chan io.ReadCloser, errs chan error, break } toSkip := c.Offset - currentOffset - if _, err := io.Copy(ioutil.Discard, io.LimitReader(body, int64(toSkip))); err != nil { + if _, err := io.Copy(io.Discard, io.LimitReader(body, int64(toSkip))); err != nil { errs <- err break } @@ -316,7 +315,7 @@ func splitHTTP200ResponseToPartial(streams chan io.ReadCloser, errs chan error, } s := signalCloseReader{ closed: make(chan interface{}), - stream: ioutil.NopCloser(io.LimitReader(body, int64(c.Length))), + stream: io.NopCloser(io.LimitReader(body, int64(c.Length))), consumeStream: true, } streams <- s @@ -515,7 +514,7 @@ func (s *dockerImageSource) getOneSignature(ctx context.Context, url *url.URL) ( switch url.Scheme { case "file": logrus.Debugf("Reading %s", url.Path) - sig, err := ioutil.ReadFile(url.Path) + sig, err := os.ReadFile(url.Path) if err != nil { if os.IsNotExist(err) { return nil, true, nil @@ -765,7 +764,7 @@ func (s signalCloseReader) Read(p []byte) (int, error) { func (s signalCloseReader) Close() error { defer close(s.closed) if s.consumeStream { - if _, err := io.Copy(ioutil.Discard, s.stream); err != nil { + if _, err := io.Copy(io.Discard, s.stream); err != nil { s.stream.Close() return err } diff --git a/docker/docker_image_src_test.go b/docker/docker_image_src_test.go index 8d99082bd..ea9ee3dd8 100644 --- a/docker/docker_image_src_test.go +++ b/docker/docker_image_src_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "io" - "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -51,11 +50,11 @@ location = "with-mirror.example.com" [[registry.mirror]] location = "@REGISTRY@/with-mirror" `, "@REGISTRY@", registry, -1) - registriesConf, err := ioutil.TempFile("", "docker-image-src") + registriesConf, err := os.CreateTemp("", "docker-image-src") require.NoError(t, err) defer registriesConf.Close() defer os.Remove(registriesConf.Name()) - err = ioutil.WriteFile(registriesConf.Name(), []byte(mirrorConfiguration), 0600) + err = os.WriteFile(registriesConf.Name(), []byte(mirrorConfiguration), 0600) require.NoError(t, err) for _, c := range []struct{ input, physical string }{ @@ -108,7 +107,7 @@ func readNextStream(streams chan io.ReadCloser, errs chan error) ([]byte, error) return nil, nil } defer r.Close() - return ioutil.ReadAll(r) + return io.ReadAll(r) case err := <-errs: return nil, err } @@ -128,7 +127,7 @@ func verifyGetBlobAtOutput(t *testing.T, streams chan io.ReadCloser, errs chan e } func TestSplitHTTP200ResponseToPartial(t *testing.T) { - body := ioutil.NopCloser(bytes.NewReader([]byte("123456789"))) + body := io.NopCloser(bytes.NewReader([]byte("123456789"))) defer body.Close() streams := make(chan io.ReadCloser) errs := make(chan error) @@ -148,7 +147,7 @@ func TestSplitHTTP200ResponseToPartial(t *testing.T) { } func TestHandle206Response(t *testing.T) { - body := ioutil.NopCloser(bytes.NewReader([]byte("--AAA\r\n\r\n23\r\n--AAA\r\n\r\n5\r\n--AAA--"))) + body := io.NopCloser(bytes.NewReader([]byte("--AAA\r\n\r\n23\r\n--AAA\r\n\r\n5\r\n--AAA--"))) defer body.Close() streams := make(chan io.ReadCloser) errs := make(chan error) @@ -169,7 +168,7 @@ func TestHandle206Response(t *testing.T) { } verifyGetBlobAtOutput(t, streams, errs, expected) - body = ioutil.NopCloser(bytes.NewReader([]byte("HELLO"))) + body = io.NopCloser(bytes.NewReader([]byte("HELLO"))) defer body.Close() streams = make(chan io.ReadCloser) errs = make(chan error) diff --git a/docker/internal/tarfile/reader.go b/docker/internal/tarfile/reader.go index 6164ceb66..c77c002d1 100644 --- a/docker/internal/tarfile/reader.go +++ b/docker/internal/tarfile/reader.go @@ -4,7 +4,6 @@ import ( "archive/tar" "encoding/json" "io" - "io/ioutil" "os" "path" @@ -53,7 +52,7 @@ func NewReaderFromFile(sys *types.SystemContext, path string) (*Reader, error) { // The caller should call .Close() on the returned archive when done. func NewReaderFromStream(sys *types.SystemContext, inputStream io.Reader) (*Reader, error) { // Save inputStream to a temporary file - tarCopyFile, err := ioutil.TempFile(tmpdir.TemporaryDirectoryForBigFiles(sys), "docker-tar") + tarCopyFile, err := os.CreateTemp(tmpdir.TemporaryDirectoryForBigFiles(sys), "docker-tar") if err != nil { return nil, errors.Wrap(err, "creating temporary file") } diff --git a/docker/internal/tarfile/src.go b/docker/internal/tarfile/src.go index b8d84d245..8e9be17c1 100644 --- a/docker/internal/tarfile/src.go +++ b/docker/internal/tarfile/src.go @@ -6,7 +6,6 @@ import ( "context" "encoding/json" "io" - "io/ioutil" "os" "path" "sync" @@ -170,7 +169,7 @@ func (s *Source) prepareLayerData(tarManifest *ManifestItem, parsedConfig *manif uncompressedSize := h.Size if isCompressed { - uncompressedSize, err = io.Copy(ioutil.Discard, uncompressedStream) + uncompressedSize, err = io.Copy(io.Discard, uncompressedStream) if err != nil { return nil, errors.Wrapf(err, "reading %s to find its size", layerPath) } @@ -263,7 +262,7 @@ func (s *Source) GetBlob(ctx context.Context, info types.BlobInfo, cache types.B } if info.Digest == s.configDigest { // FIXME? Implement a more general algorithm matching instead of assuming sha256. - return ioutil.NopCloser(bytes.NewReader(s.configBytes)), int64(len(s.configBytes)), nil + return io.NopCloser(bytes.NewReader(s.configBytes)), int64(len(s.configBytes)), nil } if li, ok := s.knownLayers[info.Digest]; ok { // diffID is a digest of the uncompressed tarball, diff --git a/docker/internal/tarfile/src_test.go b/docker/internal/tarfile/src_test.go index f578f50c9..e1f678eab 100644 --- a/docker/internal/tarfile/src_test.go +++ b/docker/internal/tarfile/src_test.go @@ -3,7 +3,7 @@ package tarfile import ( "bytes" "context" - "io/ioutil" + "io" "testing" "github.com/containers/image/v5/manifest" @@ -55,7 +55,7 @@ func TestSourcePrepareLayerData(t *testing.T) { }, cache) if !c.shouldFail { require.NoError(t, err, c.config) - config2, err := ioutil.ReadAll(configStream) + config2, err := io.ReadAll(configStream) require.NoError(t, err, c.config) assert.Equal(t, []byte(c.config), config2, c.config) } else { diff --git a/docker/lookaside.go b/docker/lookaside.go index 22d84931c..d0a3f1be0 100644 --- a/docker/lookaside.go +++ b/docker/lookaside.go @@ -2,7 +2,6 @@ package docker import ( "fmt" - "io/ioutil" "net/url" "os" "path" @@ -146,7 +145,7 @@ func loadAndMergeConfig(dirPath string) (*registryConfiguration, error) { continue } configPath := filepath.Join(dirPath, configName) - configBytes, err := ioutil.ReadFile(configPath) + configBytes, err := os.ReadFile(configPath) if err != nil { return nil, err } diff --git a/docker/lookaside_test.go b/docker/lookaside_test.go index ddfff67b6..15689fe4b 100644 --- a/docker/lookaside_test.go +++ b/docker/lookaside_test.go @@ -2,7 +2,6 @@ package docker import ( "fmt" - "io/ioutil" "net/url" "os" "path/filepath" @@ -137,9 +136,9 @@ func TestLoadAndMergeConfig(t *testing.T) { unreadableFileDir := filepath.Join(tmpDir, "unreadableFile") err = os.Mkdir(unreadableFileDir, 0755) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(unreadableFileDir, "0.yaml"), []byte("{}"), 0644) + err = os.WriteFile(filepath.Join(unreadableFileDir, "0.yaml"), []byte("{}"), 0644) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(unreadableFileDir, "1.yaml"), nil, 0000) + err = os.WriteFile(filepath.Join(unreadableFileDir, "1.yaml"), nil, 0000) require.NoError(t, err) _, err = loadAndMergeConfig(unreadableFileDir) assert.Error(t, err) @@ -148,7 +147,7 @@ func TestLoadAndMergeConfig(t *testing.T) { invalidYAMLDir := filepath.Join(tmpDir, "invalidYAML") err = os.Mkdir(invalidYAMLDir, 0755) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(invalidYAMLDir, "0.yaml"), []byte("}"), 0644) + err = os.WriteFile(filepath.Join(invalidYAMLDir, "0.yaml"), []byte("}"), 0644) require.NoError(t, err) _, err = loadAndMergeConfig(invalidYAMLDir) assert.Error(t, err) @@ -157,10 +156,10 @@ func TestLoadAndMergeConfig(t *testing.T) { duplicateDefault := filepath.Join(tmpDir, "duplicateDefault") err = os.Mkdir(duplicateDefault, 0755) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(duplicateDefault, "0.yaml"), + err = os.WriteFile(filepath.Join(duplicateDefault, "0.yaml"), []byte("default-docker:\n sigstore: file:////tmp/something"), 0644) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(duplicateDefault, "1.yaml"), + err = os.WriteFile(filepath.Join(duplicateDefault, "1.yaml"), []byte("default-docker:\n sigstore: file:////tmp/different"), 0644) require.NoError(t, err) _, err = loadAndMergeConfig(duplicateDefault) @@ -171,10 +170,10 @@ func TestLoadAndMergeConfig(t *testing.T) { duplicateNS := filepath.Join(tmpDir, "duplicateNS") err = os.Mkdir(duplicateNS, 0755) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(duplicateNS, "0.yaml"), + err = os.WriteFile(filepath.Join(duplicateNS, "0.yaml"), []byte("docker:\n example.com:\n sigstore: file:////tmp/something"), 0644) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(duplicateNS, "1.yaml"), + err = os.WriteFile(filepath.Join(duplicateNS, "1.yaml"), []byte("docker:\n example.com:\n sigstore: file:////tmp/different"), 0644) require.NoError(t, err) _, err = loadAndMergeConfig(duplicateNS) diff --git a/go.mod b/go.mod index 081be1d20..04a3d32be 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/containers/image/v5 -go 1.15 +go 1.16 require ( github.com/14rcole/gopopulate v0.0.0-20180821133914-b175b219e774 // indirect diff --git a/go.sum b/go.sum index cb2eb9461..6448efd32 100644 --- a/go.sum +++ b/go.sum @@ -302,7 +302,6 @@ github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsr github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/cyphar/filepath-securejoin v0.2.2/go.mod h1:FpkQEhXnPnOthhzymB7CGsFk2G9VLXONKD9G7QGMM+4= github.com/cyphar/filepath-securejoin v0.2.3 h1:YX6ebbZCZP7VkM3scTTokDgBL2TY741X51MTk3ycuNI= diff --git a/image/docker_schema1_test.go b/image/docker_schema1_test.go index d63fefe82..6aa7405e0 100644 --- a/image/docker_schema1_test.go +++ b/image/docker_schema1_test.go @@ -3,7 +3,7 @@ package image import ( "context" "encoding/json" - "io/ioutil" + "os" "path/filepath" "testing" "time" @@ -96,7 +96,7 @@ var schema1WithThrowawaysFixtureLayerDiffIDs = []digest.Digest{ } func manifestSchema1FromFixture(t *testing.T, fixture string) genericManifest { - manifest, err := ioutil.ReadFile(filepath.Join("fixtures", fixture)) + manifest, err := os.ReadFile(filepath.Join("fixtures", fixture)) require.NoError(t, err) m, err := manifestSchema1FromManifest(manifest) @@ -157,7 +157,7 @@ func TestManifestSchema1Serialize(t *testing.T) { err = json.Unmarshal(serialized, &contents) require.NoError(t, err) - original, err := ioutil.ReadFile("fixtures/schema1.json") + original, err := os.ReadFile("fixtures/schema1.json") require.NoError(t, err) var originalContents map[string]interface{} err = json.Unmarshal(original, &originalContents) @@ -428,7 +428,7 @@ func TestManifestSchema1ConvertToSchema2(t *testing.T) { require.NoError(t, err) assert.Equal(t, manifest.DockerV2Schema2MediaType, mt) - byHandJSON, err := ioutil.ReadFile("fixtures/schema1-to-schema2.json") + byHandJSON, err := os.ReadFile("fixtures/schema1-to-schema2.json") require.NoError(t, err) var converted, byHand map[string]interface{} err = json.Unmarshal(byHandJSON, &byHand) @@ -442,7 +442,7 @@ func TestManifestSchema1ConvertToSchema2(t *testing.T) { convertedConfig, err := res.ConfigBlob(context.Background()) require.NoError(t, err) - byHandConfig, err := ioutil.ReadFile("fixtures/schema1-to-schema2-config.json") + byHandConfig, err := os.ReadFile("fixtures/schema1-to-schema2-config.json") require.NoError(t, err) converted = map[string]interface{}{} byHand = map[string]interface{}{} @@ -521,7 +521,7 @@ func TestManifestSchema1ConvertToManifestOCI1(t *testing.T) { require.NoError(t, err) assert.Equal(t, imgspecv1.MediaTypeImageManifest, mt) - byHandJSON, err := ioutil.ReadFile("fixtures/schema1-to-oci1.json") + byHandJSON, err := os.ReadFile("fixtures/schema1-to-oci1.json") require.NoError(t, err) var converted, byHand map[string]interface{} err = json.Unmarshal(byHandJSON, &byHand) @@ -535,7 +535,7 @@ func TestManifestSchema1ConvertToManifestOCI1(t *testing.T) { convertedConfig, err := res.ConfigBlob(context.Background()) require.NoError(t, err) - byHandConfig, err := ioutil.ReadFile("fixtures/schema1-to-oci1-config.json") + byHandConfig, err := os.ReadFile("fixtures/schema1-to-oci1-config.json") require.NoError(t, err) converted = map[string]interface{}{} byHand = map[string]interface{}{} diff --git a/image/docker_schema2_test.go b/image/docker_schema2_test.go index 2884fc394..d78f5b486 100644 --- a/image/docker_schema2_test.go +++ b/image/docker_schema2_test.go @@ -6,7 +6,7 @@ import ( "encoding/hex" "encoding/json" "io" - "io/ioutil" + "os" "path/filepath" "testing" "time" @@ -47,7 +47,7 @@ func (f unusedImageSource) LayerInfosForCopy(context.Context, *digest.Digest) ([ } func manifestSchema2FromFixture(t *testing.T, src types.ImageSource, fixture string, mustFail bool) genericManifest { - manifest, err := ioutil.ReadFile(filepath.Join("fixtures", fixture)) + manifest, err := os.ReadFile(filepath.Join("fixtures", fixture)) require.NoError(t, err) m, err := manifestSchema2FromManifest(src, manifest) @@ -119,7 +119,7 @@ func TestManifestSchema2Serialize(t *testing.T) { err = json.Unmarshal(serialized, &contents) require.NoError(t, err) - original, err := ioutil.ReadFile("fixtures/schema2.json") + original, err := os.ReadFile("fixtures/schema2.json") require.NoError(t, err) var originalContents map[string]interface{} err = json.Unmarshal(original, &originalContents) @@ -168,7 +168,7 @@ func (f configBlobImageSource) GetBlob(ctx context.Context, info types.BlobInfo, } func TestManifestSchema2ConfigBlob(t *testing.T) { - realConfigJSON, err := ioutil.ReadFile("fixtures/schema2-config.json") + realConfigJSON, err := os.ReadFile("fixtures/schema2-config.json") require.NoError(t, err) for _, c := range []struct { @@ -177,7 +177,7 @@ func TestManifestSchema2ConfigBlob(t *testing.T) { }{ // Success {func(digest digest.Digest) (io.ReadCloser, int64, error) { - return ioutil.NopCloser(bytes.NewReader(realConfigJSON)), int64(len(realConfigJSON)), nil + return io.NopCloser(bytes.NewReader(realConfigJSON)), int64(len(realConfigJSON)), nil }, realConfigJSON}, // Various kinds of failures {nil, nil}, @@ -192,7 +192,7 @@ func TestManifestSchema2ConfigBlob(t *testing.T) { }, nil}, {func(digest digest.Digest) (io.ReadCloser, int64, error) { nonmatchingJSON := []byte("This does not match ConfigDescriptor.Digest") - return ioutil.NopCloser(bytes.NewReader(nonmatchingJSON)), int64(len(nonmatchingJSON)), nil + return io.NopCloser(bytes.NewReader(nonmatchingJSON)), int64(len(nonmatchingJSON)), nil }, nil}, } { var src types.ImageSource @@ -273,7 +273,7 @@ func TestManifestSchema2EmbeddedDockerReferenceConflicts(t *testing.T) { } func TestManifestSchema2Inspect(t *testing.T) { - configJSON, err := ioutil.ReadFile("fixtures/schema2-config.json") + configJSON, err := os.ReadFile("fixtures/schema2-config.json") require.NoError(t, err) m := manifestSchema2FromComponentsLikeFixture(configJSON) @@ -367,7 +367,7 @@ func (ref refImageReferenceMock) DeleteImage(ctx context.Context, sys *types.Sys } func newSchema2ImageSource(t *testing.T, dockerRef string) *schema2ImageSource { - realConfigJSON, err := ioutil.ReadFile("fixtures/schema2-config.json") + realConfigJSON, err := os.ReadFile("fixtures/schema2-config.json") require.NoError(t, err) ref, err := reference.ParseNormalizedNamed(dockerRef) @@ -376,7 +376,7 @@ func newSchema2ImageSource(t *testing.T, dockerRef string) *schema2ImageSource { return &schema2ImageSource{ configBlobImageSource: configBlobImageSource{ f: func(digest digest.Digest) (io.ReadCloser, int64, error) { - return ioutil.NopCloser(bytes.NewReader(realConfigJSON)), int64(len(realConfigJSON)), nil + return io.NopCloser(bytes.NewReader(realConfigJSON)), int64(len(realConfigJSON)), nil }, }, ref: ref, @@ -422,7 +422,7 @@ func (d *memoryImageDest) PutBlob(ctx context.Context, stream io.Reader, inputIn if inputInfo.Digest == "" { panic("inputInfo.Digest unexpectedly empty") } - contents, err := ioutil.ReadAll(stream) + contents, err := io.ReadAll(stream) if err != nil { return types.BlobInfo{}, err } @@ -535,7 +535,7 @@ func TestConvertToManifestOCI(t *testing.T) { require.NoError(t, err) assert.Equal(t, imgspecv1.MediaTypeImageManifest, mt) - byHandJSON, err := ioutil.ReadFile("fixtures/schema2-to-oci1.json") + byHandJSON, err := os.ReadFile("fixtures/schema2-to-oci1.json") require.NoError(t, err) var converted, byHand map[string]interface{} err = json.Unmarshal(byHandJSON, &byHand) @@ -556,7 +556,7 @@ func TestConvertToManifestOCIAllMediaTypes(t *testing.T) { require.NoError(t, err) assert.Equal(t, imgspecv1.MediaTypeImageManifest, mt) - byHandJSON, err := ioutil.ReadFile("fixtures/schema2-all-media-types-to-oci1.json") + byHandJSON, err := os.ReadFile("fixtures/schema2-all-media-types-to-oci1.json") require.NoError(t, err) var converted, byHand map[string]interface{} err = json.Unmarshal(byHandJSON, &byHand) @@ -590,7 +590,7 @@ func TestConvertToManifestSchema1(t *testing.T) { // byDockerJSON is the result of asking the Docker Hub for a schema1 manifest, // except that we have replaced "name" to verify that the ref from // memoryDest, not from originalSrc, is used. - byDockerJSON, err := ioutil.ReadFile("fixtures/schema2-to-schema1-by-docker.json") + byDockerJSON, err := os.ReadFile("fixtures/schema2-to-schema1-by-docker.json") require.NoError(t, err) var converted, byDocker map[string]interface{} err = json.Unmarshal(byDockerJSON, &byDocker) diff --git a/image/oci_test.go b/image/oci_test.go index 2d1f59a22..5dca7a5fe 100644 --- a/image/oci_test.go +++ b/image/oci_test.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" "io" - "io/ioutil" + "os" "path/filepath" "testing" "time" @@ -21,7 +21,7 @@ import ( ) func manifestOCI1FromFixture(t *testing.T, src types.ImageSource, fixture string) genericManifest { - manifest, err := ioutil.ReadFile(filepath.Join("fixtures", fixture)) + manifest, err := os.ReadFile(filepath.Join("fixtures", fixture)) require.NoError(t, err) m, err := manifestOCI1FromManifest(src, manifest) @@ -98,7 +98,7 @@ func TestManifestOCI1Serialize(t *testing.T) { err = json.Unmarshal(serialized, &contents) require.NoError(t, err) - original, err := ioutil.ReadFile("fixtures/oci1.json") + original, err := os.ReadFile("fixtures/oci1.json") require.NoError(t, err) var originalContents map[string]interface{} err = json.Unmarshal(original, &originalContents) @@ -137,7 +137,7 @@ func TestManifestOCI1ConfigInfo(t *testing.T) { } func TestManifestOCI1ConfigBlob(t *testing.T) { - realConfigJSON, err := ioutil.ReadFile("fixtures/oci1-config.json") + realConfigJSON, err := os.ReadFile("fixtures/oci1-config.json") require.NoError(t, err) for _, c := range []struct { @@ -146,7 +146,7 @@ func TestManifestOCI1ConfigBlob(t *testing.T) { }{ // Success {func(digest digest.Digest) (io.ReadCloser, int64, error) { - return ioutil.NopCloser(bytes.NewReader(realConfigJSON)), int64(len(realConfigJSON)), nil + return io.NopCloser(bytes.NewReader(realConfigJSON)), int64(len(realConfigJSON)), nil }, realConfigJSON}, // Various kinds of failures {nil, nil}, @@ -161,7 +161,7 @@ func TestManifestOCI1ConfigBlob(t *testing.T) { }, nil}, {func(digest digest.Digest) (io.ReadCloser, int64, error) { nonmatchingJSON := []byte("This does not match ConfigDescriptor.Digest") - return ioutil.NopCloser(bytes.NewReader(nonmatchingJSON)), int64(len(nonmatchingJSON)), nil + return io.NopCloser(bytes.NewReader(nonmatchingJSON)), int64(len(nonmatchingJSON)), nil }, nil}, } { var src types.ImageSource @@ -248,7 +248,7 @@ func TestManifestOCI1EmbeddedDockerReferenceConflicts(t *testing.T) { } func TestManifestOCI1Inspect(t *testing.T) { - configJSON, err := ioutil.ReadFile("fixtures/oci1-config.json") + configJSON, err := os.ReadFile("fixtures/oci1-config.json") require.NoError(t, err) m := manifestOCI1FromComponentsLikeFixture(configJSON) @@ -311,7 +311,7 @@ func (OCIis *oci1ImageSource) Reference() types.ImageReference { } func newOCI1ImageSource(t *testing.T, dockerRef string) *oci1ImageSource { - realConfigJSON, err := ioutil.ReadFile("fixtures/oci1-config.json") + realConfigJSON, err := os.ReadFile("fixtures/oci1-config.json") require.NoError(t, err) ref, err := reference.ParseNormalizedNamed(dockerRef) @@ -320,7 +320,7 @@ func newOCI1ImageSource(t *testing.T, dockerRef string) *oci1ImageSource { return &oci1ImageSource{ configBlobImageSource: configBlobImageSource{ f: func(digest digest.Digest) (io.ReadCloser, int64, error) { - return ioutil.NopCloser(bytes.NewReader(realConfigJSON)), int64(len(realConfigJSON)), nil + return io.NopCloser(bytes.NewReader(realConfigJSON)), int64(len(realConfigJSON)), nil }, }, ref: ref, @@ -404,7 +404,7 @@ func TestManifestOCI1ConvertToManifestSchema1(t *testing.T) { require.NoError(t, err) assert.Equal(t, manifest.DockerV2Schema1SignedMediaType, mt) - byHandJSON, err := ioutil.ReadFile("fixtures/oci1-to-schema1.json") + byHandJSON, err := os.ReadFile("fixtures/oci1-to-schema1.json") require.NoError(t, err) var converted, byHand map[string]interface{} err = json.Unmarshal(byHandJSON, &byHand) @@ -468,7 +468,7 @@ func TestConvertToManifestSchema2(t *testing.T) { require.NoError(t, err) assert.Equal(t, manifest.DockerV2Schema2MediaType, mt) - byHandJSON, err := ioutil.ReadFile("fixtures/oci1-to-schema2.json") + byHandJSON, err := os.ReadFile("fixtures/oci1-to-schema2.json") require.NoError(t, err) var converted, byHand map[string]interface{} err = json.Unmarshal(byHandJSON, &byHand) @@ -491,7 +491,7 @@ func TestConvertToManifestSchema2AllMediaTypes(t *testing.T) { func TestConvertToV2S2WithInvalidMIMEType(t *testing.T) { originalSrc := newOCI1ImageSource(t, "httpd-copy:latest") - manifest, err := ioutil.ReadFile(filepath.Join("fixtures", "oci1-invalid-media-type.json")) + manifest, err := os.ReadFile(filepath.Join("fixtures", "oci1-invalid-media-type.json")) require.NoError(t, err) _, err = manifestOCI1FromManifest(originalSrc, manifest) diff --git a/internal/iolimits/iolimits.go b/internal/iolimits/iolimits.go index 3fed1995c..49fa410e9 100644 --- a/internal/iolimits/iolimits.go +++ b/internal/iolimits/iolimits.go @@ -2,7 +2,6 @@ package iolimits import ( "io" - "io/ioutil" "github.com/pkg/errors" ) @@ -47,7 +46,7 @@ const ( func ReadAtMost(reader io.Reader, limit int) ([]byte, error) { limitedReader := io.LimitReader(reader, int64(limit+1)) - res, err := ioutil.ReadAll(limitedReader) + res, err := io.ReadAll(limitedReader) if err != nil { return nil, err } diff --git a/internal/putblobdigest/put_blob_digest_test.go b/internal/putblobdigest/put_blob_digest_test.go index 363a9c092..eb8ebbc05 100644 --- a/internal/putblobdigest/put_blob_digest_test.go +++ b/internal/putblobdigest/put_blob_digest_test.go @@ -3,7 +3,6 @@ package putblobdigest import ( "bytes" "io" - "io/ioutil" "testing" "github.com/containers/image/v5/types" @@ -26,7 +25,7 @@ func testDigester(t *testing.T, constructor func(io.Reader, types.BlobInfo) (Dig stream := bytes.NewReader(testData) digester, newStream := constructor(stream, types.BlobInfo{Digest: c.inputDigest}) assert.Equal(t, c.computesDigest, newStream != stream, c.inputDigest) - data, err := ioutil.ReadAll(newStream) + data, err := io.ReadAll(newStream) require.NoError(t, err, c.inputDigest) assert.Equal(t, testData, data, c.inputDigest) digest := digester.Digest() diff --git a/internal/streamdigest/stream_digest.go b/internal/streamdigest/stream_digest.go index 306220585..84bb656ac 100644 --- a/internal/streamdigest/stream_digest.go +++ b/internal/streamdigest/stream_digest.go @@ -3,7 +3,6 @@ package streamdigest import ( "fmt" "io" - "io/ioutil" "os" "github.com/containers/image/v5/internal/putblobdigest" @@ -16,7 +15,7 @@ import ( // It is the caller's responsibility to call the cleanup function, which closes and removes the temporary file. // If an error occurs, inputInfo is not modified. func ComputeBlobInfo(sys *types.SystemContext, stream io.Reader, inputInfo *types.BlobInfo) (io.Reader, func(), error) { - diskBlob, err := ioutil.TempFile(tmpdir.TemporaryDirectoryForBigFiles(sys), "stream-blob") + diskBlob, err := os.CreateTemp(tmpdir.TemporaryDirectoryForBigFiles(sys), "stream-blob") if err != nil { return nil, nil, fmt.Errorf("creating temporary on-disk layer: %w", err) } diff --git a/internal/streamdigest/stream_digest_test.go b/internal/streamdigest/stream_digest_test.go index b211c5361..b0a1327d3 100644 --- a/internal/streamdigest/stream_digest_test.go +++ b/internal/streamdigest/stream_digest_test.go @@ -1,7 +1,7 @@ package streamdigest import ( - "io/ioutil" + "io" "os" "testing" @@ -30,7 +30,7 @@ func TestComputeBlobInfo(t *testing.T) { assert.Equal(t, inputInfo, fixtureInfo) // ensure streamCopy is the same as fixture - b, err := ioutil.ReadAll(streamCopy) + b, err := io.ReadAll(streamCopy) require.NoError(t, err) assert.Equal(t, b, fixtureBytes) } diff --git a/internal/testing/explicitfilepath-tmpdir/tmpdir.go b/internal/testing/explicitfilepath-tmpdir/tmpdir.go index f87e149b2..a47ada4b7 100644 --- a/internal/testing/explicitfilepath-tmpdir/tmpdir.go +++ b/internal/testing/explicitfilepath-tmpdir/tmpdir.go @@ -1,13 +1,13 @@ // Package tmpdir is a TESTING-ONLY utility. // // Some tests directly or indirectly exercising the directory/explicitfilepath -// subpackage expect the path returned by ioutil.TempDir to be canonical in the +// subpackage expect the path returned by os.MkdirTemp to be canonical in the // directory/explicitfilepath sense (absolute, no symlinks, cleaned up). // -// ioutil.TempDir uses $TMPDIR by default, and on macOS, $TMPDIR is by +// os.MkdirTemp uses $TMPDIR by default, and on macOS, $TMPDIR is by // default set to /var/folders/…, with /var a symlink to /private/var , // which does not match our expectations. So, tests which want to use -// ioutil.TempDir that way, can +// os.MkdirTemp that way, can // import _ "github.com/containers/image/internal/testing/explicitfilepath-tmpdir" // to ensure that $TMPDIR is canonical and usable as a base for testing // path canonicalization in its subdirectories. diff --git a/internal/uploadreader/upload_reader_test.go b/internal/uploadreader/upload_reader_test.go index 3a1753a1b..c91967a15 100644 --- a/internal/uploadreader/upload_reader_test.go +++ b/internal/uploadreader/upload_reader_test.go @@ -4,7 +4,6 @@ import ( "bytes" "errors" "io" - "io/ioutil" "testing" "github.com/stretchr/testify/assert" @@ -17,19 +16,19 @@ func TestUploadReader(t *testing.T) { data := bytes.Repeat([]byte{0x01}, 65535) // No termination ur := NewUploadReader(bytes.NewReader(data)) - read, err := ioutil.ReadAll(ur) + read, err := io.ReadAll(ur) require.NoError(t, err) assert.Equal(t, data, read) // Terminated ur = NewUploadReader(bytes.NewReader(data)) readLen := len(data) / 2 - read, err = ioutil.ReadAll(io.LimitReader(ur, int64(readLen))) + read, err = io.ReadAll(io.LimitReader(ur, int64(readLen))) require.NoError(t, err) assert.Equal(t, data[:readLen], read) terminationErr := errors.New("Terminated") ur.Terminate(terminationErr) - read, err = ioutil.ReadAll(ur) + read, err = io.ReadAll(ur) assert.Equal(t, terminationErr, err) assert.Len(t, read, 0) } diff --git a/manifest/common_test.go b/manifest/common_test.go index cddfe18bb..15b92f88e 100644 --- a/manifest/common_test.go +++ b/manifest/common_test.go @@ -3,7 +3,7 @@ package manifest import ( "bytes" "fmt" - "io/ioutil" + "os" "path/filepath" "testing" @@ -69,7 +69,7 @@ func TestValidateUnambiguousManifestFormat(t *testing.T) { // Intended to help test manifest parsers' detection of schema mismatches. func testManifestFixturesAreRejected(t *testing.T, parser func([]byte) error, fixtures []string) { for _, fixture := range fixtures { - manifest, err := ioutil.ReadFile(filepath.Join("fixtures", fixture)) + manifest, err := os.ReadFile(filepath.Join("fixtures", fixture)) require.NoError(t, err, fixture) err = parser(manifest) assert.Error(t, err, fixture) diff --git a/manifest/docker_schema1_test.go b/manifest/docker_schema1_test.go index 72d570340..93accdfff 100644 --- a/manifest/docker_schema1_test.go +++ b/manifest/docker_schema1_test.go @@ -1,7 +1,7 @@ package manifest import ( - "io/ioutil" + "os" "path/filepath" "testing" "time" @@ -12,7 +12,7 @@ import ( ) func manifestSchema1FromFixture(t *testing.T, fixture string) *Schema1 { - manifest, err := ioutil.ReadFile(filepath.Join("fixtures", fixture)) + manifest, err := os.ReadFile(filepath.Join("fixtures", fixture)) require.NoError(t, err) m, err := Schema1FromManifest(manifest) @@ -21,7 +21,7 @@ func manifestSchema1FromFixture(t *testing.T, fixture string) *Schema1 { } func TestSchema1FromManifest(t *testing.T) { - validManifest, err := ioutil.ReadFile(filepath.Join("fixtures", "schema2-to-schema1-by-docker.json")) + validManifest, err := os.ReadFile(filepath.Join("fixtures", "schema2-to-schema1-by-docker.json")) require.NoError(t, err) // Invalid manifest version is rejected diff --git a/manifest/docker_schema2_list_test.go b/manifest/docker_schema2_list_test.go index 40ffa8ddd..0d7807ffa 100644 --- a/manifest/docker_schema2_list_test.go +++ b/manifest/docker_schema2_list_test.go @@ -1,7 +1,7 @@ package manifest import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -9,7 +9,7 @@ import ( ) func TestSchema2ListFromManifest(t *testing.T) { - validManifest, err := ioutil.ReadFile(filepath.Join("fixtures", "v2list.manifest.json")) + validManifest, err := os.ReadFile(filepath.Join("fixtures", "v2list.manifest.json")) require.NoError(t, err) parser := func(m []byte) error { diff --git a/manifest/docker_schema2_test.go b/manifest/docker_schema2_test.go index f6bc16b41..a16144705 100644 --- a/manifest/docker_schema2_test.go +++ b/manifest/docker_schema2_test.go @@ -1,7 +1,7 @@ package manifest import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -61,7 +61,7 @@ func TestSupportedSchema2MediaType(t *testing.T) { } func TestSchema2FromManifest(t *testing.T) { - validManifest, err := ioutil.ReadFile(filepath.Join("fixtures", "v2s2.manifest.json")) + validManifest, err := os.ReadFile(filepath.Join("fixtures", "v2s2.manifest.json")) require.NoError(t, err) parser := func(m []byte) error { @@ -79,7 +79,7 @@ func TestSchema2FromManifest(t *testing.T) { } func TestUpdateLayerInfosV2S2GzipToZstd(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/v2s2.manifest.json") + bytes, err := os.ReadFile("fixtures/v2s2.manifest.json") assert.Nil(t, err) origManifest, err := Schema2FromManifest(bytes) @@ -112,7 +112,7 @@ func TestUpdateLayerInfosV2S2GzipToZstd(t *testing.T) { } func TestUpdateLayerInfosV2S2InvalidCompressionOperation(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/v2s2.manifest.json") + bytes, err := os.ReadFile("fixtures/v2s2.manifest.json") assert.Nil(t, err) origManifest, err := Schema2FromManifest(bytes) @@ -142,7 +142,7 @@ func TestUpdateLayerInfosV2S2InvalidCompressionOperation(t *testing.T) { } func TestUpdateLayerInfosV2S2InvalidCompressionAlgorithm(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/v2s2.manifest.json") + bytes, err := os.ReadFile("fixtures/v2s2.manifest.json") assert.Nil(t, err) origManifest, err := Schema2FromManifest(bytes) @@ -175,7 +175,7 @@ func TestUpdateLayerInfosV2S2InvalidCompressionAlgorithm(t *testing.T) { } func TestUpdateLayerInfosV2S2NondistributableToGzip(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/v2s2.nondistributable.manifest.json") + bytes, err := os.ReadFile("fixtures/v2s2.nondistributable.manifest.json") assert.Nil(t, err) origManifest, err := Schema2FromManifest(bytes) @@ -195,7 +195,7 @@ func TestUpdateLayerInfosV2S2NondistributableToGzip(t *testing.T) { updatedManifestBytes, err := origManifest.Serialize() assert.Nil(t, err) - bytes, err = ioutil.ReadFile("fixtures/v2s2.nondistributable.gzip.manifest.json") + bytes, err = os.ReadFile("fixtures/v2s2.nondistributable.gzip.manifest.json") assert.Nil(t, err) expectedManifest, err := Schema2FromManifest(bytes) @@ -208,7 +208,7 @@ func TestUpdateLayerInfosV2S2NondistributableToGzip(t *testing.T) { } func TestUpdateLayerInfosV2S2NondistributableGzipToUncompressed(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/v2s2.nondistributable.gzip.manifest.json") + bytes, err := os.ReadFile("fixtures/v2s2.nondistributable.gzip.manifest.json") assert.Nil(t, err) origManifest, err := Schema2FromManifest(bytes) @@ -227,7 +227,7 @@ func TestUpdateLayerInfosV2S2NondistributableGzipToUncompressed(t *testing.T) { updatedManifestBytes, err := origManifest.Serialize() assert.Nil(t, err) - bytes, err = ioutil.ReadFile("fixtures/v2s2.nondistributable.manifest.json") + bytes, err = os.ReadFile("fixtures/v2s2.nondistributable.manifest.json") assert.Nil(t, err) expectedManifest, err := Schema2FromManifest(bytes) diff --git a/manifest/list_test.go b/manifest/list_test.go index 34558c456..47d5e0918 100644 --- a/manifest/list_test.go +++ b/manifest/list_test.go @@ -2,7 +2,7 @@ package manifest import ( "fmt" - "io/ioutil" + "os" "path/filepath" "testing" @@ -33,7 +33,7 @@ func TestParseLists(t *testing.T) { {"v2list.manifest.json", DockerV2ListMediaType}, } for _, c := range cases { - manifest, err := ioutil.ReadFile(filepath.Join("fixtures", c.path)) + manifest, err := os.ReadFile(filepath.Join("fixtures", c.path)) require.NoError(t, err, "error reading file %q", filepath.Join("fixtures", c.path)) assert.Equal(t, GuessMIMEType(manifest), c.mimeType) @@ -113,7 +113,7 @@ func TestChooseInstance(t *testing.T) { }, }, } { - rawManifest, err := ioutil.ReadFile(filepath.Join("..", "image", "fixtures", manifestList.listFile)) + rawManifest, err := os.ReadFile(filepath.Join("..", "image", "fixtures", manifestList.listFile)) require.NoError(t, err) list, err := ListFromBlob(rawManifest, GuessMIMEType(rawManifest)) require.NoError(t, err) diff --git a/manifest/manifest_test.go b/manifest/manifest_test.go index 88ea359ac..677b13650 100644 --- a/manifest/manifest_test.go +++ b/manifest/manifest_test.go @@ -1,7 +1,7 @@ package manifest import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -38,7 +38,7 @@ func TestGuessMIMEType(t *testing.T) { } for _, c := range cases { - manifest, err := ioutil.ReadFile(filepath.Join("fixtures", c.path)) + manifest, err := os.ReadFile(filepath.Join("fixtures", c.path)) require.NoError(t, err) mimeType := GuessMIMEType(manifest) assert.Equal(t, c.mimeType, mimeType, c.path) @@ -55,14 +55,14 @@ func TestDigest(t *testing.T) { {"v2s1-unsigned.manifest.json", TestDockerV2S1UnsignedManifestDigest}, } for _, c := range cases { - manifest, err := ioutil.ReadFile(filepath.Join("fixtures", c.path)) + manifest, err := os.ReadFile(filepath.Join("fixtures", c.path)) require.NoError(t, err) actualDigest, err := Digest(manifest) require.NoError(t, err) assert.Equal(t, c.expectedDigest, actualDigest) } - manifest, err := ioutil.ReadFile("fixtures/v2s1-invalid-signatures.manifest.json") + manifest, err := os.ReadFile("fixtures/v2s1-invalid-signatures.manifest.json") require.NoError(t, err) _, err = Digest(manifest) assert.Error(t, err) @@ -92,14 +92,14 @@ func TestMatchesDigest(t *testing.T) { {"v2s2.manifest.json", digest.Digest(""), false}, } for _, c := range cases { - manifest, err := ioutil.ReadFile(filepath.Join("fixtures", c.path)) + manifest, err := os.ReadFile(filepath.Join("fixtures", c.path)) require.NoError(t, err) res, err := MatchesDigest(manifest, c.expectedDigest) require.NoError(t, err) assert.Equal(t, c.result, res) } - manifest, err := ioutil.ReadFile("fixtures/v2s1-invalid-signatures.manifest.json") + manifest, err := os.ReadFile("fixtures/v2s1-invalid-signatures.manifest.json") require.NoError(t, err) // Even a correct SHA256 hash is rejected if we can't strip the JSON signature. res, err := MatchesDigest(manifest, digest.FromBytes(manifest)) @@ -112,7 +112,7 @@ func TestMatchesDigest(t *testing.T) { } func TestAddDummyV2S1Signature(t *testing.T) { - manifest, err := ioutil.ReadFile("fixtures/v2s1-unsigned.manifest.json") + manifest, err := os.ReadFile("fixtures/v2s1-unsigned.manifest.json") require.NoError(t, err) signedManifest, err := AddDummyV2S1Signature(manifest) diff --git a/manifest/oci_index_test.go b/manifest/oci_index_test.go index 1461ee5b6..defa85f54 100644 --- a/manifest/oci_index_test.go +++ b/manifest/oci_index_test.go @@ -1,7 +1,7 @@ package manifest import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -9,7 +9,7 @@ import ( ) func TestOCI1IndexFromManifest(t *testing.T) { - validManifest, err := ioutil.ReadFile(filepath.Join("fixtures", "ociv1.image.index.json")) + validManifest, err := os.ReadFile(filepath.Join("fixtures", "ociv1.image.index.json")) require.NoError(t, err) parser := func(m []byte) error { diff --git a/manifest/oci_test.go b/manifest/oci_test.go index cc1e71250..94fcb6662 100644 --- a/manifest/oci_test.go +++ b/manifest/oci_test.go @@ -1,7 +1,7 @@ package manifest import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -74,7 +74,7 @@ func TestSupportedOCI1MediaType(t *testing.T) { } func TestOCI1FromManifest(t *testing.T) { - validManifest, err := ioutil.ReadFile(filepath.Join("fixtures", "ociv1.manifest.json")) + validManifest, err := os.ReadFile(filepath.Join("fixtures", "ociv1.manifest.json")) require.NoError(t, err) parser := func(m []byte) error { @@ -93,7 +93,7 @@ func TestOCI1FromManifest(t *testing.T) { } func TestUpdateLayerInfosOCIGzipToZstd(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/ociv1.manifest.json") + bytes, err := os.ReadFile("fixtures/ociv1.manifest.json") assert.Nil(t, err) manifest, err := OCI1FromManifest(bytes) @@ -127,7 +127,7 @@ func TestUpdateLayerInfosOCIGzipToZstd(t *testing.T) { updatedManifestBytes, err := manifest.Serialize() assert.Nil(t, err) - bytes, err = ioutil.ReadFile("fixtures/ociv1.zstd.manifest.json") + bytes, err = os.ReadFile("fixtures/ociv1.zstd.manifest.json") assert.Nil(t, err) expectedManifest, err := OCI1FromManifest(bytes) @@ -140,7 +140,7 @@ func TestUpdateLayerInfosOCIGzipToZstd(t *testing.T) { } func TestUpdateLayerInfosOCIZstdToGzip(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/ociv1.zstd.manifest.json") + bytes, err := os.ReadFile("fixtures/ociv1.zstd.manifest.json") assert.Nil(t, err) manifest, err := OCI1FromManifest(bytes) @@ -174,7 +174,7 @@ func TestUpdateLayerInfosOCIZstdToGzip(t *testing.T) { updatedManifestBytes, err := manifest.Serialize() assert.Nil(t, err) - bytes, err = ioutil.ReadFile("fixtures/ociv1.manifest.json") + bytes, err = os.ReadFile("fixtures/ociv1.manifest.json") assert.Nil(t, err) expectedManifest, err := OCI1FromManifest(bytes) @@ -187,7 +187,7 @@ func TestUpdateLayerInfosOCIZstdToGzip(t *testing.T) { } func TestUpdateLayerInfosOCIZstdToUncompressed(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/ociv1.zstd.manifest.json") + bytes, err := os.ReadFile("fixtures/ociv1.zstd.manifest.json") assert.Nil(t, err) manifest, err := OCI1FromManifest(bytes) @@ -218,7 +218,7 @@ func TestUpdateLayerInfosOCIZstdToUncompressed(t *testing.T) { updatedManifestBytes, err := manifest.Serialize() assert.Nil(t, err) - bytes, err = ioutil.ReadFile("fixtures/ociv1.uncompressed.manifest.json") + bytes, err = os.ReadFile("fixtures/ociv1.uncompressed.manifest.json") assert.Nil(t, err) expectedManifest, err := OCI1FromManifest(bytes) @@ -231,7 +231,7 @@ func TestUpdateLayerInfosOCIZstdToUncompressed(t *testing.T) { } func TestUpdateLayerInfosInvalidCompressionOperation(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/ociv1.zstd.manifest.json") + bytes, err := os.ReadFile("fixtures/ociv1.zstd.manifest.json") assert.Nil(t, err) manifest, err := OCI1FromManifest(bytes) @@ -264,7 +264,7 @@ func TestUpdateLayerInfosInvalidCompressionOperation(t *testing.T) { } func TestUpdateLayerInfosInvalidCompressionAlgorithm(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/ociv1.zstd.manifest.json") + bytes, err := os.ReadFile("fixtures/ociv1.zstd.manifest.json") assert.Nil(t, err) manifest, err := OCI1FromManifest(bytes) @@ -298,7 +298,7 @@ func TestUpdateLayerInfosInvalidCompressionAlgorithm(t *testing.T) { } func TestUpdateLayerInfosOCIGzipToUncompressed(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/ociv1.manifest.json") + bytes, err := os.ReadFile("fixtures/ociv1.manifest.json") assert.Nil(t, err) manifest, err := OCI1FromManifest(bytes) @@ -329,7 +329,7 @@ func TestUpdateLayerInfosOCIGzipToUncompressed(t *testing.T) { updatedManifestBytes, err := manifest.Serialize() assert.Nil(t, err) - bytes, err = ioutil.ReadFile("fixtures/ociv1.uncompressed.manifest.json") + bytes, err = os.ReadFile("fixtures/ociv1.uncompressed.manifest.json") assert.Nil(t, err) expectedManifest, err := OCI1FromManifest(bytes) @@ -342,7 +342,7 @@ func TestUpdateLayerInfosOCIGzipToUncompressed(t *testing.T) { } func TestUpdateLayerInfosOCINondistributableToGzip(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/ociv1.nondistributable.manifest.json") + bytes, err := os.ReadFile("fixtures/ociv1.nondistributable.manifest.json") assert.Nil(t, err) manifest, err := OCI1FromManifest(bytes) @@ -362,7 +362,7 @@ func TestUpdateLayerInfosOCINondistributableToGzip(t *testing.T) { updatedManifestBytes, err := manifest.Serialize() assert.Nil(t, err) - bytes, err = ioutil.ReadFile("fixtures/ociv1.nondistributable.gzip.manifest.json") + bytes, err = os.ReadFile("fixtures/ociv1.nondistributable.gzip.manifest.json") assert.Nil(t, err) expectedManifest, err := OCI1FromManifest(bytes) @@ -375,7 +375,7 @@ func TestUpdateLayerInfosOCINondistributableToGzip(t *testing.T) { } func TestUpdateLayerInfosOCINondistributableToZstd(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/ociv1.nondistributable.manifest.json") + bytes, err := os.ReadFile("fixtures/ociv1.nondistributable.manifest.json") assert.Nil(t, err) manifest, err := OCI1FromManifest(bytes) @@ -395,7 +395,7 @@ func TestUpdateLayerInfosOCINondistributableToZstd(t *testing.T) { updatedManifestBytes, err := manifest.Serialize() assert.Nil(t, err) - bytes, err = ioutil.ReadFile("fixtures/ociv1.nondistributable.zstd.manifest.json") + bytes, err = os.ReadFile("fixtures/ociv1.nondistributable.zstd.manifest.json") assert.Nil(t, err) expectedManifest, err := OCI1FromManifest(bytes) @@ -408,7 +408,7 @@ func TestUpdateLayerInfosOCINondistributableToZstd(t *testing.T) { } func TestUpdateLayerInfosOCINondistributableGzipToUncompressed(t *testing.T) { - bytes, err := ioutil.ReadFile("fixtures/ociv1.nondistributable.gzip.manifest.json") + bytes, err := os.ReadFile("fixtures/ociv1.nondistributable.gzip.manifest.json") assert.Nil(t, err) manifest, err := OCI1FromManifest(bytes) @@ -427,7 +427,7 @@ func TestUpdateLayerInfosOCINondistributableGzipToUncompressed(t *testing.T) { updatedManifestBytes, err := manifest.Serialize() assert.Nil(t, err) - bytes, err = ioutil.ReadFile("fixtures/ociv1.nondistributable.manifest.json") + bytes, err = os.ReadFile("fixtures/ociv1.nondistributable.manifest.json") assert.Nil(t, err) expectedManifest, err := OCI1FromManifest(bytes) diff --git a/oci/archive/oci_transport.go b/oci/archive/oci_transport.go index 54d325d34..4fa912765 100644 --- a/oci/archive/oci_transport.go +++ b/oci/archive/oci_transport.go @@ -3,7 +3,6 @@ package archive import ( "context" "fmt" - "io/ioutil" "os" "strings" @@ -161,7 +160,7 @@ func (t *tempDirOCIRef) deleteTempDir() error { // createOCIRef creates the oci reference of the image // If SystemContext.BigFilesTemporaryDir not "", overrides the temporary directory to use for storing big files func createOCIRef(sys *types.SystemContext, image string) (tempDirOCIRef, error) { - dir, err := ioutil.TempDir(tmpdir.TemporaryDirectoryForBigFiles(sys), "oci") + dir, err := os.MkdirTemp(tmpdir.TemporaryDirectoryForBigFiles(sys), "oci") if err != nil { return tempDirOCIRef{}, errors.Wrapf(err, "creating temp directory") } diff --git a/oci/archive/oci_transport_test.go b/oci/archive/oci_transport_test.go index 88e6c7ab8..2429d6114 100644 --- a/oci/archive/oci_transport_test.go +++ b/oci/archive/oci_transport_test.go @@ -2,7 +2,6 @@ package archive import ( "context" - "io/ioutil" "os" "path/filepath" "testing" @@ -131,7 +130,7 @@ func refToTempOCI(t *testing.T) (types.ImageReference, string) { ] } ` - err := ioutil.WriteFile(filepath.Join(tmpDir, "index.json"), []byte(m), 0644) + err := os.WriteFile(filepath.Join(tmpDir, "index.json"), []byte(m), 0644) require.NoError(t, err) ref, err := NewReference(tmpDir, "imageValue") require.NoError(t, err) @@ -160,9 +159,9 @@ func refToTempOCIArchive(t *testing.T) (ref types.ImageReference, tmpTarFile str ] } ` - err := ioutil.WriteFile(filepath.Join(tmpDir, "index.json"), []byte(m), 0644) + err := os.WriteFile(filepath.Join(tmpDir, "index.json"), []byte(m), 0644) require.NoError(t, err) - tarFile, err := ioutil.TempFile("", "oci-transport-test.tar") + tarFile, err := os.CreateTemp("", "oci-transport-test.tar") require.NoError(t, err) err = tarDirectory(tmpDir, tarFile.Name()) require.NoError(t, err) diff --git a/oci/layout/oci_dest.go b/oci/layout/oci_dest.go index c8156cc3a..77e8fd876 100644 --- a/oci/layout/oci_dest.go +++ b/oci/layout/oci_dest.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "io" - "io/ioutil" "os" "path/filepath" "runtime" @@ -124,7 +123,7 @@ func (d *ociImageDestination) HasThreadSafePutBlob() bool { // to any other readers for download using the supplied digest. // If stream.Read() at any time, ESPECIALLY at end of input, returns an error, PutBlob MUST 1) fail, and 2) delete any data stored so far. func (d *ociImageDestination) PutBlob(ctx context.Context, stream io.Reader, inputInfo types.BlobInfo, cache types.BlobInfoCache, isConfig bool) (types.BlobInfo, error) { - blobFile, err := ioutil.TempFile(d.ref.dir, "oci-put-blob") + blobFile, err := os.CreateTemp(d.ref.dir, "oci-put-blob") if err != nil { return types.BlobInfo{}, err } @@ -238,7 +237,7 @@ func (d *ociImageDestination) PutManifest(ctx context.Context, m []byte, instanc if err := ensureParentDirectoryExists(blobPath); err != nil { return err } - if err := ioutil.WriteFile(blobPath, m, 0644); err != nil { + if err := os.WriteFile(blobPath, m, 0644); err != nil { return err } @@ -309,14 +308,14 @@ func (d *ociImageDestination) PutSignatures(ctx context.Context, signatures [][] // - Uploaded data MAY be visible to others before Commit() is called // - Uploaded data MAY be removed or MAY remain around if Close() is called without Commit() (i.e. rollback is allowed but not guaranteed) func (d *ociImageDestination) Commit(context.Context, types.UnparsedImage) error { - if err := ioutil.WriteFile(d.ref.ociLayoutPath(), []byte(`{"imageLayoutVersion": "1.0.0"}`), 0644); err != nil { + if err := os.WriteFile(d.ref.ociLayoutPath(), []byte(`{"imageLayoutVersion": "1.0.0"}`), 0644); err != nil { return err } indexJSON, err := json.Marshal(d.index) if err != nil { return err } - return ioutil.WriteFile(d.ref.indexPath(), indexJSON, 0644) + return os.WriteFile(d.ref.indexPath(), indexJSON, 0644) } func ensureDirectoryExists(path string) error { diff --git a/oci/layout/oci_dest_test.go b/oci/layout/oci_dest_test.go index f9c3882f0..18dd27502 100644 --- a/oci/layout/oci_dest_test.go +++ b/oci/layout/oci_dest_test.go @@ -3,7 +3,7 @@ package layout import ( "bytes" "context" - "io/ioutil" + "io/fs" "os" "path/filepath" "testing" @@ -129,7 +129,7 @@ func TestPutTwoDifferentTags(t *testing.T) { } func putTestConfig(t *testing.T, ociRef ociReference, tmpDir string) { - data, err := ioutil.ReadFile("../../image/fixtures/oci1-config.json") + data, err := os.ReadFile("../../image/fixtures/oci1-config.json") assert.NoError(t, err) imageDest, err := newImageDestination(nil, ociRef) assert.NoError(t, err) @@ -143,7 +143,7 @@ func putTestConfig(t *testing.T, ociRef ociReference, tmpDir string) { assert.NoError(t, err) paths := []string{} - err = filepath.Walk(tmpDir, func(path string, info os.FileInfo, err error) error { + err = filepath.WalkDir(tmpDir, func(path string, _ fs.DirEntry, err error) error { paths = append(paths, path) return nil }) @@ -154,7 +154,7 @@ func putTestConfig(t *testing.T, ociRef ociReference, tmpDir string) { } func putTestManifest(t *testing.T, ociRef ociReference, tmpDir string) { - data, err := ioutil.ReadFile("../../image/fixtures/oci1.json") + data, err := os.ReadFile("../../image/fixtures/oci1.json") assert.NoError(t, err) imageDest, err := newImageDestination(nil, ociRef) assert.NoError(t, err) @@ -166,7 +166,7 @@ func putTestManifest(t *testing.T, ociRef ociReference, tmpDir string) { assert.NoError(t, err) paths := []string{} - err = filepath.Walk(tmpDir, func(path string, info os.FileInfo, err error) error { + err = filepath.WalkDir(tmpDir, func(path string, _ fs.DirEntry, err error) error { paths = append(paths, path) return nil }) diff --git a/oci/layout/oci_src.go b/oci/layout/oci_src.go index 9d8ab689b..8973f461c 100644 --- a/oci/layout/oci_src.go +++ b/oci/layout/oci_src.go @@ -3,7 +3,6 @@ package layout import ( "context" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -93,7 +92,7 @@ func (s *ociImageSource) GetManifest(ctx context.Context, instanceDigest *digest return nil, "", err } - m, err := ioutil.ReadFile(manifestPath) + m, err := os.ReadFile(manifestPath) if err != nil { return nil, "", err } diff --git a/oci/layout/oci_src_test.go b/oci/layout/oci_src_test.go index ead0ca25a..025d1555d 100644 --- a/oci/layout/oci_src_test.go +++ b/oci/layout/oci_src_test.go @@ -5,7 +5,7 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "os" @@ -57,7 +57,7 @@ func TestGetBlobForRemoteLayers(t *testing.T) { require.NoError(t, err) defer reader.Close() - data, err := ioutil.ReadAll(reader) + data, err := io.ReadAll(reader) require.NoError(t, err) assert.Contains(t, string(data), "Hello world") } @@ -73,7 +73,7 @@ func TestGetBlobForRemoteLayersWithTLS(t *testing.T) { }, cache) require.NoError(t, err) - layerContent, _ := ioutil.ReadAll(layer) + layerContent, _ := io.ReadAll(layer) assert.Equal(t, RemoteLayerContent, string(layerContent)) assert.Equal(t, int64(len(RemoteLayerContent)), size) } @@ -97,7 +97,7 @@ func remoteLayerContent(w http.ResponseWriter, req *http.Request) { } func startRemoteLayerServer() (*httptest.Server, error) { - certBytes, err := ioutil.ReadFile("fixtures/accepted_certs/cert.cert") + certBytes, err := os.ReadFile("fixtures/accepted_certs/cert.cert") if err != nil { return nil, err } diff --git a/oci/layout/oci_transport_test.go b/oci/layout/oci_transport_test.go index cf2584270..d4fd02163 100644 --- a/oci/layout/oci_transport_test.go +++ b/oci/layout/oci_transport_test.go @@ -2,7 +2,6 @@ package layout import ( "context" - "io/ioutil" "os" "path/filepath" "testing" @@ -143,7 +142,7 @@ func refToTempOCI(t *testing.T) (types.ImageReference, string) { ] } ` - err := ioutil.WriteFile(filepath.Join(tmpDir, "index.json"), []byte(m), 0644) + err := os.WriteFile(filepath.Join(tmpDir, "index.json"), []byte(m), 0644) require.NoError(t, err) ref, err := NewReference(tmpDir, "imageValue") require.NoError(t, err) diff --git a/openshift/openshift-copies.go b/openshift/openshift-copies.go index 4ffbced6b..a6473ae68 100644 --- a/openshift/openshift-copies.go +++ b/openshift/openshift-copies.go @@ -5,7 +5,6 @@ import ( "crypto/x509" "encoding/json" "fmt" - "io/ioutil" "net" "net/http" "net/url" @@ -625,7 +624,7 @@ func (rules *clientConfigLoadingRules) Load() (*clientcmdConfig, error) { // loadFromFile is a modified copy of k8s.io/kubernetes/pkg/client/unversioned/clientcmd.LoadFromFile // LoadFromFile takes a filename and deserializes the contents into Config object func loadFromFile(filename string) (*clientcmdConfig, error) { - kubeconfigBytes, err := ioutil.ReadFile(filename) + kubeconfigBytes, err := os.ReadFile(filename) if err != nil { return nil, err } @@ -1013,7 +1012,7 @@ func dataFromSliceOrFile(data []byte, file string) ([]byte, error) { return data, nil } if len(file) > 0 { - fileData, err := ioutil.ReadFile(file) + fileData, err := os.ReadFile(file) if err != nil { return []byte{}, err } diff --git a/ostree/ostree_dest.go b/ostree/ostree_dest.go index 3eb2a2cba..011118fa5 100644 --- a/ostree/ostree_dest.go +++ b/ostree/ostree_dest.go @@ -10,7 +10,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -148,7 +147,7 @@ func (d *ostreeImageDestination) HasThreadSafePutBlob() bool { // to any other readers for download using the supplied digest. // If stream.Read() at any time, ESPECIALLY at end of input, returns an error, PutBlob MUST 1) fail, and 2) delete any data stored so far. func (d *ostreeImageDestination) PutBlob(ctx context.Context, stream io.Reader, inputInfo types.BlobInfo, cache types.BlobInfoCache, isConfig bool) (types.BlobInfo, error) { - tmpDir, err := ioutil.TempDir(d.tmpDirPath, "blob") + tmpDir, err := os.MkdirTemp(d.tmpDirPath, "blob") if err != nil { return types.BlobInfo{}, err } @@ -180,20 +179,24 @@ func (d *ostreeImageDestination) PutBlob(ctx context.Context, stream io.Reader, } func fixFiles(selinuxHnd *C.struct_selabel_handle, root string, dir string, usermode bool) error { - entries, err := ioutil.ReadDir(dir) + entries, err := os.ReadDir(dir) if err != nil { return err } - for _, info := range entries { - fullpath := filepath.Join(dir, info.Name()) - if info.Mode()&(os.ModeNamedPipe|os.ModeSocket|os.ModeDevice) != 0 { + for _, entry := range entries { + fullpath := filepath.Join(dir, entry.Name()) + if entry.Type()&(os.ModeNamedPipe|os.ModeSocket|os.ModeDevice) != 0 { if err := os.Remove(fullpath); err != nil { return err } continue } + info, err := entry.Info() + if err != nil { + return err + } if selinuxHnd != nil { relPath, err := filepath.Rel(root, fullpath) if err != nil { @@ -223,7 +226,7 @@ func fixFiles(selinuxHnd *C.struct_selabel_handle, root string, dir string, user } } - if info.IsDir() { + if entry.IsDir() { if usermode { if err := os.Chmod(fullpath, info.Mode()|0700); err != nil { return err @@ -233,7 +236,7 @@ func fixFiles(selinuxHnd *C.struct_selabel_handle, root string, dir string, user if err != nil { return err } - } else if usermode && (info.Mode().IsRegular()) { + } else if usermode && (entry.Type().IsRegular()) { if err := os.Chmod(fullpath, info.Mode()|0600); err != nil { return err } @@ -405,7 +408,7 @@ func (d *ostreeImageDestination) PutManifest(ctx context.Context, manifestBlob [ } d.digest = digest - return ioutil.WriteFile(manifestPath, manifestBlob, 0644) + return os.WriteFile(manifestPath, manifestBlob, 0644) } // PutSignatures writes signatures to the destination. @@ -423,7 +426,7 @@ func (d *ostreeImageDestination) PutSignatures(ctx context.Context, signatures [ for i, sig := range signatures { signaturePath := filepath.Join(d.tmpDirPath, d.ref.signaturePath(i)) - if err := ioutil.WriteFile(signaturePath, sig, 0644); err != nil { + if err := os.WriteFile(signaturePath, sig, 0644); err != nil { return err } } diff --git a/ostree/ostree_src.go b/ostree/ostree_src.go index d30c764a6..1e1f2be03 100644 --- a/ostree/ostree_src.go +++ b/ostree/ostree_src.go @@ -9,7 +9,6 @@ import ( "encoding/base64" "fmt" "io" - "io/ioutil" "strconv" "strings" "unsafe" @@ -369,7 +368,7 @@ func (s *ostreeImageSource) GetSignatures(ctx context.Context, instanceDigest *d } defer sigReader.Close() - sig, err := ioutil.ReadAll(sigReader) + sig, err := os.ReadAll(sigReader) if err != nil { return nil, err } diff --git a/ostree/ostree_transport_test.go b/ostree/ostree_transport_test.go index da2f8031b..dbe769c01 100644 --- a/ostree/ostree_transport_test.go +++ b/ostree/ostree_transport_test.go @@ -6,7 +6,6 @@ package ostree import ( "context" "fmt" - "io/ioutil" "os" "path/filepath" "strings" diff --git a/pkg/blobcache/blobcache.go b/pkg/blobcache/blobcache.go index b67a83f33..8b22733ac 100644 --- a/pkg/blobcache/blobcache.go +++ b/pkg/blobcache/blobcache.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "io" - "io/ioutil" "os" "path/filepath" "sync" @@ -196,7 +195,7 @@ func (s *blobCacheSource) Close() error { func (s *blobCacheSource) GetManifest(ctx context.Context, instanceDigest *digest.Digest) ([]byte, string, error) { if instanceDigest != nil { filename := filepath.Join(s.reference.directory, makeFilename(*instanceDigest, false)) - manifestBytes, err := ioutil.ReadFile(filename) + manifestBytes, err := os.ReadFile(filename) if err == nil { s.cacheHits++ return manifestBytes, manifest.GuessMIMEType(manifestBytes), nil @@ -280,10 +279,10 @@ func (s *blobCacheSource) LayerInfosForCopy(ctx context.Context, instanceDigest switch s.reference.compress { case types.Compress: alternate = blobFile + compressedNote - replaceDigest, err = ioutil.ReadFile(alternate) + replaceDigest, err = os.ReadFile(alternate) case types.Decompress: alternate = blobFile + decompressedNote - replaceDigest, err = ioutil.ReadFile(alternate) + replaceDigest, err = os.ReadFile(alternate) } if err == nil && digest.Digest(replaceDigest).Validate() == nil { alternate = filepath.Join(filepath.Dir(alternate), makeFilename(digest.Digest(replaceDigest), false)) @@ -373,7 +372,7 @@ func saveStream(wg *sync.WaitGroup, decompressReader io.ReadCloser, tempFile *os _, err3 = io.Copy(io.MultiWriter(tempFile, digester.Hash()), decompressed) } else { // Drain the pipe to keep from stalling the PutBlob() thread. - if _, err := io.Copy(ioutil.Discard, decompressReader); err != nil { + if _, err := io.Copy(io.Discard, decompressReader); err != nil { logrus.Debugf("error draining the pipe: %v", err) } } @@ -423,7 +422,7 @@ func (d *blobCacheDestination) PutBlob(ctx context.Context, stream io.Reader, in compression := archive.Uncompressed if inputInfo.Digest != "" { filename := filepath.Join(d.reference.directory, makeFilename(inputInfo.Digest, isConfig)) - tempfile, err = ioutil.TempFile(d.reference.directory, makeFilename(inputInfo.Digest, isConfig)) + tempfile, err = os.CreateTemp(d.reference.directory, makeFilename(inputInfo.Digest, isConfig)) if err == nil { stream = io.TeeReader(stream, tempfile) defer func() { @@ -457,7 +456,7 @@ func (d *blobCacheDestination) PutBlob(ctx context.Context, stream io.Reader, in if compression == archive.Gzip { // The stream is compressed, so create a file which we'll // use to store a decompressed copy. - decompressedTemp, err2 := ioutil.TempFile(d.reference.directory, makeFilename(inputInfo.Digest, isConfig)) + decompressedTemp, err2 := os.CreateTemp(d.reference.directory, makeFilename(inputInfo.Digest, isConfig)) if err2 != nil { logrus.Debugf("error while creating a temporary file under %q to hold decompressed blob %q: %v", d.reference.directory, inputInfo.Digest.String(), err2) decompressedTemp.Close() diff --git a/pkg/blobcache/blobcache_test.go b/pkg/blobcache/blobcache_test.go index b9fad2606..da83d361f 100644 --- a/pkg/blobcache/blobcache_test.go +++ b/pkg/blobcache/blobcache_test.go @@ -7,7 +7,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -176,7 +175,7 @@ func TestBlobCache(t *testing.T) { for _, cachedName := range cachedNames { if digest.Digest(cachedName).Validate() == nil { cacheMember := filepath.Join(cacheDir, cachedName) - cacheMemberBytes, err := ioutil.ReadFile(cacheMember) + cacheMemberBytes, err := os.ReadFile(cacheMember) if err != nil { t.Fatalf("error reading cache member %q: %v", cacheMember, err) } diff --git a/pkg/compression/compression.go b/pkg/compression/compression.go index c28e81792..34c90dd77 100644 --- a/pkg/compression/compression.go +++ b/pkg/compression/compression.go @@ -5,7 +5,6 @@ import ( "compress/bzip2" "fmt" "io" - "io/ioutil" "github.com/containers/image/v5/pkg/compression/internal" "github.com/containers/image/v5/pkg/compression/types" @@ -65,7 +64,7 @@ func GzipDecompressor(r io.Reader) (io.ReadCloser, error) { // Bzip2Decompressor is a DecompressorFunc for the bzip2 compression algorithm. func Bzip2Decompressor(r io.Reader) (io.ReadCloser, error) { - return ioutil.NopCloser(bzip2.NewReader(r)), nil + return io.NopCloser(bzip2.NewReader(r)), nil } // XzDecompressor is a DecompressorFunc for the xz compression algorithm. @@ -74,7 +73,7 @@ func XzDecompressor(r io.Reader) (io.ReadCloser, error) { if err != nil { return nil, err } - return ioutil.NopCloser(r), nil + return io.NopCloser(r), nil } // gzipCompressor is a CompressorFunc for the gzip compression algorithm. @@ -161,7 +160,7 @@ func AutoDecompress(stream io.Reader) (io.ReadCloser, bool, error) { return nil, false, errors.Wrapf(err, "initializing decompression") } } else { - res = ioutil.NopCloser(stream) + res = io.NopCloser(stream) } return res, decompressor != nil, nil } diff --git a/pkg/compression/compression_test.go b/pkg/compression/compression_test.go index 13c668ecb..fb7537350 100644 --- a/pkg/compression/compression_test.go +++ b/pkg/compression/compression_test.go @@ -3,7 +3,6 @@ package compression import ( "bytes" "io" - "io/ioutil" "os" "testing" @@ -24,7 +23,7 @@ func TestDetectCompression(t *testing.T) { // The original stream is preserved. for _, c := range cases { - originalContents, err := ioutil.ReadFile(c) + originalContents, err := os.ReadFile(c) require.NoError(t, err, c) stream, err := os.Open(c) @@ -34,7 +33,7 @@ func TestDetectCompression(t *testing.T) { _, updatedStream, err := DetectCompression(stream) require.NoError(t, err, c) - updatedContents, err := ioutil.ReadAll(updatedStream) + updatedContents, err := io.ReadAll(updatedStream) require.NoError(t, err, c) assert.Equal(t, originalContents, updatedContents, c) } @@ -58,7 +57,7 @@ func TestDetectCompression(t *testing.T) { uncompressedStream = s } - uncompressedContents, err := ioutil.ReadAll(uncompressedStream) + uncompressedContents, err := io.ReadAll(uncompressedStream) require.NoError(t, err, c) assert.Equal(t, []byte("Hello"), uncompressedContents, c) } @@ -67,7 +66,7 @@ func TestDetectCompression(t *testing.T) { decompressor, updatedStream, err := DetectCompression(bytes.NewReader([]byte{})) require.NoError(t, err) assert.Nil(t, decompressor) - updatedContents, err := ioutil.ReadAll(updatedStream) + updatedContents, err := io.ReadAll(updatedStream) require.NoError(t, err) assert.Equal(t, []byte{}, updatedContents) @@ -103,7 +102,7 @@ func TestAutoDecompress(t *testing.T) { assert.Equal(t, c.isCompressed, isCompressed) - uncompressedContents, err := ioutil.ReadAll(uncompressedStream) + uncompressedContents, err := io.ReadAll(uncompressedStream) require.NoError(t, err, c.filename) assert.Equal(t, []byte("Hello"), uncompressedContents, c.filename) } @@ -112,7 +111,7 @@ func TestAutoDecompress(t *testing.T) { uncompressedStream, isCompressed, err := AutoDecompress(bytes.NewReader([]byte{})) require.NoError(t, err) assert.False(t, isCompressed) - uncompressedContents, err := ioutil.ReadAll(uncompressedStream) + uncompressedContents, err := io.ReadAll(uncompressedStream) require.NoError(t, err) assert.Equal(t, []byte{}, uncompressedContents) diff --git a/pkg/docker/config/config.go b/pkg/docker/config/config.go index 52734bead..d0bdd08e9 100644 --- a/pkg/docker/config/config.go +++ b/pkg/docker/config/config.go @@ -4,7 +4,6 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -544,7 +543,7 @@ func getPathToAuthWithOS(sys *types.SystemContext, goOS string) (string, bool, e func readJSONFile(path string, legacyFormat bool) (dockerConfigFile, error) { var auths dockerConfigFile - raw, err := ioutil.ReadFile(path) + raw, err := os.ReadFile(path) if err != nil { if os.IsNotExist(err) { auths.AuthConfigs = map[string]dockerAuthConfig{} diff --git a/pkg/docker/config/config_test.go b/pkg/docker/config/config_test.go index 0f5e1ea4f..5287454bb 100644 --- a/pkg/docker/config/config_test.go +++ b/pkg/docker/config/config_test.go @@ -3,7 +3,6 @@ package config import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -282,12 +281,12 @@ func TestGetAuth(t *testing.T) { } if tc.path != "" { - contents, err := ioutil.ReadFile(tc.path) + contents, err := os.ReadFile(tc.path) if err != nil { t.Fatal(err) } - if err := ioutil.WriteFile(configPath, contents, 0640); err != nil { + if err := os.WriteFile(configPath, contents, 0640); err != nil { t.Fatal(err) } } @@ -322,7 +321,7 @@ func TestGetAuthFromLegacyFile(t *testing.T) { t.Logf("using temporary home directory: %q", tmpDir) configPath := filepath.Join(tmpDir, ".dockercfg") - contents, err := ioutil.ReadFile(filepath.Join("testdata", "legacy.json")) + contents, err := os.ReadFile(filepath.Join("testdata", "legacy.json")) if err != nil { t.Fatal(err) } @@ -350,7 +349,7 @@ func TestGetAuthFromLegacyFile(t *testing.T) { }, } { t.Run(tc.name, func(t *testing.T) { - if err := ioutil.WriteFile(configPath, contents, 0640); err != nil { + if err := os.WriteFile(configPath, contents, 0640); err != nil { t.Fatal(err) } @@ -389,12 +388,12 @@ func TestGetAuthPreferNewConfig(t *testing.T) { target: filepath.Join(tmpDir, ".dockercfg"), }, } { - contents, err := ioutil.ReadFile(data.source) + contents, err := os.ReadFile(data.source) if err != nil { t.Fatal(err) } - if err := ioutil.WriteFile(data.target, contents, 0640); err != nil { + if err := os.WriteFile(data.target, contents, 0640); err != nil { t.Fatal(err) } } @@ -432,7 +431,7 @@ func TestGetAuthFailsOnBadInput(t *testing.T) { } assert.Equal(t, types.DockerAuthConfig{}, auth) - if err := ioutil.WriteFile(configPath, []byte("Json rocks! Unless it doesn't."), 0640); err != nil { + if err := os.WriteFile(configPath, []byte("Json rocks! Unless it doesn't."), 0640); err != nil { t.Fatalf("failed to write file %q: %v", configPath, err) } _, err = getCredentialsWithHomeDir(nil, "index.docker.io", tmpHomeDir) @@ -448,7 +447,7 @@ func TestGetAuthFailsOnBadInput(t *testing.T) { assert.Equal(t, types.DockerAuthConfig{}, auth) configPath = filepath.Join(tmpHomeDir, ".dockercfg") - if err := ioutil.WriteFile(configPath, []byte("I'm certainly not a json string."), 0640); err != nil { + if err := os.WriteFile(configPath, []byte("I'm certainly not a json string."), 0640); err != nil { t.Fatalf("failed to write file %q: %v", configPath, err) } _, err = getCredentialsWithHomeDir(nil, "index.docker.io", tmpHomeDir) @@ -457,7 +456,7 @@ func TestGetAuthFailsOnBadInput(t *testing.T) { func TestGetAllCredentials(t *testing.T) { // Create a temporary authentication file. - tmpFile, err := ioutil.TempFile("", "auth.json.") + tmpFile, err := os.CreateTemp("", "auth.json.") require.NoError(t, err) authFilePath := tmpFile.Name() defer tmpFile.Close() @@ -541,7 +540,7 @@ func TestGetAllCredentials(t *testing.T) { }, } { // Write the credentials to the authfile. - err := ioutil.WriteFile(authFilePath, []byte{'{', '}'}, 0700) + err := os.WriteFile(authFilePath, []byte{'{', '}'}, 0700) require.NoError(t, err) for _, d := range data { @@ -650,7 +649,7 @@ func TestSetCredentials(t *testing.T) { "docker.io/library", }, } { - tmpFile, err := ioutil.TempFile("", "auth.json.set") + tmpFile, err := os.CreateTemp("", "auth.json.set") require.NoError(t, err) defer os.RemoveAll(tmpFile.Name()) @@ -773,7 +772,7 @@ func TestRemoveAuthentication(t *testing.T) { content, err := json.Marshal(&tc.config) require.NoError(t, err) - tmpFile, err := ioutil.TempFile("", "auth.json") + tmpFile, err := os.CreateTemp("", "auth.json") require.NoError(t, err) defer os.RemoveAll(tmpFile.Name()) @@ -877,7 +876,7 @@ func TestSetGetCredentials(t *testing.T) { } { // Create a new empty SystemContext referring an empty auth.json - tmpFile, err := ioutil.TempFile("", "auth.json-") + tmpFile, err := os.CreateTemp("", "auth.json-") require.NoError(t, err) defer os.RemoveAll(tmpFile.Name()) diff --git a/pkg/shortnames/shortnames_test.go b/pkg/shortnames/shortnames_test.go index 254fb2020..78a9fbfa6 100644 --- a/pkg/shortnames/shortnames_test.go +++ b/pkg/shortnames/shortnames_test.go @@ -1,7 +1,6 @@ package shortnames import ( - "io/ioutil" "os" "testing" @@ -95,7 +94,7 @@ func TestSplitUserInput(t *testing.T) { } func TestResolve(t *testing.T) { - tmp, err := ioutil.TempFile("", "aliases.conf") + tmp, err := os.CreateTemp("", "aliases.conf") require.NoError(t, err) defer os.Remove(tmp.Name()) @@ -261,7 +260,7 @@ func removeAlias(t *testing.T, sys *types.SystemContext, name string, mustFail b } func TestResolveWithDropInConfigs(t *testing.T) { - tmp, err := ioutil.TempFile("", "aliases.conf") + tmp, err := os.CreateTemp("", "aliases.conf") require.NoError(t, err) defer os.Remove(tmp.Name()) @@ -394,7 +393,7 @@ func TestResolveWithDropInConfigs(t *testing.T) { } func TestResolveWithVaryingShortNameModes(t *testing.T) { - tmp, err := ioutil.TempFile("", "aliases.conf") + tmp, err := os.CreateTemp("", "aliases.conf") require.NoError(t, err) defer os.Remove(tmp.Name()) @@ -459,7 +458,7 @@ func TestResolveWithVaryingShortNameModes(t *testing.T) { } func TestResolveAndRecord(t *testing.T) { - tmp, err := ioutil.TempFile("", "aliases.conf") + tmp, err := os.CreateTemp("", "aliases.conf") require.NoError(t, err) defer os.Remove(tmp.Name()) @@ -522,7 +521,7 @@ func TestResolveAndRecord(t *testing.T) { } func TestResolveLocally(t *testing.T) { - tmp, err := ioutil.TempFile("", "aliases.conf") + tmp, err := os.CreateTemp("", "aliases.conf") require.NoError(t, err) defer os.Remove(tmp.Name()) diff --git a/pkg/sysregistriesv2/shortnames_test.go b/pkg/sysregistriesv2/shortnames_test.go index 8b8417a28..7f295444a 100644 --- a/pkg/sysregistriesv2/shortnames_test.go +++ b/pkg/sysregistriesv2/shortnames_test.go @@ -1,7 +1,6 @@ package sysregistriesv2 import ( - "io/ioutil" "os" "testing" @@ -107,7 +106,7 @@ func TestValidateShortName(t *testing.T) { } func TestResolveShortNameAlias(t *testing.T) { - tmp, err := ioutil.TempFile("", "aliases.conf") + tmp, err := os.CreateTemp("", "aliases.conf") require.NoError(t, err) defer os.Remove(tmp.Name()) @@ -162,7 +161,7 @@ func TestResolveShortNameAlias(t *testing.T) { } func TestAliasesWithDropInConfigs(t *testing.T) { - tmp, err := ioutil.TempFile("", "aliases.conf") + tmp, err := os.CreateTemp("", "aliases.conf") require.NoError(t, err) defer os.Remove(tmp.Name()) @@ -274,7 +273,7 @@ func TestAliasesWithDropInConfigs(t *testing.T) { } func TestInvalidAliases(t *testing.T) { - tmp, err := ioutil.TempFile("", "aliases.conf") + tmp, err := os.CreateTemp("", "aliases.conf") require.NoError(t, err) defer os.Remove(tmp.Name()) diff --git a/pkg/sysregistriesv2/system_registries_v2.go b/pkg/sysregistriesv2/system_registries_v2.go index c5df241b7..c1753c845 100644 --- a/pkg/sysregistriesv2/system_registries_v2.go +++ b/pkg/sysregistriesv2/system_registries_v2.go @@ -2,6 +2,7 @@ package sysregistriesv2 import ( "fmt" + "io/fs" "os" "path/filepath" "reflect" @@ -643,17 +644,17 @@ func dropInConfigs(wrapper configWrapper) ([]string, error) { dirPaths = append(dirPaths, wrapper.userConfigDirPath) } for _, dirPath := range dirPaths { - err := filepath.Walk(dirPath, + err := filepath.WalkDir(dirPath, // WalkFunc to read additional configs - func(path string, info os.FileInfo, err error) error { + func(path string, d fs.DirEntry, err error) error { switch { case err != nil: // return error (could be a permission problem) return err - case info == nil: + case d == nil: // this should only happen when err != nil but let's be sure return nil - case info.IsDir(): + case d.IsDir(): if path != dirPath { // make sure to not recurse into sub-directories return filepath.SkipDir diff --git a/pkg/sysregistriesv2/system_registries_v2_test.go b/pkg/sysregistriesv2/system_registries_v2_test.go index 11d249dee..831a84b8f 100644 --- a/pkg/sysregistriesv2/system_registries_v2_test.go +++ b/pkg/sysregistriesv2/system_registries_v2_test.go @@ -2,7 +2,6 @@ package sysregistriesv2 import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -484,12 +483,12 @@ func TestMixingV1andV2(t *testing.T) { } func TestConfigCache(t *testing.T) { - configFile, err := ioutil.TempFile("", "sysregistriesv2-test") + configFile, err := os.CreateTemp("", "sysregistriesv2-test") require.NoError(t, err) defer os.Remove(configFile.Name()) defer configFile.Close() - err = ioutil.WriteFile(configFile.Name(), []byte(` + err = os.WriteFile(configFile.Name(), []byte(` [[registry]] location = "registry.com" @@ -524,7 +523,7 @@ insecure = true`), 0600) // empty the config, but use the same SystemContext to show that the // previously specified registries are in the cache - err = ioutil.WriteFile(configFile.Name(), []byte{}, 0600) + err = os.WriteFile(configFile.Name(), []byte{}, 0600) require.NoError(t, err) registries, err = GetRegistries(ctx) assert.Nil(t, err) diff --git a/pkg/tlsclientconfig/tlsclientconfig.go b/pkg/tlsclientconfig/tlsclientconfig.go index 7e2142b1f..c766417d0 100644 --- a/pkg/tlsclientconfig/tlsclientconfig.go +++ b/pkg/tlsclientconfig/tlsclientconfig.go @@ -2,7 +2,6 @@ package tlsclientconfig import ( "crypto/tls" - "io/ioutil" "net" "net/http" "os" @@ -19,7 +18,7 @@ import ( // SetupCertificates opens all .crt, .cert, and .key files in dir and appends / loads certs and key pairs as appropriate to tlsc func SetupCertificates(dir string, tlsc *tls.Config) error { logrus.Debugf("Looking for TLS certificates and private keys in %s", dir) - fs, err := ioutil.ReadDir(dir) + fs, err := os.ReadDir(dir) if err != nil { if os.IsNotExist(err) { return nil @@ -35,7 +34,7 @@ func SetupCertificates(dir string, tlsc *tls.Config) error { fullPath := filepath.Join(dir, f.Name()) if strings.HasSuffix(f.Name(), ".crt") { logrus.Debugf(" crt: %s", fullPath) - data, err := ioutil.ReadFile(fullPath) + data, err := os.ReadFile(fullPath) if err != nil { if os.IsNotExist(err) { // Dangling symbolic link? @@ -81,7 +80,7 @@ func SetupCertificates(dir string, tlsc *tls.Config) error { return nil } -func hasFile(files []os.FileInfo, name string) bool { +func hasFile(files []os.DirEntry, name string) bool { for _, f := range files { if f.Name() == name { return true diff --git a/sif/load.go b/sif/load.go index ba6d875ba..70758ad43 100644 --- a/sif/load.go +++ b/sif/load.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -103,7 +102,7 @@ func writeInjectedScript(extractedRootPath string, injectedScript []byte) error if err := os.MkdirAll(parentDirPath, 0755); err != nil { return fmt.Errorf("creating %s: %w", parentDirPath, err) } - if err := ioutil.WriteFile(filePath, injectedScript, 0755); err != nil { + if err := os.WriteFile(filePath, injectedScript, 0755); err != nil { return fmt.Errorf("writing %s to %s: %w", injectedScriptTargetPath, filePath, err) } return nil @@ -121,7 +120,7 @@ func createTarFromSIFInputs(ctx context.Context, tarPath, squashFSPath string, i conversionCommand := fmt.Sprintf("unsquashfs -d %s -f %s && tar --acls --xattrs -C %s -cpf %s ./", extractedRootPath, squashFSPath, extractedRootPath, tarPath) script := "#!/bin/sh\n" + conversionCommand + "\n" - if err := ioutil.WriteFile(scriptPath, []byte(script), 0755); err != nil { + if err := os.WriteFile(scriptPath, []byte(script), 0755); err != nil { return err } defer os.Remove(scriptPath) @@ -149,7 +148,7 @@ func createTarFromSIFInputs(ctx context.Context, tarPath, squashFSPath string, i // at start, and is exclusively used by the current process (i.e. it is safe // to use hard-coded relative paths within it). func convertSIFToElements(ctx context.Context, sifImage *sif.FileImage, tempDir string) (string, []string, error) { - // We could allocate unique names for all of these using ioutil.Temp*, but tempDir is exclusive, + // We could allocate unique names for all of these using os.{CreateTemp,MkdirTemp}, but tempDir is exclusive, // so we can just hard-code a set of unique values here. // We create and/or manage cleanup of these two paths. squashFSPath := filepath.Join(tempDir, "rootfs.squashfs") diff --git a/sif/src.go b/sif/src.go index ba95a469f..ccf125966 100644 --- a/sif/src.go +++ b/sif/src.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "github.com/containers/image/v5/internal/tmpdir" @@ -65,7 +64,7 @@ func newImageSource(ctx context.Context, sys *types.SystemContext, ref sifRefere _ = sifImg.UnloadContainer() }() - workDir, err := ioutil.TempDir(tmpdir.TemporaryDirectoryForBigFiles(sys), "sif") + workDir, err := os.MkdirTemp(tmpdir.TemporaryDirectoryForBigFiles(sys), "sif") if err != nil { return nil, fmt.Errorf("creating temp directory: %w", err) } @@ -170,7 +169,7 @@ func (s *sifImageSource) HasThreadSafeGetBlob() bool { func (s *sifImageSource) GetBlob(ctx context.Context, info types.BlobInfo, cache types.BlobInfoCache) (io.ReadCloser, int64, error) { switch info.Digest { case s.configDigest: - return ioutil.NopCloser(bytes.NewBuffer(s.config)), int64(len(s.config)), nil + return io.NopCloser(bytes.NewBuffer(s.config)), int64(len(s.config)), nil case s.layerDigest: reader, err := os.Open(s.layerFile) if err != nil { diff --git a/sif/transport_test.go b/sif/transport_test.go index c68dd045f..b7220934c 100644 --- a/sif/transport_test.go +++ b/sif/transport_test.go @@ -2,7 +2,6 @@ package sif import ( "context" - "io/ioutil" "os" "path/filepath" "testing" @@ -51,7 +50,7 @@ func TestNewReference(t *testing.T) { func testNewReference(t *testing.T, fn func(string) (types.ImageReference, error)) { tmpDir := t.TempDir() tmpFile := filepath.Join(tmpDir, "image.sif") - err := ioutil.WriteFile(tmpFile, nil, 0600) + err := os.WriteFile(tmpFile, nil, 0600) require.NoError(t, err) for _, file := range []string{ @@ -75,7 +74,7 @@ func testNewReference(t *testing.T, fn func(string) (types.ImageReference, error // The caller should // defer os.Remove(tmpFile) func refToTempFile(t *testing.T) (ref types.ImageReference, tmpDir string) { - f, err := ioutil.TempFile("", "sif-transport-test") + f, err := os.CreateTemp("", "sif-transport-test") require.NoError(t, err) tmpFile := f.Name() err = f.Close() diff --git a/signature/docker_test.go b/signature/docker_test.go index f8e0b6828..ba11bd1d5 100644 --- a/signature/docker_test.go +++ b/signature/docker_test.go @@ -1,7 +1,6 @@ package signature import ( - "io/ioutil" "os" "os/exec" "testing" @@ -27,7 +26,7 @@ func TestSignDockerManifest(t *testing.T) { t.Skipf("Signing not supported: %v", err) } - manifest, err := ioutil.ReadFile("fixtures/image.manifest.json") + manifest, err := os.ReadFile("fixtures/image.manifest.json") require.NoError(t, err) // Successful signing @@ -40,7 +39,7 @@ func TestSignDockerManifest(t *testing.T) { assert.Equal(t, TestImageManifestDigest, verified.DockerManifestDigest) // Error computing Docker manifest - invalidManifest, err := ioutil.ReadFile("fixtures/v2s1-invalid-signatures.manifest.json") + invalidManifest, err := os.ReadFile("fixtures/v2s1-invalid-signatures.manifest.json") require.NoError(t, err) _, err = SignDockerManifest(invalidManifest, TestImageSignatureReference, mech, TestKeyFingerprint) assert.Error(t, err) @@ -65,7 +64,7 @@ func TestSignDockerManifestWithPassphrase(t *testing.T) { t.Skipf("Signing not supported: %v", err) } - manifest, err := ioutil.ReadFile("fixtures/image.manifest.json") + manifest, err := os.ReadFile("fixtures/image.manifest.json") require.NoError(t, err) // Invalid passphrase @@ -90,7 +89,7 @@ func TestSignDockerManifestWithPassphrase(t *testing.T) { assert.Equal(t, TestImageManifestDigest, verified.DockerManifestDigest) // Error computing Docker manifest - invalidManifest, err := ioutil.ReadFile("fixtures/v2s1-invalid-signatures.manifest.json") + invalidManifest, err := os.ReadFile("fixtures/v2s1-invalid-signatures.manifest.json") require.NoError(t, err) _, err = SignDockerManifest(invalidManifest, TestImageSignatureReference, mech, TestKeyFingerprintWithPassphrase) assert.Error(t, err) @@ -108,9 +107,9 @@ func TestVerifyDockerManifestSignature(t *testing.T) { mech, err := newGPGSigningMechanismInDirectory(testGPGHomeDirectory) require.NoError(t, err) defer mech.Close() - manifest, err := ioutil.ReadFile("fixtures/image.manifest.json") + manifest, err := os.ReadFile("fixtures/image.manifest.json") require.NoError(t, err) - signature, err := ioutil.ReadFile("fixtures/image.signature") + signature, err := os.ReadFile("fixtures/image.signature") require.NoError(t, err) // Successful verification @@ -133,14 +132,14 @@ func TestVerifyDockerManifestSignature(t *testing.T) { assert.Nil(t, sig) // Error computing Docker manifest - invalidManifest, err := ioutil.ReadFile("fixtures/v2s1-invalid-signatures.manifest.json") + invalidManifest, err := os.ReadFile("fixtures/v2s1-invalid-signatures.manifest.json") require.NoError(t, err) sig, err = VerifyDockerManifestSignature(signature, invalidManifest, TestImageSignatureReference, mech, TestKeyFingerprint) assert.Error(t, err) assert.Nil(t, sig) // Error verifying signature - corruptSignature, err := ioutil.ReadFile("fixtures/corrupt.signature") + corruptSignature, err := os.ReadFile("fixtures/corrupt.signature") require.NoError(t, err) sig, err = VerifyDockerManifestSignature(corruptSignature, manifest, TestImageSignatureReference, mech, TestKeyFingerprint) assert.Error(t, err) @@ -152,7 +151,7 @@ func TestVerifyDockerManifestSignature(t *testing.T) { assert.Nil(t, sig) // Invalid reference in the signature - invalidReferenceSignature, err := ioutil.ReadFile("fixtures/invalid-reference.signature") + invalidReferenceSignature, err := os.ReadFile("fixtures/invalid-reference.signature") require.NoError(t, err) sig, err = VerifyDockerManifestSignature(invalidReferenceSignature, manifest, TestImageSignatureReference, mech, TestKeyFingerprint) assert.Error(t, err) diff --git a/signature/mechanism.go b/signature/mechanism.go index 961246147..249b5a1fe 100644 --- a/signature/mechanism.go +++ b/signature/mechanism.go @@ -6,7 +6,7 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" + "io" "strings" // This code is used only to parse the data in an explicitly-untrusted @@ -82,7 +82,7 @@ func gpgUntrustedSignatureContents(untrustedSignature []byte) (untrustedContents if !md.IsSigned { return nil, "", errors.New("The input is not a signature") } - content, err := ioutil.ReadAll(md.UnverifiedBody) + content, err := io.ReadAll(md.UnverifiedBody) if err != nil { // Coverage: An error during reading the body can happen only if // 1) the message is encrypted, which is not our case (and we don’t give ReadMessage the key diff --git a/signature/mechanism_gpgme.go b/signature/mechanism_gpgme.go index c166fb32d..4c7968417 100644 --- a/signature/mechanism_gpgme.go +++ b/signature/mechanism_gpgme.go @@ -7,7 +7,6 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" "os" "github.com/proglottis/gpgme" @@ -37,7 +36,7 @@ func newGPGSigningMechanismInDirectory(optionalDir string) (signingMechanismWith // of these keys. // The caller must call .Close() on the returned SigningMechanism. func newEphemeralGPGSigningMechanism(blob []byte) (signingMechanismWithPassphrase, []string, error) { - dir, err := ioutil.TempDir("", "containers-ephemeral-gpg-") + dir, err := os.MkdirTemp("", "containers-ephemeral-gpg-") if err != nil { return nil, nil, err } diff --git a/signature/mechanism_openpgp.go b/signature/mechanism_openpgp.go index ef4e70e7f..63cb7788b 100644 --- a/signature/mechanism_openpgp.go +++ b/signature/mechanism_openpgp.go @@ -7,7 +7,7 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" + "io" "os" "path" "strings" @@ -44,7 +44,7 @@ func newGPGSigningMechanismInDirectory(optionalDir string) (signingMechanismWith } } - pubring, err := ioutil.ReadFile(path.Join(gpgHome, "pubring.gpg")) + pubring, err := os.ReadFile(path.Join(gpgHome, "pubring.gpg")) if err != nil { if !os.IsNotExist(err) { return nil, err @@ -130,7 +130,7 @@ func (m *openpgpSigningMechanism) Verify(unverifiedSignature []byte) (contents [ if !md.IsSigned { return nil, "", errors.New("not signed") } - content, err := ioutil.ReadAll(md.UnverifiedBody) + content, err := io.ReadAll(md.UnverifiedBody) if err != nil { // Coverage: md.UnverifiedBody.Read only fails if the body is encrypted // (and possibly also signed, but it _must_ be encrypted) and the signing diff --git a/signature/mechanism_test.go b/signature/mechanism_test.go index 4b5cf23dc..95f240380 100644 --- a/signature/mechanism_test.go +++ b/signature/mechanism_test.go @@ -4,7 +4,6 @@ package signature import ( "bytes" - "io/ioutil" "os" "path/filepath" "testing" @@ -21,10 +20,10 @@ const ( // fixtureVariants loads V3 and V4 signature fixture variants based on the v4 fixture path, and returns a map which makes it easy to test both. func fixtureVariants(t *testing.T, v4Path string) map[string][]byte { - v4, err := ioutil.ReadFile(v4Path) + v4, err := os.ReadFile(v4Path) require.NoError(t, err) v3Path := v4Path + "-v3" - v3, err := ioutil.ReadFile(v3Path) + v3, err := os.ReadFile(v3Path) require.NoError(t, err) return map[string][]byte{v4Path: v4, v3Path: v3} } @@ -124,7 +123,7 @@ func TestNewEphemeralGPGSigningMechanism(t *testing.T) { } // Successful import - keyBlob, err := ioutil.ReadFile("./fixtures/public-key.gpg") + keyBlob, err := os.ReadFile("./fixtures/public-key.gpg") require.NoError(t, err) mech, keyIdentities, err = NewEphemeralGPGSigningMechanism(keyBlob) require.NoError(t, err) @@ -141,7 +140,7 @@ func TestNewEphemeralGPGSigningMechanism(t *testing.T) { // Two keys: Read the binary-format pubring.gpg, and concatenate it twice. // (Using two copies of public-key.gpg, in the ASCII-armored format, works with // gpgmeSigningMechanism but not openpgpSigningMechanism.) - keyBlob, err = ioutil.ReadFile("./fixtures/pubring.gpg") + keyBlob, err = os.ReadFile("./fixtures/pubring.gpg") require.NoError(t, err) mech, keyIdentities, err = NewEphemeralGPGSigningMechanism(bytes.Join([][]byte{keyBlob, keyBlob}, nil)) require.NoError(t, err) @@ -226,13 +225,13 @@ func TestGPGSigningMechanismVerify(t *testing.T) { assertSigningError(t, content, signingFingerprint, err) // Literal packet, not a signature - signature, err := ioutil.ReadFile("./fixtures/unsigned-literal.signature") // Not fixtureVariants, the “literal data” packet does not have V3/V4 versions. + signature, err := os.ReadFile("./fixtures/unsigned-literal.signature") // Not fixtureVariants, the “literal data” packet does not have V3/V4 versions. require.NoError(t, err) content, signingFingerprint, err = mech.Verify(signature) assertSigningError(t, content, signingFingerprint, err) // Encrypted data, not a signature. - signature, err = ioutil.ReadFile("./fixtures/unsigned-encrypted.signature") // Not fixtureVariants, the “public-key encrypted session key” does not have V3/V4 versions. + signature, err = os.ReadFile("./fixtures/unsigned-encrypted.signature") // Not fixtureVariants, the “public-key encrypted session key” does not have V3/V4 versions. require.NoError(t, err) content, signingFingerprint, err = mech.Verify(signature) assertSigningError(t, content, signingFingerprint, err) @@ -240,7 +239,7 @@ func TestGPGSigningMechanismVerify(t *testing.T) { // FIXME? Is there a way to create a multi-signature so that gpgme_op_verify returns multiple signatures? // Expired signature - signature, err = ioutil.ReadFile("./fixtures/expired.signature") // Not fixtureVariants, V3 signature packets don’t support expiration. + signature, err = os.ReadFile("./fixtures/expired.signature") // Not fixtureVariants, V3 signature packets don’t support expiration. require.NoError(t, err) content, signingFingerprint, err = mech.Verify(signature) assertSigningError(t, content, signingFingerprint, err) @@ -284,19 +283,19 @@ func TestGPGSigningMechanismUntrustedSignatureContents(t *testing.T) { assert.Error(t, err) // Literal packet, not a signature - signature, err := ioutil.ReadFile("./fixtures/unsigned-literal.signature") // Not fixtureVariants, the “literal data” packet does not have V3/V4 versions. + signature, err := os.ReadFile("./fixtures/unsigned-literal.signature") // Not fixtureVariants, the “literal data” packet does not have V3/V4 versions. require.NoError(t, err) _, _, err = mech.UntrustedSignatureContents(signature) assert.Error(t, err) // Encrypted data, not a signature. - signature, err = ioutil.ReadFile("./fixtures/unsigned-encrypted.signature") // Not fixtureVariants, the “public-key encrypted session key” does not have V3/V4 versions. + signature, err = os.ReadFile("./fixtures/unsigned-encrypted.signature") // Not fixtureVariants, the “public-key encrypted session key” does not have V3/V4 versions. require.NoError(t, err) _, _, err = mech.UntrustedSignatureContents(signature) assert.Error(t, err) // Expired signature - signature, err = ioutil.ReadFile("./fixtures/expired.signature") // Not fixtureVariants, V3 signature packets don’t support expiration. + signature, err = os.ReadFile("./fixtures/expired.signature") // Not fixtureVariants, V3 signature packets don’t support expiration. require.NoError(t, err) content, shortKeyID, err := mech.UntrustedSignatureContents(signature) require.NoError(t, err) diff --git a/signature/policy_config.go b/signature/policy_config.go index 82fbb68cb..bb91cae8c 100644 --- a/signature/policy_config.go +++ b/signature/policy_config.go @@ -16,7 +16,6 @@ package signature import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -80,7 +79,7 @@ func defaultPolicyPathWithHomeDir(sys *types.SystemContext, homeDir string) stri // NewPolicyFromFile returns a policy configured in the specified file. func NewPolicyFromFile(fileName string) (*Policy, error) { - contents, err := ioutil.ReadFile(fileName) + contents, err := os.ReadFile(fileName) if err != nil { return nil, err } diff --git a/signature/policy_config_test.go b/signature/policy_config_test.go index 68890b275..936a8f16d 100644 --- a/signature/policy_config_test.go +++ b/signature/policy_config_test.go @@ -3,7 +3,6 @@ package signature import ( "bytes" "encoding/json" - "io/ioutil" "os" "path/filepath" "testing" @@ -213,7 +212,7 @@ func TestNewPolicyFromFile(t *testing.T) { func TestNewPolicyFromBytes(t *testing.T) { // Success - bytes, err := ioutil.ReadFile("./fixtures/policy.json") + bytes, err := os.ReadFile("./fixtures/policy.json") require.NoError(t, err) policy, err := NewPolicyFromBytes(bytes) require.NoError(t, err) diff --git a/signature/policy_eval_signedby.go b/signature/policy_eval_signedby.go index 26cca4759..65e825973 100644 --- a/signature/policy_eval_signedby.go +++ b/signature/policy_eval_signedby.go @@ -5,7 +5,7 @@ package signature import ( "context" "fmt" - "io/ioutil" + "os" "strings" "github.com/containers/image/v5/manifest" @@ -33,7 +33,7 @@ func (pr *prSignedBy) isSignatureAuthorAccepted(ctx context.Context, image types if pr.KeyData != nil { data = pr.KeyData } else { - d, err := ioutil.ReadFile(pr.KeyPath) + d, err := os.ReadFile(pr.KeyPath) if err != nil { return sarRejected, nil, err } diff --git a/signature/policy_eval_signedby_test.go b/signature/policy_eval_signedby_test.go index 87a3d9a5b..3f241939f 100644 --- a/signature/policy_eval_signedby_test.go +++ b/signature/policy_eval_signedby_test.go @@ -2,7 +2,6 @@ package signature import ( "context" - "io/ioutil" "os" "path" "testing" @@ -52,7 +51,7 @@ func TestPRSignedByIsSignatureAuthorAccepted(t *testing.T) { ktGPG := SBKeyTypeGPGKeys prm := NewPRMMatchExact() testImage := dirImageMock(t, "fixtures/dir-img-valid", "testing/manifest:latest") - testImageSig, err := ioutil.ReadFile("fixtures/dir-img-valid/signature-1") + testImageSig, err := os.ReadFile("fixtures/dir-img-valid/signature-1") require.NoError(t, err) // Successful validation, with KeyData and KeyPath @@ -64,7 +63,7 @@ func TestPRSignedByIsSignatureAuthorAccepted(t *testing.T) { DockerReference: "testing/manifest:latest", }) - keyData, err := ioutil.ReadFile("fixtures/public-key.gpg") + keyData, err := os.ReadFile("fixtures/public-key.gpg") require.NoError(t, err) pr, err = NewPRSignedByKeyData(ktGPG, keyData, prm) require.NoError(t, err) @@ -130,7 +129,7 @@ func TestPRSignedByIsSignatureAuthorAccepted(t *testing.T) { // because we use a temporary directory and only import the trusted keys.) pr, err = NewPRSignedByKeyPath(ktGPG, "fixtures/public-key.gpg", prm) require.NoError(t, err) - sig, err := ioutil.ReadFile("fixtures/unknown-key.signature") + sig, err := os.ReadFile("fixtures/unknown-key.signature") require.NoError(t, err) // Pass a nil pointer to, kind of, test that the return value does not depend on the image parameter.. sar, parsedSig, err = pr.isSignatureAuthorAccepted(context.Background(), nil, sig) @@ -139,7 +138,7 @@ func TestPRSignedByIsSignatureAuthorAccepted(t *testing.T) { // A valid signature of an invalid JSON. pr, err = NewPRSignedByKeyPath(ktGPG, "fixtures/public-key.gpg", prm) require.NoError(t, err) - sig, err = ioutil.ReadFile("fixtures/invalid-blob.signature") + sig, err = os.ReadFile("fixtures/invalid-blob.signature") require.NoError(t, err) // Pass a nil pointer to, kind of, test that the return value does not depend on the image parameter.. sar, parsedSig, err = pr.isSignatureAuthorAccepted(context.Background(), nil, sig) @@ -156,7 +155,7 @@ func TestPRSignedByIsSignatureAuthorAccepted(t *testing.T) { // Error reading image manifest image := dirImageMock(t, "fixtures/dir-img-no-manifest", "testing/manifest:latest") - sig, err = ioutil.ReadFile("fixtures/dir-img-no-manifest/signature-1") + sig, err = os.ReadFile("fixtures/dir-img-no-manifest/signature-1") require.NoError(t, err) pr, err = NewPRSignedByKeyPath(ktGPG, "fixtures/public-key.gpg", prm) require.NoError(t, err) @@ -165,7 +164,7 @@ func TestPRSignedByIsSignatureAuthorAccepted(t *testing.T) { // Error computing manifest digest image = dirImageMock(t, "fixtures/dir-img-manifest-digest-error", "testing/manifest:latest") - sig, err = ioutil.ReadFile("fixtures/dir-img-manifest-digest-error/signature-1") + sig, err = os.ReadFile("fixtures/dir-img-manifest-digest-error/signature-1") require.NoError(t, err) pr, err = NewPRSignedByKeyPath(ktGPG, "fixtures/public-key.gpg", prm) require.NoError(t, err) @@ -174,7 +173,7 @@ func TestPRSignedByIsSignatureAuthorAccepted(t *testing.T) { // A valid signature with a non-matching manifest image = dirImageMock(t, "fixtures/dir-img-modified-manifest", "testing/manifest:latest") - sig, err = ioutil.ReadFile("fixtures/dir-img-modified-manifest/signature-1") + sig, err = os.ReadFile("fixtures/dir-img-modified-manifest/signature-1") require.NoError(t, err) pr, err = NewPRSignedByKeyPath(ktGPG, "fixtures/public-key.gpg", prm) require.NoError(t, err) @@ -186,7 +185,7 @@ func TestPRSignedByIsSignatureAuthorAccepted(t *testing.T) { // fails. func createInvalidSigDir(t *testing.T) string { dir := t.TempDir() - err := ioutil.WriteFile(path.Join(dir, "manifest.json"), []byte("{}"), 0644) + err := os.WriteFile(path.Join(dir, "manifest.json"), []byte("{}"), 0644) require.NoError(t, err) // Creating a 000-permissions file would work for unprivileged accounts, but root (in particular, // in the Docker container we use for testing) would still have access. So, create a symlink diff --git a/signature/signature_test.go b/signature/signature_test.go index 08991532c..c3b18efed 100644 --- a/signature/signature_test.go +++ b/signature/signature_test.go @@ -2,7 +2,7 @@ package signature import ( "encoding/json" - "io/ioutil" + "os" "path/filepath" "testing" "time" @@ -300,7 +300,7 @@ func TestVerifyAndExtractSignature(t *testing.T) { }, } - signature, err := ioutil.ReadFile("./fixtures/image.signature") + signature, err := os.ReadFile("./fixtures/image.signature") require.NoError(t, err) signatureData := triple{ keyIdentity: TestKeyFingerprint, @@ -333,7 +333,7 @@ func TestVerifyAndExtractSignature(t *testing.T) { assert.Equal(t, triple{}, recorded) // Valid signature of non-JSON: asked for keyIdentity, only - invalidBlobSignature, err := ioutil.ReadFile("./fixtures/invalid-blob.signature") + invalidBlobSignature, err := os.ReadFile("./fixtures/invalid-blob.signature") require.NoError(t, err) recorded = triple{} sig, err = verifyAndExtractSignature(mech, invalidBlobSignature, recordingRules) @@ -373,7 +373,7 @@ func TestVerifyAndExtractSignature(t *testing.T) { } func TestGetUntrustedSignatureInformationWithoutVerifying(t *testing.T) { - signature, err := ioutil.ReadFile("./fixtures/image.signature") + signature, err := os.ReadFile("./fixtures/image.signature") require.NoError(t, err) // Successful parsing, all optional fields present info, err := GetUntrustedSignatureInformationWithoutVerifying(signature) @@ -386,7 +386,7 @@ func TestGetUntrustedSignatureInformationWithoutVerifying(t *testing.T) { assert.Equal(t, time.Unix(1458239713, 0), *info.UntrustedTimestamp) assert.Equal(t, TestKeyShortID, info.UntrustedShortKeyIdentifier) // Successful parsing, no optional fields present - signature, err = ioutil.ReadFile("./fixtures/no-optional-fields.signature") + signature, err = os.ReadFile("./fixtures/no-optional-fields.signature") require.NoError(t, err) // Successful parsing info, err = GetUntrustedSignatureInformationWithoutVerifying(signature) @@ -405,7 +405,7 @@ func TestGetUntrustedSignatureInformationWithoutVerifying(t *testing.T) { assert.Error(t, err) // Valid signature of non-JSON - invalidBlobSignature, err := ioutil.ReadFile("./fixtures/invalid-blob.signature") + invalidBlobSignature, err := os.ReadFile("./fixtures/invalid-blob.signature") require.NoError(t, err) _, err = GetUntrustedSignatureInformationWithoutVerifying(invalidBlobSignature) assert.Error(t, err) diff --git a/storage/storage_image.go b/storage/storage_image.go index 08ae042ac..8071e3b32 100644 --- a/storage/storage_image.go +++ b/storage/storage_image.go @@ -10,7 +10,6 @@ import ( stderrors "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" "sync" @@ -155,7 +154,7 @@ func (s *storageImageSource) HasThreadSafeGetBlob() bool { // May update BlobInfoCache, preferably after it knows for certain that a blob truly exists at a specific location. func (s *storageImageSource) GetBlob(ctx context.Context, info types.BlobInfo, cache types.BlobInfoCache) (rc io.ReadCloser, n int64, err error) { if info.Digest == image.GzippedEmptyLayerDigest { - return ioutil.NopCloser(bytes.NewReader(image.GzippedEmptyLayer)), int64(len(image.GzippedEmptyLayer)), nil + return io.NopCloser(bytes.NewReader(image.GzippedEmptyLayer)), int64(len(image.GzippedEmptyLayer)), nil } // NOTE: the blob is first written to a temporary file and subsequently @@ -167,7 +166,7 @@ func (s *storageImageSource) GetBlob(ctx context.Context, info types.BlobInfo, c } defer rc.Close() - tmpFile, err := ioutil.TempFile(tmpdir.TemporaryDirectoryForBigFiles(s.systemContext), "") + tmpFile, err := os.CreateTemp(tmpdir.TemporaryDirectoryForBigFiles(s.systemContext), "") if err != nil { return nil, 0, err } @@ -210,7 +209,7 @@ func (s *storageImageSource) getBlobAndLayerID(info types.BlobInfo) (rc io.ReadC } r := bytes.NewReader(b) logrus.Debugf("exporting opaque data as blob %q", info.Digest.String()) - return ioutil.NopCloser(r), int64(r.Len()), "", nil + return io.NopCloser(r), int64(r.Len()), "", nil } // Step through the list of matching layers. Tests may want to verify that if we have multiple layers // which claim to have the same contents, that we actually do have multiple layers, otherwise we could @@ -395,7 +394,7 @@ func (s *storageImageSource) GetSignatures(ctx context.Context, instanceDigest * // newImageDestination sets us up to write a new image, caching blobs in a temporary directory until // it's time to Commit() the image func newImageDestination(sys *types.SystemContext, imageRef storageReference) (*storageImageDestination, error) { - directory, err := ioutil.TempDir(tmpdir.TemporaryDirectoryForBigFiles(sys), "storage") + directory, err := os.MkdirTemp(tmpdir.TemporaryDirectoryForBigFiles(sys), "storage") if err != nil { return nil, errors.Wrapf(err, "creating a temporary directory") } @@ -791,7 +790,7 @@ func (s *storageImageDestination) getConfigBlob(info types.BlobInfo) ([]byte, er } // Assume it's a file, since we're only calling this from a place that expects to read files. if filename, ok := s.filenames[info.Digest]; ok { - contents, err2 := ioutil.ReadFile(filename) + contents, err2 := os.ReadFile(filename) if err2 != nil { return nil, errors.Wrapf(err2, `reading blob from file %q`, filename) } @@ -1136,7 +1135,7 @@ func (s *storageImageDestination) Commit(ctx context.Context, unparsedToplevel t delete(dataBlobs, layerBlob.Digest) } for blob := range dataBlobs { - v, err := ioutil.ReadFile(s.filenames[blob]) + v, err := os.ReadFile(s.filenames[blob]) if err != nil { return errors.Wrapf(err, "copying non-layer blob %q to image", blob) } diff --git a/storage/storage_test.go b/storage/storage_test.go index 19cd0b3e2..ea926df27 100644 --- a/storage/storage_test.go +++ b/storage/storage_test.go @@ -12,7 +12,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "os" "path/filepath" "reflect" @@ -1102,7 +1101,7 @@ func TestDuplicateBlob(t *testing.T) { if err != nil { t.Fatalf("getBlobAndLayerID(%q) returned error %v", layerInfo.Digest, err) } - _, err = io.Copy(ioutil.Discard, rc) + _, err = io.Copy(io.Discard, rc) require.NoError(t, err) rc.Close() layers = append(layers, layerID) diff --git a/tarball/tarball_src.go b/tarball/tarball_src.go index 694ad17bd..aedfdf5de 100644 --- a/tarball/tarball_src.go +++ b/tarball/tarball_src.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "runtime" "strings" @@ -87,7 +86,7 @@ func (r *tarballReference) NewImageSource(ctx context.Context, sys *types.System uncompressed = nil } // TODO: This can take quite some time, and should ideally be cancellable using ctx.Done(). - n, err := io.Copy(ioutil.Discard, reader) + n, err := io.Copy(io.Discard, reader) if err != nil { return nil, fmt.Errorf("error reading %q: %v", filename, err) } @@ -217,14 +216,14 @@ func (is *tarballImageSource) HasThreadSafeGetBlob() bool { func (is *tarballImageSource) GetBlob(ctx context.Context, blobinfo types.BlobInfo, cache types.BlobInfoCache) (io.ReadCloser, int64, error) { // We should only be asked about things in the manifest. Maybe the configuration blob. if blobinfo.Digest == is.configID { - return ioutil.NopCloser(bytes.NewBuffer(is.config)), is.configSize, nil + return io.NopCloser(bytes.NewBuffer(is.config)), is.configSize, nil } // Maybe one of the layer blobs. for i := range is.blobIDs { if blobinfo.Digest == is.blobIDs[i] { // We want to read that layer: open the file or memory block and hand it back. if is.filenames[i] == "-" { - return ioutil.NopCloser(bytes.NewBuffer(is.reference.stdin)), int64(len(is.reference.stdin)), nil + return io.NopCloser(bytes.NewBuffer(is.reference.stdin)), int64(len(is.reference.stdin)), nil } reader, err := os.Open(is.filenames[i]) if err != nil { diff --git a/tarball/tarball_transport.go b/tarball/tarball_transport.go index d407c657f..63d835530 100644 --- a/tarball/tarball_transport.go +++ b/tarball/tarball_transport.go @@ -3,7 +3,7 @@ package tarball import ( "errors" "fmt" - "io/ioutil" + "io" "os" "strings" @@ -36,7 +36,7 @@ func (t *tarballTransport) ParseReference(reference string) (types.ImageReferenc filenames := strings.Split(reference, separator) for _, filename := range filenames { if filename == "-" { - stdin, err = ioutil.ReadAll(os.Stdin) + stdin, err = io.ReadAll(os.Stdin) if err != nil { return nil, fmt.Errorf("error buffering stdin: %v", err) }